Sobes.tech
Middle

In what order are the WHERE and HAVING conditions executed in SQL queries?

sobes.tech AI

Answer from AI

In SQL queries with grouping (GROUP BY), the order of execution of conditions is as follows:

  1. FROM: Defines the data sources (tables).
  2. JOIN: Combines tables from the FROM clause.
  3. WHERE: Applies filtering to individual rows before grouping. Rows that do not meet the condition are discarded.
  4. GROUP BY: Groups the filtered rows based on specified columns.
  5. HAVING: Applies filtering to the groups created by GROUP BY. Used with aggregate functions (SUM, COUNT, AVG, etc.). Groups that do not meet the condition are discarded.
  6. SELECT: Selects columns for output (may include aggregate functions).
  7. ORDER BY: Sorts the result set.
  8. LIMIT/OFFSET: Limits the number of rows returned.

WHERE filters rows before aggregation, and HAVING filters groups after aggregation.

// Example query illustrating the order
SELECT
    category,
    COUNT(*) as total_products
FROM
    products
WHERE
    price > 10 // Filtering individual products by price
GROUP BY
    category // Grouping by categories
HAVING
    COUNT(*) > 5 // Filtering groups with more than 5 products
ORDER BY
    total_products DESC; // Sorting by the number of products in the group