Home Database SQL What are the common SQL query statements?

What are the common SQL query statements?

Oct 26, 2020 am 10:06 AM
sql query statement

Common SQL query statements include: 1. View table structure [SQL>DESC emp;]; 2. Query all columns [SQL>SELECT * FROM emp]; 3. Query specified columns [SQL>SELECT empmo ,]; 4. Query the specified row [SQL>SELECT * FROM].

What are the common SQL query statements?

Common sql query statements are:

1. Simple query statements

1. View the table structure

SQL>DESC emp;
Copy after login

2. Query all columns

SQL>SELECT * FROM emp;
Copy after login

3. Query the specified column

SQL>SELECT empmo, ename, mgr FROM emp;
Copy after login

SQL>SELECT DISTINCT mgr FROM emp; Only display items with different results

4. Query the specified row

SQL>SELECT * FROM emp WHERE job='CLERK';
Copy after login

5 . Using the arithmetic expression

SQL>SELECT ename, sal*13+nvl(comm,0)  FROM emp;
Copy after login

nvl(comm,1) means that if there is a value in comm, then nvl(comm,1)=comm; if there is no value in comm, then nvl(comm ,1)=0.

SQL>SELECT ename, sal*13 nvl(comm,0) year_sal FROM emp; (year_sal is an alias and can be sorted by alias)

SQL>SELECT * FROM emp WHERE hiredate>'01-1月-82';
Copy after login

6. Use the like operator (%, _)

% represents one or more characters, _ represents one character, [charlist] represents any single character in the character column, [^charlist] or [!charlist] is not a character Any single character in the column.

SQL>SELECT * FROM emp WHERE ename like 'S__T%';
Copy after login

7. Use In

SQL>SELECT * FROM emp WHERE job IN ('CLERK','ANALYST');
Copy after login

# in the where condition. 8. Query the statement that the field content is empty/non-empty

SQL>SELECT * FROM emp WHERE mgr IS/IS NOT NULL;
Copy after login

9. Use logical operation symbols

SQL>SELECT * FROM emp WHERE (sal>500 or job='MANAGE') and ename like 'J%';
Copy after login

10. Sort the query results by the value of the field

SQL>SELECT * FROM emp ORDER BY deptno, sal DESC;
Copy after login

(in ascending order by department , and in descending order by salary)

11. Use case ... when ... then ... end to process the query results

SQL>SELECT CASE a WHEN "original_a" THEN "New name Aa" WHEN "original_b" THEN "New name Bb" END AS XXX;

Select the a field in the table and name it XXX. When the content of a is original_a, The content is displayed as "New Name Aa".

12. Format date data

SQL>SELECT DATE_FORMAT(start_time,"%Y-%m-%d") as "时间";
Copy after login

2. Complex query

1. Data grouping (max ,min,avg,sum,count)

SQL>SELECT MAX(sal),MIN(age),AVG(sal),SUM(sal) from emp;
SQL>SELECT * FROM emp where sal=(SELECT MAX(sal) from emp));
SQL>SELEC COUNT(*) FROM emp;
Copy after login

2. group by (used to group statistics on query results) and having clause (used to limit group display results)

SQL>SELECT deptno,MAX(sal),AVG(sal) FROM emp GROUP BY deptno;
SQL>SELECT deptno, job, AVG(sal),MIN(sal) FROM emp group by deptno,job having AVG(sal)<2000;
Copy after login

Summary of data grouping:

a. Grouping functions can only appear in the selection list, having, order by clause (not in where)

b. If the select statement contains group by, having, order by at the same time, then their order is group by, having, order by.

c. If there are columns, expressions and grouping functions in the selected column, these columns and expressions must appear in the group by clause, otherwise an error will occur. That is: the column name in the SELECT clause must be a grouping column or column function

Using group by is not a prerequisite for using having.

3. Multi-table query

SQL>SELECT e.name,e.sal,d.dname FROM emp e, dept d WHERE e.deptno=d.deptno order by d.deptno;
SQL>SELECT e.ename,e.sal,s.grade FROM emp e,salgrade s WHER e.sal BETWEEN s.losal AND s.hisal;
Select a.*, b.x, c.y from a
  left outer join (Select * from tablex where condition1)b
  on a.id=b.id
  left outer join (Select * from tabley where condition2)c
  on a.id=c.id
where condition3;
Copy after login

Use the selected data as a new table to perform a left join query; from: https://q.cnblogs.com/q /67530/

4. Self-join (referring to the connection query of the same table)

SQL>SELECT er.ename, ee.ename mgr_name from emp er, emp ee where er.mgr=ee.empno;
Copy after login

5. Subquery (embedded in other sql statements) select statement, also called nested query)

5.1 Single row subquery

SQL>SELECT ename FROM emp WHERE deptno=(SELECT deptno FROM emp where ename=&#39;SMITH&#39;);
Copy after login

Query the names of people in the same department as smith in the query table. Because the return result is only one row, use "=" to connect the subquery statement

5.2 Multi-row subquery

SQL>SELECT ename,job,sal,deptno from emp WHERE job IN (SELECT DISTINCT job FROM emp WHERE deptno=10);
Copy after login

Query table for employees with the same job as department number 10 Name, job, salary, department number. Because there are multiple rows in the returned result, "IN" is used to connect the subquery statements.

The difference between in and exists: The subquery after exists() is called a correlated subquery, and it does not return the value of the list. It just returns a true or false result. The operation method is to run the main query once, and then query the corresponding results in the subquery. If it is true, it will be output, otherwise it will not be output. Then query in the subquery based on each row in the main query. The subquery after in() returns the result set. In other words, the execution order is different from exists(). The subquery first generates a result set, and then the main query goes to the result set to find a list of fields that meet the requirements. Output that meets the requirements, otherwise no output.

5.3 Use ALL

SQL>SELECT ename,sal,deptno FROM emp WHERE sal> ALL (SELECT sal FROM emp WHERE deptno=30);或SQL>SELECT ename,sal,deptno FROM emp WHERE sal> (SELECT MAX(sal) FROM emp WHERE deptno=30);
Copy after login

to query the name, salary and department number of employees whose salary is higher than that of all employees with department number 30. The above two statements are functionally the same, but in terms of execution efficiency, the function will be much higher.

5.4 Use ANY

SQL>SELECT ename,sal,deptno FROM emp WHERE sal> ANY (SELECT sal FROM emp WHERE deptno=30);或SQL>SELECT ename,sal,deptno FROM emp WHERE sal> (SELECT MIN(sal) FROM emp WHERE deptno=30);
Copy after login

to query the name and salary of employees whose salary is higher than that of any employee with department number 30 (as long as the salary is higher than that of a certain employee) and department number. The above two statements are functionally the same, but in terms of execution efficiency, the function will be much higher.

5.5 Multi-column subquery

SQL>SELECT * FROM emp WHERE (job, deptno)=(SELECT job, deptno FROM emp WHERE ename=&#39;SMITH&#39;);
Copy after login

5.6 Using subqueries in the from clause

 SQL>SELECT emp.deptno,emp.ename,emp.sal,t_avgsal.avgsal FROM emp,(SELECT emp.deptno,avg(emp.sal) avgsal FROM emp GROUP BY emp.deptno) t_avgsal where emp.deptno=t_avgsal.deptno AND emp.sal>t_avgsal.avgsal ORDER BY emp.deptno;
Copy after login

5.7 Paging query

Each row of data in the database Each has a corresponding row number, called rownum.

SQL>SELECT a2.* FROM (SELECT a1.*, ROWNUM rn FROM (SELECT * FROM emp ORDER BY sal) a1 WHERE ROWNUM<=10) a2 WHERE rn>=6;
Copy after login

To specify query columns, sort query results, etc., you only need to modify the innermost subquery.

5.8 Create a new table with query results

SQL>CREATE TABLE mytable (id,name,sal,job,deptno) AS SELECT empno,ename,sal,job,deptno FROM emp;
Copy after login

5.9 Merge query (union union, intersect intersection, union all union intersection, minus difference set)

SQL>SELECT ename, sal, job FROM emp WHERE sal>2500 UNION(INTERSECT/UNION ALL/MINUS) SELECT ename, sal, job FROM emp WHERE job=&#39;MANAGER&#39;;
Copy after login

合并查询的执行效率远高于and,or等逻辑查询。

5.10 使用子查询插入数据

SQL>CREATE TABLE myEmp(empID number(4), name varchar2(20), sal number(6), job varchar2(10), dept number(2));
Copy after login

先建一张空表;

SQL>INSERT INTO myEmp(empID, name, sal, job, dept) SELECT empno, ename, sal, job, deptno FROM emp WHERE deptno=10;
Copy after login

再将emp表中部门号为10的数据插入到新表myEmp中,实现数据的批量查询。

5.11 使用了查询更新表中的数据

SQL>UPDATE emp SET(job, sal, comm)=(SELECT job, sal, comm FROM emp where ename=&#39;SMITH&#39;) WHERE ename=&#39;SCOTT&#39;;
Copy after login

相关免费学习推荐:SQL视频教程

The above is the detailed content of What are the common SQL query statements?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
SQL: The Commands, MySQL: The Engine SQL: The Commands, MySQL: The Engine Apr 15, 2025 am 12:04 AM

SQL commands are divided into five categories in MySQL: DQL, DDL, DML, DCL and TCL, and are used to define, operate and control database data. MySQL processes SQL commands through lexical analysis, syntax analysis, optimization and execution, and uses index and query optimizers to improve performance. Examples of usage include SELECT for data queries and JOIN for multi-table operations. Common errors include syntax, logic, and performance issues, and optimization strategies include using indexes, optimizing queries, and choosing the right storage engine.

SQL and MySQL: Understanding the Core Differences SQL and MySQL: Understanding the Core Differences Apr 17, 2025 am 12:03 AM

SQL is a standard language for managing relational databases, while MySQL is a specific database management system. SQL provides a unified syntax and is suitable for a variety of databases; MySQL is lightweight and open source, with stable performance but has bottlenecks in big data processing.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

SQL: How to Overcome the Learning Hurdles SQL: How to Overcome the Learning Hurdles Apr 26, 2025 am 12:25 AM

To become an SQL expert, you should master the following strategies: 1. Understand the basic concepts of databases, such as tables, rows, columns, and indexes. 2. Learn the core concepts and working principles of SQL, including parsing, optimization and execution processes. 3. Proficient in basic and advanced SQL operations, such as CRUD, complex queries and window functions. 4. Master debugging skills and use the EXPLAIN command to optimize query performance. 5. Overcome learning challenges through practice, utilizing learning resources, attaching importance to performance optimization and maintaining curiosity.

SQL and MySQL: A Beginner's Guide to Data Management SQL and MySQL: A Beginner's Guide to Data Management Apr 29, 2025 am 12:50 AM

The difference between SQL and MySQL is that SQL is a language used to manage and operate relational databases, while MySQL is an open source database management system that implements these operations. 1) SQL allows users to define, operate and query data, and implement it through commands such as CREATETABLE, INSERT, SELECT, etc. 2) MySQL, as an RDBMS, supports these SQL commands and provides high performance and reliability. 3) The working principle of SQL is based on relational algebra, and MySQL optimizes performance through mechanisms such as query optimizers and indexes.

The Importance of SQL: Data Management in the Digital Age The Importance of SQL: Data Management in the Digital Age Apr 23, 2025 am 12:01 AM

SQL's role in data management is to efficiently process and analyze data through query, insert, update and delete operations. 1.SQL is a declarative language that allows users to talk to databases in a structured way. 2. Usage examples include basic SELECT queries and advanced JOIN operations. 3. Common errors such as forgetting the WHERE clause or misusing JOIN, you can debug through the EXPLAIN command. 4. Performance optimization involves the use of indexes and following best practices such as code readability and maintainability.

SQL in Action: Real-World Examples and Use Cases SQL in Action: Real-World Examples and Use Cases Apr 18, 2025 am 12:13 AM

In practical applications, SQL is mainly used for data query and analysis, data integration and reporting, data cleaning and preprocessing, advanced usage and optimization, as well as handling complex queries and avoiding common errors. 1) Data query and analysis can be used to find the most sales product; 2) Data integration and reporting generate customer purchase reports through JOIN operations; 3) Data cleaning and preprocessing can delete abnormal age records; 4) Advanced usage and optimization include using window functions and creating indexes; 5) CTE and JOIN can be used to handle complex queries to avoid common errors such as SQL injection.

SQL: The Language of Databases Explained SQL: The Language of Databases Explained Apr 27, 2025 am 12:14 AM

SQL is the core tool for database operations, used to query, operate and manage databases. 1) SQL allows CRUD operations to be performed, including data query, operations, definition and control. 2) The working principle of SQL includes three steps: parsing, optimizing and executing. 3) Basic usages include creating tables, inserting, querying, updating and deleting data. 4) Advanced usage covers JOIN, subquery and window functions. 5) Common errors include syntax, logic and performance issues, which can be debugged through database error information, check query logic and use the EXPLAIN command. 6) Performance optimization tips include creating indexes, avoiding SELECT* and using JOIN.

See all articles