SQL is how we ask a database for data. You tell it which columns you want, which table they live in, and any rules for filtering or summarising them, and it hands back a table of results.

In this post I'll build up from a basic query to subqueries and CTEs in Snowflake, using a Superstore-style dataset with ORDERS, CUSTOMERS and PRODUCTS tables, and a Formula 1 dataset with races, results and drivers.

Let's start with a basic query.

Every query starts with SELECT (which columns) and FROM (which table). In Snowflake the full table name is DATABASE.SCHEMA.TABLE.

SQL

SELECT
     ORDER_ID
    ,CUSTOMER_ID
FROM TIL_PLAYGROUND.SQL_COURSE.ORDERS
LIMIT 10;

This returns the order ID and customer ID for the first 10 rows of the orders table. LIMIT 10 keeps the result small, which is handy when you just want a quick look at the data.

From there you can add a few building blocks:

  • WHERE filters rows, e.g. WHERE ship_mode LIKE '%First%'
  • JOIN brings in another table on a shared key
  • GROUP BY aggregates, and HAVING filters after aggregating

Putting them together, here are customers who have spent more than 10,000:

SQL

SELECT
     C.customer_name
    ,SUM(O.sales) AS total_sales

FROM orders AS O

INNER JOIN customers AS C
    ON O.customer_id = C.customer_id
GROUP BY C.customer_name
HAVING total_sales > 10000
ORDER BY total_sales DESC;

That works when everything you need comes from one level of aggregation. But what if I want each category's sales and the total sales for the whole business on the same row, to see each category's share?

The GROUP BY splits the data by category, so it can't also give me the overall total. I need to calculate that total separately, then bring it into the query.

That's where a subquery comes in.

Subqueries

A subquery is a query in brackets, inside another query. Snowflake runs the inner one first and passes its result to the outer one.

In the SELECT: compare each row to a total

Here every category's sales sit next to the overall total, so you can see each category's share.

SQL

SELECT
     P.category
    ,ROUND(SUM(O.sales), 2) AS category_sales
    ,(SELECT ROUND(SUM(sales), 2) FROM orders) AS total_sales
FROM orders AS O
INNER JOIN products AS P
    ON O.product_id = P.product_id
GROUP BY P.category;

  • Snowflake runs the subquery in brackets first: (SELECT ROUND(SUM(sales), 2) FROM orders). It adds up every sale in the whole table and returns one number: the grand total.
  • The outer query joins ORDERS to PRODUCTS so each order knows its category, then groups by category and sums the sales for each one.
  • Because the subquery gives back just one value, Snowflake puts that same number on every row in a new column called TOTAL_SALES.

The result has one row per category (Furniture, Office Supplies, Technology), with that category's sales next to the grand total. From here you could divide one by the other to get each category's percentage of sales.

This kind is called a scalar subquery, because it returns exactly one value. If it returned more than one row, Snowflake wouldn't know which value to show and would give you an error.

In the FROM or JOIN: use a result like a table

Using the F1 data, this lists the drivers in the 2021 Monaco Grand Prix with their all-time Monaco wins. The bracketed part counts the wins, and the outer query joins to it as if it were a table called W.

SQL

SELECT
     D.forename
    ,D.surname
    ,W.wins

FROM TIL_PLAYGROUND.F1.RACES AS RA

INNER JOIN TIL_PLAYGROUND.F1.RESULTS AS R USING (raceid)
INNER JOIN TIL_PLAYGROUND.F1.DRIVERS AS D USING (driverid)

LEFT JOIN (
    SELECT R.driverid, COUNT(*) AS wins
   * FROM TILPLAYGROUND.F1.RESULTS AS R
    INNER JOIN TILPLAYGROUND.F1.RACES AS RA USING (raceid)
    WHERE R.position = 1
      AND RA.name ILIKE '%Monaco%'
    GROUP BY R.driverid
) AS W ON D.driverid = W.driverid

WHERE RA.name = 'Monaco Grand Prix'
  AND RA.year = 2021;

  • The inner query (in brackets) looks at every race result where the driver finished first (POSITION = 1) at a race with "Monaco" in its name, and counts how many wins each driver has. ILIKE is like LIKE but ignores upper and lower case, and % is a wildcard meaning "anything", so '%Monaco%' matches any race name containing Monaco.
  • AS W gives that result a short name, so the outer query can use its columns, like W.WINS. A subquery in FROM or JOIN always needs a name like this.
  • The outer query finds the drivers who raced at Monaco in 2021, then joins to W to pick up their win count.
  • LEFT JOIN keeps every driver from the outer query, even if they've never won at Monaco. Those drivers simply show NULL in the WINS column instead of disappearing from the results.

One more shortcut: USING (RACEID) means the same as ON RA.RACEID = R.RACEID. You can use it when the column you're joining on has the same name in both tables.

CTE

A CTE (Common Table Expression) is a subquery that you move to the top of the query and give a name, using WITH. You can then refer to it by name as many times as you like, and the query reads from top to bottom.

This example finds customers whose total sales are above the average customer's:

SQL

WITH customer_sales AS (
    SELECT
         customer_id
        ,SUM(sales) AS total_sales
    FROM orders
    GROUP BY customer_ID
)
SELECT
     C.customer_name
    ,CS.total_sales
    ,(SELECT ROUND(AVG(total_sales), 2) FROM customer_sales) AS avg_total_sales

FROM customer_SALES AS CS
INNER JOIN customers AS c USING (customer_id)
WHERE CS.total_sales > (SELECT AVG(total_sales) FROM customer_sales)
ORDER BY CS.total_sales DESC;

Reading it from top to bottom:

  1. WITH CUSTOMER_SALES AS ( ... ) creates a temporary result called CUSTOMER_SALES, with one row per customer and their total sales. It only exists while this query runs, so nothing gets saved to the database.
  2. The main SELECT reads from CUSTOMER_SALES as if it were a real table, and joins to CUSTOMERS to get each customer's name.
  3. The subquery in the SELECT works out the average of all those customer totals and shows it on every row, so you can compare each customer against it.
  4. The WHERE keeps only the customers whose total is higher than that average.
  5. ORDER BY ... DESC sorts the biggest spenders to the top.

Notice that the CTE and the subqueries work together here: the CTE does the heavy lifting once, and the small subqueries reuse it.

CUSTOMER_SALES is written once but used three times. Without the CTE, you'd have to copy the same SUM ... GROUP BY block into each subquery.

When to use which

  • Simple query: You need one table, or a straightforward join and aggregation
  • Subquery: You need one extra value or small result, used once.
  • CTE: You need a step used more than once, or the query is getting hard t0 read