SQL Query Explainer

Understand any SQL query in plain English — break down clauses, explain execution order, and identify potential issues.

About SQL Query Explainer

Complex SQL queries can be difficult to understand, especially for developers new to SQL or when reviewing legacy code. This explainer breaks down any SQL query into its component parts, explains what each clause does in plain English, identifies the logical execution order (which is different from the written order), and highlights potential performance issues or patterns to watch out for.

Understanding SQL execution order is crucial for writing correct queries: SQL is processed logically in this order: FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. This means you can't use a SELECT alias in a WHERE clause (WHERE processes before SELECT), but you can use it in ORDER BY (which processes after SELECT).

FAQ

What is the SQL execution order?
SQL clauses are written in one order but executed in another: 1) FROM/JOIN (identify tables), 2) WHERE (filter rows), 3) GROUP BY (group), 4) HAVING (filter groups), 5) SELECT (select columns), 6) DISTINCT (remove duplicates), 7) ORDER BY (sort), 8) LIMIT/OFFSET (paginate). This is why you cannot use a SELECT alias in a WHERE clause.
What is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY. Use WHERE to filter based on row values (WHERE price > 100). Use HAVING to filter based on aggregate values (HAVING SUM(price) > 1000). HAVING can use aggregate functions; WHERE cannot.