Snowflake SQL Tutorial 37 - Scalar Subqueries in Snowflake

Snowflake SQL · Episode 37

In this post we are going to cover scalar subqueries in Snowflake.

A subquery is just a query written inside another query. A scalar subquery is the simplest kind. It returns one row with one column, which means it returns a single value. And once it is a value, we can put it anywhere a value is allowed. A WHERE clause, the SELECT list, or in the middle of a bigger expression.

We will start by putting one in a WHERE clause and checking what it returned. Then we will look at the two ways a scalar subquery stops being scalar, because only one of those two tells us anything. And we will finish with a mistake that was left in on purpose.

Every query below was run on a real Snowflake account, and every result you see is the output it gave back.

Episode 37 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's look at the salaries we are working with

Every number on this page comes out of one column of one table. EMPLOYEES was created in Episode 1 and every post since has reused it. The column that matters today is SALARY.

So let's put it on screen, sorted, before any subquery goes near it.

The data this post works on
SELECT EMP_ID, FIRST_NAME, SALARY FROM EMPLOYEES ORDER BY SALARY;
Result8 rows · 3 columns
EMP_IDFIRST_NAMESALARY
7Sofia71400.00
4Tomas87250.00
8Grace92000.00
2Marcus96500.00
5Priya96500.00
3Lena104000.00
1Aisha118000.00
6Daniel131000.00

Eight employees. The lowest salary is 71400.00 and the highest is 131000.00.

Keep that grid in mind. One of the sections near the end of this post is a mistake that this grid would have caught, and did not, because it was on screen and nobody was reading it.

Let's put a query where a value belongs

Who earns more than average? The obvious attempt is WHERE SALARY > AVG(SALARY), and that does not work. An aggregate cannot go in a WHERE clause, because WHERE is evaluated row by row and the average is a property of the whole set.

But a value can go there. And a query in brackets that returns one row and one column is a value. So let's write it that way.

Query
SELECT EMP_ID, FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY > (SELECT AVG(SALARY) FROM EMPLOYEES)
ORDER BY SALARY DESC;
Result3 rows · 3 columns
EMP_IDFIRST_NAMESALARY
6Daniel131000.00
1Aisha118000.00
3Lena104000.00

Three rows. Daniel, Aisha and Lena earn more than the company average. The inner query ran, it produced one number, and the outer WHERE clause compared every salary against it.

So what did that subquery return?

We do not have to take the threshold on trust. Let's run the inner query on its own.

The subquery, by itself
SELECT AVG(SALARY) AS AVG_SALARY FROM EMPLOYEES;
Result1 row · 1 column
AVG_SALARY
99581.25000000

So the filter in the previous query was really SALARY > 99581.25000000. Nothing was hidden. The brackets just saved us from typing it, and from having to retype it tomorrow when somebody gets a raise.

Why not just type the number

This is the argument for a subquery over a literal. SALARY > 99581.25000000 returns the same three rows today and the wrong rows after the next hire. The subquery works the threshold out again every time the query runs.

Does it run once, or once per row?

The same subquery works in the SELECT list. Let's put the company average beside every row, and the difference beside that.

Query
SELECT FIRST_NAME,
       SALARY,
       (SELECT AVG(SALARY) FROM EMPLOYEES)          AS COMPANY_AVG,
       SALARY - (SELECT AVG(SALARY) FROM EMPLOYEES) AS DIFFERENCE
FROM EMPLOYEES
ORDER BY DIFFERENCE DESC;
Result8 rows · 4 columns
FIRST_NAMESALARYCOMPANY_AVGDIFFERENCE
Daniel131000.0099581.2500000031418.75000000
Aisha118000.0099581.2500000018418.75000000
Lena104000.0099581.250000004418.75000000
Marcus96500.0099581.25000000-3081.25000000
Priya96500.0099581.25000000-3081.25000000
Grace92000.0099581.25000000-7581.25000000
Tomas87250.0099581.25000000-12331.25000000
Sofia71400.0099581.25000000-28181.25000000

Eight rows, and the interesting column is COMPANY_AVG. It is the identical value all the way down. That repetition is our proof that the subquery ran once for the whole statement and not once per row. It does not depend on anything in the row beside it, so there is nothing to recompute. The value is worked out, and then every row is handed the same one.

The DIFFERENCE column is just arithmetic on a value, which is the point. Once the subquery is a value, every operator that works on a number works on it. Daniel comes out at 31418.75000000 and Sofia at -28181.25000000.

The other kind

A subquery that genuinely does run once per row, because it refers to a column of the outer query, is a correlated subquery. That is a different mechanism and it is written differently, and it gets Episode 41 to itself.

Now let's give the subquery its own WHERE clause

There is nothing about the inner query that restricts it to an aggregate over everything. It is a whole query, so it can have its own WHERE clause. That is how we compare each row against a subset instead of against the whole table.

Query
SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY > (SELECT AVG(SALARY) FROM EMPLOYEES WHERE DEPT_ID = 10)
ORDER BY SALARY DESC;
Result2 rows · 2 columns
FIRST_NAMESALARY
Daniel131000.00
Aisha118000.00

Two rows this time instead of three. The threshold moved, because the average of one department is not the average of the company. Let's run the inner query on its own again.

The subquery, by itself
SELECT AVG(SALARY) AS AVG_DEPT_10 FROM EMPLOYEES WHERE DEPT_ID = 10;
Result1 row · 1 column
AVG_DEPT_10
115166.66666667

A higher bar, so fewer people clear it. And the outer query did not change at all. The comparison is still SALARY > something. The inner query is the only thing that decides what that something is.

What if the subquery returns more than one row?

A scalar subquery is only scalar if it returns one row. So let's find out what happens when it returns several.

The DEPARTMENTS table is the easiest way to try this, because it holds one budget per department. Here it is again, so this page runs on its own.

Sample data for this section
-- DEPARTMENTS was created back in Episode 24, when Level 3 needed
-- a second table. This post only borrows its BUDGET column, so here it is
-- again in full - the four rows matter to the error we are about to see.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE DEPARTMENTS (
    DEPT_ID    INT,
    DEPT_NAME  VARCHAR,
    LOCATION   VARCHAR,
    BUDGET     NUMBER(12,2)
);

INSERT INTO DEPARTMENTS VALUES
    (10, 'Engineering', 'Charlotte', 2400000.00),
    (20, 'Finance',     'Charlotte', 1100000.00),
    (30, 'Marketing',   'Raleigh',    750000.00),
    (40, 'Operations',  'Raleigh',    640000.00);

Four departments, so SELECT BUDGET FROM DEPARTMENTS returns four rows. Let's put that where one value belongs.

Query — this fails
SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY > (SELECT BUDGET FROM DEPARTMENTS);
Query failed — Snowflake returned an error
090150 (22000): Single-row subquery returns more than one row.

090150, Single-row subquery returns more than one row. Snowflake could not guess which budget we meant, so it refused to guess. Nothing ran, nothing came back, and the message names the problem.

The safe failure

This is the failure you want. It is loud, it is immediate, and it is impossible to ship by accident. Keep that in mind for the next section, which is the same mistake in the other direction and produces no message at all.

Let's make it return one row

Any aggregate collapses many rows to one. So let's take MIN(BUDGET), and divide it by ten to bring it into the range salaries actually live in.

The subquery, by itself
SELECT MIN(BUDGET) AS MIN_BUDGET, MIN(BUDGET) / 10 AS MIN_BUDGET_OVER_10
FROM DEPARTMENTS;
Result1 row · 2 columns
MIN_BUDGETMIN_BUDGET_OVER_10
640000.0064000.00000000

One row, with two columns. The first is the smallest budget, 640000.00. The second is that divided by ten, 64000.00000000, and that is the value the outer query is going to compare against.

Now let's run the outer query.

Query
SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY > (SELECT MIN(BUDGET) / 10 FROM DEPARTMENTS)
ORDER BY SALARY DESC;
Result8 rows · 2 columns
FIRST_NAMESALARY
Daniel131000.00
Aisha118000.00
Lena104000.00
Marcus96500.00
Priya96500.00
Grace92000.00
Tomas87250.00
Sofia71400.00

Eight rows, because every salary in the table clears 64000.00000000. The query itself is not interesting. The fact that it runs at all is. The only thing we changed was the shape of the inner result.

And what if it returns no rows at all?

Now let's go the other way. There is no employee 999, so what does a subquery looking for one give us back? Not an error. And not an empty set either, because the surrounding statement needs a value and it gets one.

Query
SELECT (SELECT SALARY FROM EMPLOYEES WHERE EMP_ID = 999) AS NO_SUCH_EMPLOYEE;
Result1 row · 1 column
NO_SUCH_EMPLOYEE
NULL

NULL. A scalar subquery that matches nothing evaluates to NULL rather than complaining. On its own that is reasonable enough. It is what happens next that does the damage.

Let's put that same subquery in a WHERE clause.

Query
SELECT FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY > (SELECT SALARY FROM EMPLOYEES WHERE EMP_ID = 999);
Result0 rows · 2 columns
FIRST_NAMESALARY

Zero rows. The WHERE clause became SALARY > NULL, and a comparison against NULL is never true. It is unknown, and WHERE keeps only the rows where the condition is true. So every row was tested, every row came back unknown, and every row was thrown away.

And the table is untouched. The data was never the problem.

Query
SELECT COUNT(*) AS EMPLOYEE_COUNT FROM EMPLOYEES;
Result1 row · 1 column
EMPLOYEE_COUNT
8

Eight employees, exactly as before. So what we are left looking at is an empty result from a statement that reported success. No error, no warning, and nothing anywhere telling us which part of it threw our data away.

The habit this post is for

When a query returns nothing and you cannot see why, check the subqueries first. Run each one on its own and look for a NULL. A subquery whose WHERE clause has stopped matching, maybe an ID that got renumbered or a status value that got renamed, takes the entire outer query down with it and leaves no trace of having done so.

Let's put the two failures side by side

Two failures, and the same cause behind both of them. A subquery that did not return exactly one row. But there is nothing alike about how they behave.

The subquery returnsWhat Snowflake doesWhat we seeHow bad
Exactly one rowUses the valueThe result we asked for—
More than one rowRefuses: 090150An error naming the problemAnnoying, and safe
No rowsSubstitutes NULLAn empty result, no messageSilent, and wrong

The loud one cannot reach production without somebody noticing. The quiet one can sit in a scheduled report for months, returning nothing, while everybody downstream reads it as there is nothing to report.

Can we use = instead of greater-than?

We can. Any comparison operator takes a scalar subquery. = against MAX finds the top earner without sorting anything and without a LIMIT.

Query
SELECT EMP_ID, FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEES);
Result1 row · 3 columns
EMP_IDFIRST_NAMESALARY
6Daniel131000.00

Daniel, one row. But read what we actually asked for. Not give me the highest-paid employee. We asked for every employee whose salary equals this number. A subquery gives us a value, not a row, so any number of people can match it.

Let's see that happen. First, the lowest salary above 95000.

The subquery, by itself
SELECT MIN(SALARY) AS LOWEST_ABOVE_95K FROM EMPLOYEES WHERE SALARY > 95000;
Result1 row · 1 column
LOWEST_ABOVE_95K
96500.00

Now let's ask for everybody who earns exactly that.

Query
SELECT EMP_ID, FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY = (SELECT MIN(SALARY) FROM EMPLOYEES WHERE SALARY > 95000)
ORDER BY EMP_ID;
Result2 rows · 3 columns
EMP_IDFIRST_NAMESALARY
2Marcus96500.00
5Priya96500.00

Two rows. Marcus and Priya earn exactly the same, so both of them match the value and both come back. Nothing went wrong here. But if you were expecting one row, because you were thinking of MIN as the minimum row, this is where that idea breaks.

One mistake we are leaving in, because it is worth seeing

That tie demo was written wrong the first time. The intention was to show two people matching one value. The query asked for the lowest salary above 90000, and the expectation was Marcus and Priya. Here is what it gave back.

Query — the wrong threshold
SELECT EMP_ID, FIRST_NAME, SALARY
FROM EMPLOYEES
WHERE SALARY = (SELECT MIN(SALARY) FROM EMPLOYEES WHERE SALARY > 90000)
ORDER BY EMP_ID;
Result1 row · 3 columns
EMP_IDFIRST_NAMESALARY
8Grace92000.00

One row, and the wrong person. The lowest salary above 90000 is Grace on 92000.00, so the subquery returned that, and Grace is the only employee who earns it.

Snowflake did exactly what it was asked. The arithmetic was the mistake. Raising the threshold to 95000, which is the query in the previous section, is the whole fix.

And the salaries were on the page the entire time.

Result8 rows · 3 columns
The grid that already had the answer
EMP_IDFIRST_NAMESALARY
7Sofia71400.00
4Tomas87250.00
8Grace92000.00
2Marcus96500.00
5Priya96500.00
3Lena104000.00
1Aisha118000.00
6Daniel131000.00

Which is the argument for showing the source table before doing anything to it, and the reason this course opens every post that way. A result you cannot check against the input is a result you are taking on trust. And the error here was not in the SQL, so no amount of reading the SQL would have found it.

Key points

  • A subquery returning one row and one column is a value, and it can go anywhere a value can go. A WHERE clause, the SELECT list, or inside a larger expression.
  • A scalar subquery in the SELECT list runs once for the statement and not once per row, which is why every row carried the same COMPANY_AVG.
  • The inner query is a full query. It can have its own WHERE, and changing it moves the threshold without touching the outer query at all.
  • Return more than one row and Snowflake raises 090150, Single-row subquery returns more than one row. That failure is loud, immediate and safe.
  • Return no rows and the subquery evaluates to NULL. No error, no warning.
  • SALARY > NULL is unknown, never true, so a WHERE clause built on a NULL subquery discards every row and explains nothing.
  • When a query returns nothing and you cannot see why, run each subquery on its own and look for a NULL.
  • A subquery yields a value, not a row, so = (SELECT MIN(...)) returns everyone who matches that value, ties included.
  • Show the source table first. The wrong-threshold query on this page is correct SQL answering a question that was miscalculated, and only the input grid reveals it.
Next in this series

In the next post we will look at IN and NOT IN. A subquery that returns many rows is a list, and IN is how we test against one. NOT IN looks like its opposite, and with a single NULL in that list it returns nothing at all. Correct SQL, no error, and a wrong answer.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode, including the error. The EMPLOYEES and DEPARTMENTS data is invented demo data created by that script. No performance or benchmark claims are made anywhere in this series. Subquery behaviour follows the Snowflake subquery documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.