Introducing ten steps to fully understand SQL
SQLThe column introduces ten steps to completely understand SQL

Recommended (Free): SQL
Many programmers regard SQL as a scourge. SQL is one of the few declarative languages that operates completely differently from the command line languages, object-oriented programming languages, and even functional languages we are familiar with (although some people think that the SQL language is also a functional language ).
We write SQL every day and apply it in the open source software jOOQ. So I want to introduce the beauty of SQL to those friends who still have headaches about it, so this article is specially written for the following readers:
1. I will use SQL at work but I don’t know much about it. People who don’t fully understand.
2. People who are proficient in using SQL but do not understand its grammatical logic.
3. People who want to teach others SQL.
This article focuses on the SELECT sentence pattern, and other DML (Data Manipulation Language data manipulation language commands) will be introduced in other articles.
10 simple steps to fully understand SQL
1. SQL is a declarative language
First of all Keep this concept in mind: "statement". The SQL language is an example of declaring for the computer what kind of results you want to get from the raw data, rather than telling the computer how to get the results. Isn't this great?
(Translator's Note: Simply put, the SQL language declares the properties of the result set. The computer will select the data that meets the declaration from the database based on what the SQL declares, rather than traditional programming thinking. To instruct the computer how to operate.)
SELECT first_name, last_name FROM employees WHERE salary > 100000
The above example is easy to understand. We don’t care where these employee records come from. All we need is the data of those with high salaries (Translator’s Note: salary>100000) .
Where did we learn this?
If the SQL language is so simple, then what makes people "turn pale after hearing SQL"? The main reason is that we subconsciously think about problems according to the imperative programming way of thinking. It's like this: "Computer, do this step first, then that step, but before that check whether condition A and condition B are met." For example, using variables to pass parameters, using loop statements, iteration, calling functions, etc. are all thinking habits of this imperative programming.
2. SQL syntax is not executed in the syntactic order
SQL statements have a feature that confuses most people, that is: the execution order of SQL statements It is inconsistent with the grammatical order of its statements. The syntax sequence of SQL statements is:
- SELECT[DISTINCT]
- FROM
- WHERE
- GROUP BY
- HAVING
- UNION
- ORDER BY
For the convenience of understanding, not all SQL syntax structures are listed above, but it is enough to explain the syntax sequence and order of SQL statements. The execution order is completely different. Taking the above statement as an example, the execution order is:
- FROM
- WHERE
- GROUP BY
- HAVING
- SELECT
- DISTINCT
- UNION
- ORDER BY
Regarding the execution order of SQL statements, there are three things worth mentioning Things to note:
1. FROM is the first step in SQL statement execution, not SELECT. The first step for a database to execute a SQL statement is to load data from the hard disk into the data buffer so that it can be operated on. (Translator's Note: The original text is "The first thing that happens is loading data from the disk into memory, in order to operate on such data.", but this is not the case. Taking commonly used databases such as Oracle as an example, the data is extracted from the hard disk. Go to the data buffer to operate.)
2. SELECT is executed after most statements are executed. Strictly speaking, it is executed after FROM and GROUP BY. It is very important to understand this, which is why you cannot use a field in WHERE that is aliased in SELECT as a condition.
SELECT A.x + A.y AS z FROM A WHERE z = 10 -- z 在此处不可用,因为SELECT是最后执行的语句!
If you want to reuse alias z, you have two options. Either rewrite the expression represented by z:
SELECT A.x + A.y AS z FROM A WHERE (A.x + A.y) = 10
...or resort to derived tables, common data expressions, or views to avoid alias reuse. See the examples below.
3. Whether in syntax or execution order, UNION is always ranked before ORDER BY. Many people think that every UNION segment can be sorted using ORDER BY, but according to the SQL language standard and the implementation differences of SQL in each database, this is not true. Although some databases allow SQL statements to sort subqueries or derived tables, this does not mean that the sorting will remain in the sorted order after the UNION operation.
Note: Not all databases use the same parsing method for SQL statements. For example, MySQL, PostgreSQL and SQLite will not perform as mentioned in the second point above.
What did we learn?
既然并不是所有的数据库都按照上述方式执行 SQL 预计,那我们的收获是什么?我们的收获是永远要记得:SQL 语句的语法顺序和其执行顺序并不一致,这样我们就能避免一般性的错误。如果你能记住 SQL 语句语法顺序和执行顺序的差异,你就能很容易的理解一些很常见的 SQL 问题。
当然,如果一种语言被设计成语法顺序直接反应其语句的执行顺序,那么这种语言对程序员是十分友好的,这种编程语言层面的设计理念已经被微软应用到了 LINQ 语言中。
3、 SQL 语言的核心是对表的引用(table references)
由于 SQL 语句语法顺序和执行顺序的不同,很多同学会认为SELECT 中的字段信息是 SQL 语句的核心。其实真正的核心在于对表的引用。
根据 SQL 标准,FROM 语句被定义为:
<from> ::= FROM <table> [ { <comma> <table> }... ]<p>FROM 语句的“输出”是一张联合表,来自于所有引用的表在某一维度上的联合。我们们慢慢来分析:</p>
<pre class="brush:php;toolbar:false">FROM a, b
上面这句 FROM 语句的输出是一张联合表,联合了表 a 和表 b 。如果 a 表有三个字段, b 表有 5 个字段,那么这个“输出表”就有 8 ( =5+3)个字段。
这个联合表里的数据是 ab,即 a 和 b 的笛卡尔积。换句话说,也就是 a 表中的每一条数据都要跟 b 表中的每一条数据配对。如果 a 表有3 条数据, b 表有 5 条数据,那么联合表就会有 15 ( =53)条数据。
FROM 输出的结果被 WHERE 语句筛选后要经过 GROUP BY 语句处理,从而形成新的输出结果。我们后面还会再讨论这方面问题。
如果我们从集合论(关系代数)的角度来看,一张数据库的表就是一组数据元的关系,而每个 SQL 语句会改变一种或数种关系,从而产生出新的数据元的关系(即产生新的表)。
我们学到了什么?
思考问题的时候从表的角度来思考问题提,这样很容易理解数据如何在 SQL 语句的“流水线”上进行了什么样的变动。
4、 灵活引用表能使 SQL 语句变得更强大
灵活引用表能使 SQL 语句变得更强大。一个简单的例子就是 JOIN 的使用。严格的说 JOIN 语句并非是 SELECT 中的一部分,而是一种特殊的表引用语句。SQL 语言标准中表的连接定义如下:
The above is the detailed content of Introducing ten steps to fully understand SQL. For more information, please follow other related articles on the PHP Chinese website!
SQL: The Learning Curve for BeginnersApr 16, 2025 am 12:11 AMThe SQL learning curve is steep, but it can be mastered through practice and understanding the core concepts. 1. Basic operations include SELECT, INSERT, UPDATE, DELETE. 2. Query execution is divided into three steps: analysis, optimization and execution. 3. Basic usage is such as querying employee information, and advanced usage is such as using JOIN connection table. 4. Common errors include not using alias and SQL injection, and parameterized query is required to prevent it. 5. Performance optimization is achieved by selecting necessary columns and maintaining code readability.
SQL: The Commands, MySQL: The EngineApr 15, 2025 am 12:04 AMSQL 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 for Data Analysis: Advanced Techniques for Business IntelligenceApr 14, 2025 am 12:02 AMAdvanced query skills in SQL include subqueries, window functions, CTEs and complex JOINs, which can handle complex data analysis requirements. 1) Subquery is used to find the employees with the highest salary in each department. 2) Window functions and CTE are used to analyze employee salary growth trends. 3) Performance optimization strategies include index optimization, query rewriting and using partition tables.
MySQL: A Specific Implementation of SQLApr 13, 2025 am 12:02 AMMySQL is an open source relational database management system that provides standard SQL functions and extensions. 1) MySQL supports standard SQL operations such as CREATE, INSERT, UPDATE, DELETE, and extends the LIMIT clause. 2) It uses storage engines such as InnoDB and MyISAM, which are suitable for different scenarios. 3) Users can efficiently use MySQL through advanced functions such as creating tables, inserting data, and using stored procedures.
SQL: Making Data Management Accessible to AllApr 12, 2025 am 12:14 AMSQLmakesdatamanagementaccessibletoallbyprovidingasimpleyetpowerfultoolsetforqueryingandmanagingdatabases.1)Itworkswithrelationaldatabases,allowinguserstospecifywhattheywanttodowiththedata.2)SQL'sstrengthliesinfiltering,sorting,andjoiningdataacrosstab
SQL Indexing Strategies: Improve Query Performance by Orders of MagnitudeApr 11, 2025 am 12:04 AMSQL indexes can significantly improve query performance through clever design. 1. Select the appropriate index type, such as B-tree, hash or full text index. 2. Use composite index to optimize multi-field query. 3. Avoid over-index to reduce data maintenance overhead. 4. Maintain indexes regularly, including rebuilding and removing unnecessary indexes.
How to delete constraints in sqlApr 10, 2025 pm 12:21 PMTo delete a constraint in SQL, perform the following steps: Identify the constraint name to be deleted; use the ALTER TABLE statement: ALTER TABLE table name DROP CONSTRAINT constraint name; confirm deletion.
How to set SQL triggerApr 10, 2025 pm 12:18 PMA SQL trigger is a database object that automatically performs specific actions when a specific event is executed on a specified table. To set up SQL triggers, you can use the CREATE TRIGGER statement, which includes the trigger name, table name, event type, and trigger code. The trigger code is defined using the AS keyword and contains SQL or PL/SQL statements or blocks. By specifying trigger conditions, you can use the WHERE clause to limit the execution scope of a trigger. Trigger operations can be performed in the trigger code using the INSERT INTO, UPDATE, or DELETE statement. NEW and OLD keywords can be used to reference the affected keyword in the trigger code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment






