📅  最后修改于: 2023-12-03 15:20:14.204000             🧑  作者: Mango
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.
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.
The most basic SQL commands are SELECT
, INSERT
, UPDATE
, and DELETE
. Here are some examples of each:
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;
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');
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;
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;
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';
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;
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;
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!