SQL Query Order of Execution

Adina Socaci
4 min readJun 14, 2024

In SQL, the order in which you write the statements in a query does not necessarily correspond to the order in which they are executed by the database engine. Let’s take a look.

  • FROM and JOINs: The FROM clause and any JOINs are processed first to determine the data sources and how to combine them.
  • WHERE: The WHERE clause is applied to filter rows from the result of the FROM and JOIN operations.
  • GROUP BY: The GROUP BY clause is used to aggregate data by grouping rows based on one or more columns.
  • HAVING: The HAVING clause is applied to filter groups created by the GROUP BY clause.
  • SELECT: The SELECT clause specifies which columns or expressions to include in the final result set.
  • DISTINCT: The DISTINCT clause removes duplicate rows from the result set.
  • ORDER BY: The ORDER BY clause sorts the final result set by one or more columns.
  • LIMIT / OFFSET: The LIMIT or OFFSET clause is used to limit the number of rows returned or to skip a certain number of rows.

Example Query and Execution Order

Query Example

SELECT department, COUNT(employee_id) AS num_employees
FROM employees
WHERE salary > 50000
GROUP BY department…

--

--