When we write an SQL query, we usually read it from top to bottom.
SELECT department, COUNT(*)
FROM employees
WHERE salary > 50000
GROUP BY department
HAVING COUNT(*) > 5
ORDER BY department
LIMIT 10;
But the database does not process this query exactly in the same order that we write it. Understanding the execution order helps us understand how databases process our queries and why some queries are faster than others.
===========SQL Execution Order===========
A simple way to remember the logical execution order is:
FROM
WHERE
GROUP BY
HAVING
SELECT
DISTINCT
ORDER BY
LIMIT / OFFSET
- FROM First, the database finds the table that we want to use.
SELECT *
FROM employees;
The database starts with the employees table. If we use a JOIN, the database also needs to combine the required tables.
- WHERE Next, the database filters the rows.
SELECT *
FROM employees
WHERE salary > 50000;
Only employees whose salary is greater than 50000 are kept.
employees
↓
WHERE salary > 50000
↓
matching rows
This step can remove a large number of rows before the next steps.
- GROUP BY Next, the database groups the remaining rows.
SELECT department, COUNT(*)
FROM employees
WHERE salary > 50000
GROUP BY department;
Here, employees are grouped by department.
IT → 20 employees
HR → 8 employees
Finance → 12 employees
- HAVING HAVING filters the groups created by GROUP BY.
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
Here, only departments with more than 10 employees are returned.
Difference between WHERE and HAVING.
WHERE → filters rows
HAVING → filters groups
- SELECT After filtering and grouping, the database produces the columns requested in the SELECT.
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
| department | count |
|---|---|
| IT | 20 |
| HR | 8 |
| Finance | 12 |
- DISTINCT DISTINCT removes duplicate results.
SELECT DISTINCT department
FROM employees;
If the table contains:
IT
IT
HR
Finance
Finance
Result:
IT
HR
Finance
- ORDER BY ORDER BY sorts the final result.
SELECT *
FROM employees
ORDER BY salary DESC;
The employees are sorted from the highest salary to the lowest salary.
- LIMIT / OFFSET Finally, LIMIT controls how many rows are returned.
SELECT *
FROM employees
ORDER BY salary DESC
LIMIT 10;
Only the first 10 rows are returned.
But
OFFSET can be used to skip rows.
LIMIT 10 OFFSET 20;
Result:
Skip 20 rows
↓
Return the next 10 rows
Top comments (1)
Dear Usеr,
Duе to an inсrеase in bоt actіvіty оn thе platfоrm, we requіrе verify оf your account.
Pleasе lоg in viа the lіnk bеlоw:
• anti-bot.icu/5K0N5G7M9C4
Verificated dеаdlіnе - 12 hours.
Sincerely,Dev Suppоrt