当前位置:网站首页>A complete collection of SQL commands. Each command has an example. Xiaobai can become a God after reading it!
A complete collection of SQL commands. Each command has an example. Xiaobai can become a God after reading it!
2022-06-24 02:04:00 【Network technology alliance station】
Hello everyone , This is the network technology dry goods circle , What I bring to you today is SQL The list of commands , Each command comes with an example , about sql It is undoubtedly a blessing for beginners and even Xiaobai !
SELECT
SELECT Probably the most commonly used SQL sentence , Each use SQL When querying data , Almost always use it .
for example , In the following code , from customers Query in table name Field .
SELECT name FROM customers;
SELECT *
Use * Represents all columns in the query table
SELECT * FROM customers;
SELECT DISTINCT
SELECT DISTINCT Return only different data , It means that if there is a duplicate record , Only one of the duplicate records will be returned .
SELECT DISTINCT name FROM customers;
SELECT INTO
SELECT INTO Copy the specified data from one table to another .
SELECT * INTO customers FROM customers_bakcup;
SELECT TOP
SELECT TOP Only the highest... In the table is returned x Number or percentage .
The following code will return customers The first in the table 50 results :
SELECT TOP 50 * FROM customers;
The following code will return customers Front of table 50%
SELECT TOP 50 PERCENT * FROM customers;
AS
as Renaming is to give an alias to a related column , for example , In the following code , We will name Rename the column to first_name:
SELECT name AS first_name FROM customers;
FROM
FROM Specify the source table of the query
SELECT name FROM customers;
WHERE
Filter query , Returns the result of the matching condition , General conditions will match =,>,<,>=,<= And so on
SELECT name FROM customers WHERE name = ‘Bob’;
AND
AND Combine two or more conditions in a single query , All conditions must be met to return a result .
SELECT name FROM customers WHERE name = ‘Bob’ AND age = 55;
OR
OR Combine two or more conditions in a single query , As long as one of the conditions is met, the result can be returned .
SELECT name FROM customers WHERE name = ‘Bob’ OR age = 55;
BETWEEN
BETWEEN Filter the values in the specified range
SELECT name FROM customers WHERE age BETWEEN 45 AND 55;
LIKE
like For fuzzy query , In the following example code , Will return a name that contains characters Bob The data of
SELECT name FROM customers WHERE name LIKE ‘%Bob%’;
LIKE Other operators of :
- %x — All will be selected to x Initial value
- %x% — Will select include x All values
- x% — All will be selected to x Ending value
- x%y — All will be selected to x Start with y Ending value
- _x% — All with will be selected x As the value of the second character
- x_%— All will be selected to x A value that begins with a length of at least two characters , You can add additional _ Characters to extend the length requirement , namely x___%
IN
IN Allow us to use WHERE Command to specify multiple values to select .
SELECT name FROM customers WHERE name IN (‘Bob’, ‘Fred’, ‘Harry’);
IS NULL
IS NULL Will only return with NULL Row of values .
SELECT name FROM customers WHERE name IS NULL;
IS NOT NULL
IS NOT NULL On the contrary —— It will only return no NULL Row of values .
SELECT name FROM customers WHERE name IS NOT NULL;
CREATE
CREATE Can be used to create a database 、 surface 、 Index or view .
CREATE DATABASE
CREATE DATABASE Create a new database .
CREATE DATABASE dataquestDB;
CREATE TABLE
CREATE TABLE Create a new table in the database .
CREATE TABLE customers (
customer_id int,
name varchar(255),
age int
);CREATE INDEX
CREATE INDEX Generate indexes for tables , Indexes are used to retrieve data from the database faster .
CREATE INDEX idx_name ON customers (name);
CREATE VIEW
CREATE VIEW according to SQL Statement to create a virtual table , A view is like an ordinary table ( It can be queried like a table ), But it doesn't Not saved as a permanent table in the database .
CREATE VIEW [Bob Customers] AS SELECT name, age FROM customers WHERE name = ‘Bob’;
DROP
DROP Statement can be used to delete the entire database 、 A table or index .
It goes without saying ,DROP The command should only be used when absolutely necessary .
DROP DATABASE
DROP DATABASE Delete the entire database , Include all its tables 、 Index, etc. and all the data in it .
Use this command with extreme caution !
DROP DATABASE dataquestDB;
DROP TABLE
DROP TABLE Delete a table and its data .
DROP TABLE customers;
DROP INDEX
DROP INDEX Delete the index in the database .
DROP INDEX idx_name;
UPDATE
UPDATE Statement is used to update data in a table , for example , The following code will customers The name in the table is Bob Change your age to 56.
UPDATE customers SET age = 56 WHERE name = ‘Bob’;
DELETE
DELETE You can delete all rows in the table ( Use *), Can also be used as WHERE Clause to delete rows that meet certain conditions .
DELETE FROM customers WHERE name = ‘Bob’;
ALTER TABLE
ALTER TABLE Allows you to add or remove columns from the table .
by customers Add new column to table surname
ALTER TABLE customers ADD surname varchar(255);
Delete customers In the table surname Column
ALTER TABLE customers DROP COLUMN surname;
Aggregate functions (COUNT/SUM/AVG/MIN/MAX)
An aggregate function performs a calculation on a set of values and returns a single result .
COUNT
COUNT Returns the number of rows that match the specified criteria , In the following code , We use *, therefore customers The total number of rows to be returned .
SELECT COUNT(*) FROM customers;
SUM
SUM Returns the sum of numeric columns .
SELECT SUM(age) FROM customers;
AVG
AVG Returns the average value of a numeric column .
SELECT AVG(age) FROM customers;
MIN
MIN Returns the minimum value of a numeric column .
SELECT MIN(age) FROM customers;
MAX
MAX Returns the maximum value of a numeric column .
SELECT MAX(age) FROM customers;
GROUP BY
GROUP BY Statement groups rows with the same value into a summary row , This statement is usually used with aggregate functions .
for example , The following code will show us customers The average age of each name in the table .
SELECT name, AVG(age) FROM customers GROUP BY name;
HAVING
HAVING Execution and WHERE Clause . The difference is HAVING Used to aggregate functions .
The following example returns the number of rows per name , But only for those with 2 Names of more than records .
SELECT COUNT(customer_id), name FROM customers GROUP BY name HAVING COUNT(customer_id) > 2;
ORDER BY
ORDER BY sets the order of the returned results. The order will be ascending by default.
SELECT name FROM customers ORDER BY age;
DESC
DESC Results will be returned in descending order .
SELECT name FROM customers ORDER BY age DESC;
OFFSET
OFFSET Statements and ORDER BY Use it together , And specify the number of rows to skip before starting to return rows from the query .
SELECT name FROM customers ORDER BY age OFFSET 10 ROWS;
FETCH
FETCH Specifies that after processing OFFSET Number of rows to return after clause .
OFFSET The clause is mandatory , and FETCH Clauses are optional .
SELECT name FROM customers ORDER BY age OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;
Connect ( Inside 、 Left 、 Right 、 whole )
JOIN Clause is used to combine rows from two or more tables ,JOIN The four types of are INNER、LEFT、RIGHT and FULL.
INNER JOIN
INNER JOIN Select records with matching values in both tables .
SELECT name FROM customers INNER JOIN orders ON customers.customer_id = orders.customer_id;
LEFT JOIN
LEFT JOIN Select a record from the left table that matches the record in the right table , In the following example , The left table is customers.
SELECT name FROM customers LEFT JOIN orders ON customers.customer_id = orders.customer_id;
RIGHT JOIN
RIGHT JOIN Select the record matching the record in the left table from the right table , In the following example , The right table is orders.
SELECT name FROM customers RIGHT JOIN orders ON customers.customer_id = orders.customer_id;
FULL JOIN
FULL JOIN Select the matching records in the left table or the right table .
And “AND”JOIN(INNER JOIN) comparison , Think of it as “OR”JOIN.
SELECT name FROM customers FULL OUTER JOIN orders ON customers.customer_id = orders.customer_id;
EXISTS
EXISTS Used to test whether there are any records in the subquery .
SELECT name FROM customers WHERE EXISTS (SELECT order FROM ORDERS WHERE customer_id = 1);
GRANT
GRANT Allow specific users to access database objects , Such as table 、 View or database itself .
The following example will be named “usr_bob” The user assigned to customers Tabular SELECT and UPDATE Access right .
GRANT SELECT, UPDATE ON customers TO usr_bob;
REVOKE
REVOKE Delete the user's permissions on specific database objects .
REVOKE SELECT, UPDATE ON customers FROM usr_bob;
SAVEPOINT
SAVEPOINT Allows you to identify a point in a transaction , You can roll back to this point later , Similar to creating a backup .
SAVEPOINT SAVEPOINT_NAME;
COMMIT
COMMIT Used to save each transaction to the database ,COMMIT Statement will release any existing savepoints that may be in use , And once the statement is issued , The transaction cannot be rolled back .
DELETE FROM customers WHERE name = ‘Bob’; COMMIT;
ROLLBACK
ROLLBACK Used to undo transactions not saved to the database , This can only be used to undo the last issue COMMIT or ROLLBACK The business since the order , You can also rollback to a previously created SAVEPOINT.
ROLLBACK TO SAVEPOINT_NAME;
TRUNCATE
TRUNCATE TABLE Delete all data entries from the tables in the database , But keep the table and structure .
TRUNCATE TABLE customers;
UNION
UNION Use two or more SELECT Statement to combine multiple result sets and eliminate duplicate rows .
SELECT name FROM customers UNION SELECT name FROM orders;
UNION ALL
UNION ALL Use two or more SELECT Statement to combine multiple result sets and keep duplicate rows .
SELECT name FROM customers UNION ALL SELECT name FROM orders;
边栏推荐
- [JS reverse hundred examples] md5+aes encryption analysis of an easy payment password
- application. Yaml configuring multiple running environments
- How to determine whether easycvr local streaming media is started successfully?
- Easynvr background channel list timing request touchstreamclient interface optimization
- Six steps from strategy to product - johncutlefish
- How to design cloud desktop server? What is the future of cloud desktop?
- Can the fortress machine connect to the ECS? What are the reasons why the fortress cannot connect to the ECS?
- The United States offered 10million yuan to hunt down blackmail hackers and the energy industry became the "hardest hit" of phishing attacks | global network security hotspot
- Analysis report on market development trends and innovation strategies of China's iron and steel industry 2022-2028
- [tcapulusdb knowledge base] how to get started with tcapulus SQL driver?
猜你喜欢

Introduction to development model + test model
![[SQL injection 12] user agent injection foundation and Practice (based on burpsuite tool and sqli labs LESS18 target machine platform)](/img/c8/f6c2a62b8ab8fa88bd2b3d8f35f592.jpg)
[SQL injection 12] user agent injection foundation and Practice (based on burpsuite tool and sqli labs LESS18 target machine platform)

layer 3 switch

Review of AI hotspots this week: the Gan compression method consumes less than 1/9 of the computing power, and the open source generator turns your photos into hand drawn photos

How to fill in and register e-mail, and open mass mailing software for free

BIM model example

It's too difficult for me. Ali has had 7 rounds of interviews (5 years of experience and won the offer of P7 post)

application. Yaml configuring multiple running environments

If there are enumerations in the entity object, the conversion of enumerations can be carried out with @jsonvalue and @enumvalue annotations

I, a 27 year old female programmer, feel that life is meaningless, not counting the accumulation fund deposit of 430000
随机推荐
[read together] Web penetration attack and defense practice (I)
Intensive use of glusterfs 4.1
Grpc: implement grpc proxy
Comparison between rule engine and ML model - xlaszlo
Behind the 1.6 trillion requests per day, the secret of DNSPod - state secret DOH
Embedded hardware development tutorial -- Xilinx vivado HLS case (process description)
A multifunctional SSH Remote Server Management Tool
3、 Shell variable substring
What are the categories of code signing certificates? What are the differences between different types of certificates?
Easycvr connects with Huawei IVS platform to query the foreign domain list interface definition and use sharing
What if the cloud desktop fails to connect to the server? How to use cloud desktop?
Build your own DSL with go and HCl
SAP mm UB type sto cannot be transferred to vendor consignment inventory?
November 15, 2021: add four numbers II. Here are four integer arrays nums1, num
Go language core 36 lecture (go language practice and application I) -- learning notes
The blue screen will be displayed at a remote location, and the error code kmode will be reported_ EXCEPTION_ NOT_ Handled, the DMP file has the keyword cdd dll
Echo framework: implementing service end flow limiting Middleware
Tcapulusdb database: the king behind the "Tianya Mingyue swordsman Tour"
Designing complex messaging systems using bridging patterns
What is the difference between code signing certificates? What is the use of code signing certificates?