SQL Execution Order
A super useful SQL concept you won't learn during your initial data career: SQL Execution Order. What happens when a sql is executed?
SQL, or Structured Query Language, is a declarative language and let's us specify what data should be retrieved from a database using a high level syntax rather worry about how.
The simple SQL query structure is usually composed of:
SELECT
DISTINCT <column/s>
FROM
<database_table>
WHERE
<some_column> = <filter_condition>
GROUP BY
<some_column>
HAVING
<some_logic>
ORDER BY
<some_column> ASC/DESC
LIMIT <number>;
But does it execute in the same order? No! The execution order depends on the query syntax but usually it follows a logical sequence.
FROM: Determines the tables to query. Any joins between tables happen here.
WHERE: Filters the rows based on specified conditions before any grouping or aggregations.
GROUP BY: Groups rows that have the same values in specified columns.
HAVING: Filters groups created by GROUP BY based on aggregate functions (like COUNT, SUM, etc.)
SELECT: Selects the columns or expressions to return in the query result.
DISTINCT: Removes duplicate rows from the result set.
ORDER BY: Sorts the result set based on specified columns or expressions.
LIMIT: Limits the number of rows returned
pic courtesy ByteByteGo