Header Ads

Understanding execution order of SQL queries

Before you can optimize SQL queries, you must understand their order of execution!

Understanding execution order of SQL queries

The order of execution is different from how you write it, here's the actual order:

1️⃣ FROM: Determines the tables of interest

2️⃣ JOIN: Joins the tables of interest as per specification and sets up the base data.

2️⃣ WHERE: Applies a filter to the rows returned from the FROM clause. It restricts the result set to only those rows that meet a specified condition

3️⃣ GROUP BY: Groups rows that have the same values in specified columns. It is often used with aggregate functions ( eg. COUNT, MAX, MIN, SUM, AVG) to perform calculations on each group.

4️⃣ HAVING: Similar to the WHERE clause, but it is used to filter groups based on aggregate functions. It is applied after the GROUP BY clause.

5️⃣ SELECT: Used to specify the columns from the filtered results to display in the query's result set. It can include column names, aggregate functions, and expressions.

6️⃣ ORDER BY: Sorts the result set returned by the query in ascending (ASC) or descending (DESC) order based on one or more columns.

7️⃣ LIMIT: Restricts the number of rows returned by the query.

Powered by Blogger.