Mike's Notes
Level Up Coding is a great visual reference.
Resources
- https://blog.levelupcoding.com/
- https://blog.levelupcoding.com/p/luc-78-cap-theorem-explained-in-simple-terms
- https://www.linkedin.com/posts/nikkisiapno_things-every-developer-should-know-sql-activity-7306256944128761858-WDXn/
References
Repository
- Home >
Last Updated
22/03/2025
How Does SQL Execution Order Work, and Why is it so Important?
A SQL query executes its statements in the following order:
- FROM / JOIN
- WHERE
- GROUP BY
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- LIMIT / OFFSET
The techniques you implement at each step help speed up the following steps. This is why it's important to know their execution order. To maximize efficiency, focus on optimizing the steps earlier in the query.
With that in mind, let's take a look at some optimization tips:
1) Maximise the WHERE clause
This clause I executed early, so it's a good opportunity to reduce the size of your data set before the rest of the query is processed.
2) Filter your rows before a JOIN
Although the FROM/JOIN occurs first, you can still limit the rows. To limit the number of rows you are joining, use a subquery in the FROM statement instead of a table.
3) Use WHERE over HAVING
The HAVING clause is executed after WHERE & GROUP BY. This means you're better off moving any appropriate conditions to the WHERE clause when you can.
4) Don't confuse LIMIT, OFFSET, and DISTINCT for optimization techniques
It's easy to assume that these would boost performance by minimizing the data set, but this isn’t the case. Because they occur at the end of the query, they make little to no impact on its performance.
If you want to create efficient queries, it's a good idea to understand how things work under the hood otherwise your efforts may be wasted. While these tips work best in most cases, you should consider your unique use case when choosing the best course of action.
No comments:
Post a Comment