SQL Query Execution Order

Deepshika

How You can Explain Your Project In An Interview?

SQL Query Execution Order

1️⃣ FROM

This is where it all begins. SQL starts by identifying the tables involved and establishing relationships through joins if needed.

Example: FROM employees

2️⃣ WHERE

Next, it filters rows based on specified conditions.

Example: WHERE salary > 50000

3️⃣ GROUP BY

After filtering, SQL groups rows that share a specified column’s value.

Example: GROUP BY department

4️⃣ HAVING

This is similar to WHERE but operates on groups created by GROUP BY, allowing for group-level filtering.

Example: HAVING COUNT(*) > 10

5️⃣ SELECT

Now, SQL identifies which columns or calculations to return.

Example: SELECT department, AVG(salary)

6️⃣ DISTINCT

This step removes duplicate rows from the result set.

Example: SELECT DISTINCT department

7️⃣ ORDER BY

Finally, SQL orders the result set based on specified columns.

Example: ORDER BY AVG(salary) DESC

8️⃣ LIMIT/OFFSET

If you need to restrict the number of rows returned or paginate results, this comes last.

Example: LIMIT 10 OFFSET 20

Putting It All Together: Consider this query:

“SELECT department, AVG(salary)

FROM employees

WHERE salary > 50000

GROUP BY department

HAVING COUNT(*) > 10

ORDER BY AVG(salary) DESC

LIMIT 10 OFFSET 20;

Step 1️⃣: Identify tables from employees.

Step 2️⃣: Filter rows where salary > 50000.

Step 3️⃣: Group rows by department.

Step 4️⃣: Filter groups having more than 10 rows.

Step 5️⃣: Select the department and the average salary for each group.

Step 6️⃣: No duplicates to remove here, as DISTINCT is not used.

Step 7️⃣: Order results by average salary in descending order.

Step 8️⃣: Return the 21st to 30th rows from the ordered result.

By understanding this order, you can write more efficient queries and troubleshoot why your query isn’t returning the expected results.