The order of SQL execution

The order of SQL execution follows a specific logical sequence, regardless of how the SQL query is written. Here’s the general execution order of SQL clauses:

  1. FROM – This is the first step where the tables or views are identified and joined (if applicable).
  2. ON – If you’re using JOIN, the ON condition is evaluated to establish how the tables are joined.
  3. WHERE – Filters the rows based on the condition provided.
  4. GROUP BY – Groups the result set by one or more columns.
  5. HAVING – Filters the results after the grouping has been applied (like WHERE, but it works on aggregated results).
  6. SELECT – After grouping and filtering, the columns specified in the SELECT clause are determined.
  7. DISTINCT – Removes duplicate rows from the results (if specified).
  8. ORDER BY – Sorts the results based on the specified columns.
  9. LIMIT / OFFSET – Limits the number of rows returned (if applicable).

Visualizing the SQL Execution Order:

sqlCopy codeSELECT column_list
FROM table
JOIN another_table ON condition
WHERE condition
GROUP BY column
HAVING condition
ORDER BY column
LIMIT number;
  • 1. FROM: Start by determining which tables to use.
  • 2. ON: If JOIN is used, establish the join condition.
  • 3. WHERE: Apply filters to rows.
  • 4. GROUP BY: Group rows into aggregate sets.
  • 5. HAVING: Apply conditions to the grouped results.
  • 6. SELECT: Choose the columns to include in the final output.
  • 7. DISTINCT: Remove duplicates (if used).
  • 8. ORDER BY: Sort the results.
  • 9. LIMIT/OFFSET: Restrict the number of rows returned.

Example:

sqlCopy codeSELECT department, COUNT(*) AS employee_count
FROM employees
WHERE salary > 50000
GROUP BY department
HAVING COUNT(*) > 1
ORDER BY employee_count DESC;

Execution Order:

  1. FROM: employees table is accessed.
  2. WHERE: Only employees with a salary greater than 50,000 are considered.
  3. GROUP BY: The remaining rows are grouped by department.
  4. HAVING: Only departments with more than one employee are included.
  5. SELECT: The department and employee_count are selected.
  6. ORDER BY: Results are ordered by employee_count in descending order.

Understanding this order helps in writing correct and efficient SQL queries.

Leave a Reply

Your email address will not be published. Required fields are marked *

Deprecated: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in /var/www/html/wp-includes/formatting.php on line 4720