If you are learning Snowflake or SQL for the first time, it can be hard to grasp the execution order and remember it. This blog will help you understand how SQL queries are processed step by step, with an example and mnemonic to remember by.
The Execution Order
When writing SQL queries, the order in which different clauses are executed is different from how they are written. Here is the correct order of execution:
SELECT – Choose the required columns.
FROM – Identify the dataset (table) to query.
JOIN (ON) – Combine data from multiple tables based on a common key.
WHERE – Filter the data before aggregation.
GROUP BY – Group the filtered data.
HAVING – Filter the grouped data.
ORDER BY – Sort the final result.
LIMIT – Restrict the number of rows displayed.
Example Query (Using the Superstore Sales Dataset)
Let’s say we want to retrieve total sales for each region, along with the associated regional manager, only for regions where total sales exceed $500,000. The results should be sorted in descending order of sales and limited to the top 5 regions.
SELECT
r.Region,
r.Regional_Manager,
SUM(s.Sales) AS Total_Sales
FROM Sales s
JOIN Regions r ON s.Region = r.Region
WHERE s.Order_Date >= '2023-01-01'
GROUP BY r.Region, r.Regional_Manager
HAVING SUM(s.Sales) > 500000
ORDER BY Total_Sales DESC
LIMIT 5;
Explanation of the Example
- SELECT – Extracts the required columns:
Region
,Regional_Manager
, and the calculatedTotal_Sales
. - FROM Sales s – Retrieves data from the
Sales
table. - JOIN Regions r ON s.Region = r.Region – Joins the
Sales
table with theRegions
table using theRegion
column. - WHERE s.Order_Date >= '2023-01-01' – Filters only sales records from 2023 onward.
- GROUP BY r.Region, r.Regional_Manager – Groups data by region and regional manager.
- HAVING SUM(s.Sales) > 500000 – Filters grouped results to include only regions where total sales exceed $500,000.
- ORDER BY Total_Sales DESC – Sorts the results in descending order of total sales.
- LIMIT 5 – Restricts the output to the top 5 regions.
Remember it like this
If you struggle to remember the order, use this mnemonic:
Some Friendly Jellyfish Wander Gracefully Holding Opal Lanterns
(Select → From → Join → Where → Group By → Having → Order By → Limit)
Happy querying! 🚀