📜  Sql cheetsheet - SQL (1)

📅  最后修改于: 2023-12-03 15:20:14.204000             🧑  作者: Mango

SQL Cheatsheet - SQL

SQL (Structured Query Language) is a programming language designed for managing and manipulating relational databases. In this cheatsheet, we will cover the basics of SQL queries in order to help you get started.

Connecting to a Database

Before you can begin querying a database, you need to establish a connection to it using a database management system (DBMS). Here's an example of connecting to a MySQL database using the mysql command-line client:

mysql -h hostname -u username -p password

For other DBMSs, the command may be different.

Basic SQL Commands

The most basic SQL commands are SELECT, INSERT, UPDATE, and DELETE. Here are some examples of each:

SELECT

The SELECT command is used to retrieve data from a database. Here's an example of selecting all columns from a table called users:

SELECT * FROM users;
INSERT

The INSERT command is used to insert new data into a table. Here's an example of inserting a new user into the users table:

INSERT INTO users (username, email, password)
VALUES ('johndoe', 'johndoe@example.com', 'password123');
UPDATE

The UPDATE command is used to update existing data in a table. Here's an example of updating the password for the user with the ID of 1:

UPDATE users SET password = 'newpassword123' WHERE id = 1;
DELETE

The DELETE command is used to delete data from a table. Here's an example of deleting the user with the ID of 1:

DELETE FROM users WHERE id = 1;
Filtering Data

You can filter data returned from a SELECT query by using the WHERE clause. Here's an example of selecting only the rows from the users table where the email is 'johndoe@example.com':

SELECT * FROM users WHERE email = 'johndoe@example.com';
Sorting Data

You can sort data returned from a SELECT query using the ORDER BY clause. Here's an example of selecting all the rows from the users table and sorting them by username:

SELECT * FROM users ORDER BY username;
Joining Tables

You can join multiple tables together in a query using the JOIN keyword. Here's an example of joining the users and orders tables together based on the user_id column:

SELECT * FROM users JOIN orders ON users.id = orders.user_id;
Conclusion

This SQL cheatsheet should get you started with the basic commands and concepts of SQL. However, SQL is a powerful language and there's much more to learn. Practice and experimentation will help you become a pro at querying databases!