Snowflake SQL Tutorial 11 - 7 divided by 2 Is NOT 3 - Operators, Precedence & Concatenation in Snowflake

Snowflake SQL · Episode 11

In this post we are going to cover the operators in Snowflake.

An operator is a symbol that does something to a value. + adds, * multiplies, % gives us a remainder, and || sticks two pieces of text together. We already met the comparison operators in episode 3, and AND, OR and NOT in episode 5. This post is about the rest of them.

We will start with the four arithmetic operators, then look at what 7 / 2 actually returns, then the order Snowflake applies operators in, and then gluing text together. The last two sections are the ones worth slowing down for: a NULL that takes a whole string with it, and an alias that will not compile.

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

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

Let's create some sample data

Everything on this page runs against one small table called EMPLOYEES. If you followed the earlier posts you already have it. If not, the script below creates it and fills it.

Copy this into a Snowflake worksheet and run it once. Then you can run every query on this page yourself.

Sample data — run once
-- Creates the EMPLOYEES table used by every episode in this series.
-- Run it once; every later episode can reuse it.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;

CREATE OR REPLACE TABLE EMPLOYEES (
    EMP_ID          INT,
    FIRST_NAME      VARCHAR,
    LAST_NAME       VARCHAR,
    EMAIL           VARCHAR,
    DEPT_ID         INT,
    MANAGER_ID      INT,
    SALARY          NUMBER(10,2),
    COMMISSION_PCT  NUMBER(4,2),
    HIRE_DATE       DATE
);

INSERT INTO EMPLOYEES VALUES
    (1, 'Aisha',  'Khan',      'aisha.khan@example.com',      10,    6, 118000.00, NULL,  '2019-03-11'),
    (2, 'Marcus', 'Reid',      'marcus.reid@example.com',     10,    6,  96500.00, NULL,  '2021-07-01'),
    (3, 'Lena',   'Fischer',   'lena.fischer@example.com',    20,    6, 104000.00, 0.05,  '2018-01-22'),
    (4, 'Tomas',  'Novak',     'tomas.novak@example.com',     20,    3,  87250.00, NULL,  '2022-09-05'),
    (5, 'Priya',  'Raman',     'priya.raman@example.com',     30,    6,  96500.00, 0.10,  '2020-11-17'),
    (6, 'Daniel', 'O''Connor', 'daniel.oconnor@example.com',  10, NULL, 131000.00, NULL,  '2016-05-30'),
    (7, 'Sofia',  'Marino',    'sofia.marino@example.com',    30,    5,  71400.00, 0.08,  '2023-02-13'),
    (8, 'Grace',  'Lin',       'grace.lin@example.com',     NULL,    6,  92000.00, NULL,  '2021-04-19');

A few of those columns do all the work here. SALARY is where the arithmetic happens, and its declared type matters for the very first result. It is a number with two decimal places. FIRST_NAME and LAST_NAME are the two we will glue together with the string operator. DEPT_ID is where the NULL at the end of this page comes from.

Let's start with add, subtract, multiply and divide

Let's put the four arithmetic operators on the same column, side by side, so we can compare them on one row rather than four screens apart. We add five thousand, subtract five thousand, multiply by two and divide by two.

Query
SELECT FIRST_NAME, SALARY, SALARY + 5000 AS ADDED, SALARY - 5000 AS SUBTRACTED, SALARY * 2 AS MULTIPLIED, SALARY / 2 AS DIVIDED FROM EMPLOYEES;
Result8 rows · 6 columns · scroll →
FIRST_NAMESALARYADDEDSUBTRACTEDMULTIPLIEDDIVIDED
Aisha118000.00123000.00113000.00236000.0059000.00000000
Marcus96500.00101500.0091500.00193000.0048250.00000000
Lena104000.00109000.0099000.00208000.0052000.00000000
Tomas87250.0092250.0082250.00174500.0043625.00000000
Priya96500.00101500.0091500.00193000.0048250.00000000
Daniel131000.00136000.00126000.00262000.0065500.00000000
Sofia71400.0076400.0066400.00142800.0035700.00000000
Grace92000.0097000.0087000.00184000.0046000.00000000

The values are the obvious ones. The interesting part is the number of decimal places, and that is worth reading column by column rather than row by row.

ADDED, SUBTRACTED and MULTIPLIED all came back with the same two decimal places as SALARY itself. DIVIDED did not. It came back with eight.

What this page claims, and what it does not

Division widened the scale of the result. The other three operators left it alone.
That is as far as this page will go, deliberately. There is no rule here for exactly how much division widens by, because that is scale arithmetic this series has not checked closely enough to state as fact. What is on offer is the observation, with the grid above it: division changes the shape of your number.

It matters in two places. If we are formatting that figure for a report, the trailing zeros are ours to deal with. And if we compare it to a fixed-scale column further down a pipeline, the two sides no longer have the same shape.

Now let's put a minus sign in front of one value

Let's write -SALARY on its own and see what comes back.

Query
SELECT FIRST_NAME, SALARY, -SALARY AS NEGATED FROM EMPLOYEES;
Result8 rows · 3 columns
FIRST_NAMESALARYNEGATED
Aisha118000.00-118000.00
Marcus96500.00-96500.00
Lena104000.00-104000.00
Tomas87250.00-87250.00
Priya96500.00-96500.00
Daniel131000.00-131000.00
Sofia71400.00-71400.00
Grace92000.00-92000.00

Every salary came back negative. A - in front of a single value negates it rather than subtracting anything, so it is worth keeping separate in your head from the - we used above.

Now let's try 7 / 2

Next a query with no table in it at all. Three expressions on literal numbers. That is the fastest way there is to settle an argument about an operator.

Query
SELECT 7 / 2 AS DIV, 7 % 2 AS REM, FLOOR(7 / 2) AS FLOORED;
Result1 row · 3 columns
DIVREMFLOORED
3.50000013

Let's read that grid one column at a time, because each column is a different operator and they are easy to blur together:

  • DIV is 7 / 2. The division operator returned 3.500000 — the decimal, with the half intact.
  • REM is 7 % 2. The modulo operator returned 1, which is the remainder.
  • FLOORED is FLOOR(7 / 2). FLOOR returned 3 — and FLOOR is the only thing in that row that produced 3.

If you have written Python 2, C or Java, you carry an instinct that dividing one whole number by another gives you a whole number and quietly discards the rest. That instinct is wrong in Snowflake. / on two integer literals gave back the fractional part.

That is mostly good news. The off-by-a-half bug people port in from other languages does not happen here. But it also means that if we actually wanted the whole number, we have to ask for it. The asking is FLOOR. The remainder we get with %.

Worth knowing in both directions

This cuts both ways when you port a query out of Snowflake, or in from somewhere else. The same expression that gives a decimal here may truncate in the language or the database you move it to, and nothing will raise an error — you will just get a slightly different number.

Now let's look at % and MOD()

The modulo operator has a twin. Let's put MOD(EMP_ID, 2) next to EMP_ID % 2 in one result, so there is no doubt about it.

Query
SELECT FIRST_NAME, EMP_ID, MOD(EMP_ID, 2) AS MOD_FN, EMP_ID % 2 AS MOD_OP FROM EMPLOYEES;
Result8 rows · 4 columns
FIRST_NAMEEMP_IDMOD_FNMOD_OP
Aisha111
Marcus200
Lena311
Tomas400
Priya511
Daniel600
Sofia711
Grace800

MOD_FN and MOD_OP are identical, value for value. Same operation, two spellings. Pick the one that reads better to you and then be consistent about it. A file that uses both is a file that makes its reader wonder what the difference is.

What it is for

MOD(x, 2) is the standard way to ask is this number even? — the answer is 0 for even and 1 for odd, which is exactly the pattern in that grid.

Now let's see which operator goes first

The same three numbers, written twice. The only difference between the two columns is a pair of brackets.

Query
SELECT 2 + 3 * 4 AS NO_PARENS, (2 + 3) * 4 AS WITH_PARENS;
Result1 row · 2 columns
NO_PARENSWITH_PARENS
1420

Two different answers from three identical numbers.

NO_PARENS is what we get when the multiplication happens first. 3 * 4 is 12, plus 2. That is the default, and it is the same rule you were taught at school. Multiply and divide before you add and subtract.

WITH_PARENS is what we get when the brackets force the addition to happen first. 2 + 3 is 5, times 4.

The grid above shows one pairing, multiplication before addition. For the operators on this page, the documentation sets the order out like this:

Applied firstOperators
1anything inside ( )
2a unary - or + on one value
3*   /   %
4+   -

The advice is unglamorous and it is still the right advice. If there is any doubt at all, put the brackets in. They cost nothing at runtime. Nobody reading your query has ever been confused by a bracket that did not need to be there. Plenty of people have been confused by one that was missing.

Let's glue some text together

The concatenation operator is two pipe characters, and it means stick these together. Let's join the first name and the last name.

Query
SELECT FIRST_NAME || ' ' || LAST_NAME AS FULL_NAME FROM EMPLOYEES;
Result8 rows · 1 column
FULL_NAME
Aisha Khan
Marcus Reid
Lena Fischer
Tomas Novak
Priya Raman
Daniel O'Connor
Sofia Marino
Grace Lin

The ' ' in the middle is a literal space. It is there because concatenation adds nothing of its own. Leave it out and the two names run together.

There is also a function that does the same job. Let's run that one too.

Query
SELECT CONCAT(FIRST_NAME, ' ', LAST_NAME) AS FULL_NAME FROM EMPLOYEES;
Result8 rows · 1 column
FULL_NAME
Aisha Khan
Marcus Reid
Lena Fischer
Tomas Novak
Priya Raman
Daniel O'Connor
Sofia Marino
Grace Lin

Identical output. It is the same story as % and MOD(). Two spellings, one operation. Pick one and stay with it.

Now let's put a number in the middle of some text

SALARY is a number column, and there is no conversion function anywhere in the next query.

Query
SELECT FIRST_NAME || ' earns ' || SALARY AS SENTENCE FROM EMPLOYEES;
Result8 rows · 1 column
SENTENCE
Aisha earns 118000.00
Marcus earns 96500.00
Lena earns 104000.00
Tomas earns 87250.00
Priya earns 96500.00
Daniel earns 131000.00
Sofia earns 71400.00
Grace earns 92000.00

Snowflake converted the number to text on its own. Now notice what it did not do. It kept the column's own two decimal places. What we get is the raw column formatting, not something tidied up for a reader.

Formatting is a separate job

If you want thousands separators, a currency symbol or a rounded figure in that sentence, you have to format it yourself. That is the TO_CHAR / TO_VARCHAR family, later in the course.

Now let's see what one NULL does to a whole string

Here is the same operator building a label out of a name, a slash and a department. It is the kind of thing people write to make a key out of two columns.

Query
SELECT FIRST_NAME, DEPT_ID, FIRST_NAME || '/' || DEPT_ID AS WITH_NULL FROM EMPLOYEES;
Result8 rows · 3 columns
FIRST_NAMEDEPT_IDWITH_NULL
Aisha10Aisha/10
Marcus10Marcus/10
Lena20Lena/20
Tomas20Tomas/20
Priya30Priya/30
Daniel10Daniel/10
Sofia30Sofia/30
GraceNULLNULL

Most of that grid is what we expected. Now look at the row for Grace, who has no department.

Her WITH_NULL is not Grace/. It is not Grace/NULL. The entire value is NULL, and her name went with it.

That is episode 6 again, in a new place. Anything combined with a NULL gives us a NULL, and concatenation is no exception to it.

The one that eats rows quietly

If you build keys, labels or display strings this way, wrap the nullable part in COALESCE. Otherwise you lose whole values — not the missing piece, the whole value — and no error tells you it happened. A join or a lookup on that key then quietly misses the row.

One last thing: MINUS is a reserved word

This one is a mistake this episode made while it was being written. The obvious alias for a subtraction is the word MINUS, so let's try it.

Query — does not compile
-- The version that does not compile: MINUS is a reserved word.
SELECT FIRST_NAME,
       SALARY - 5000 AS MINUS
FROM EMPLOYEES;

That is a compilation error. MINUS is a reserved word in Snowflake, because it is the set operator, the synonym for EXCEPT. There is no result pane under that query, because the failure was not captured for this episode. It is the author's account of what happened, not a grid this page can show you.

The fix is the one that was captured, and it is double quotes.

Query
SELECT FIRST_NAME, SALARY - 5000 AS "MINUS" FROM EMPLOYEES;
Result8 rows · 2 columns
FIRST_NAMEMINUS
Aisha113000.00
Marcus91500.00
Lena99000.00
Tomas82250.00
Priya91500.00
Daniel126000.00
Sofia66400.00
Grace87000.00

Inside double quotes it is just a name again, exactly like the quoted aliases in episode 10. It comes with the same catch, because a quoted identifier is case-sensitive and has to be spelled identically everywhere you refer to it.

How to recognise it next time

This is worth recognising because it is a confusing error to hit: the query looks completely ordinary and the message does not obviously point at the alias. If a perfectly reasonable alias will not compile, suspect a reserved word before you suspect anything else. The set operators — UNION, INTERSECT, MINUS and EXCEPT — get their own episodes in Level 4.

Key points

  • +, - and * on this SALARY column returned the same two decimal places the column has. / returned eight — division widens the scale, the others do not.
  • 7 / 2 returned 3.500000. There is no integer truncation to inherit from C, Java or Python 2.
  • FLOOR(7 / 2) is what returned 3, and 7 % 2 is what returned the remainder 1. If you want the whole number, name the function that gives it to you.
  • % and MOD() are the same operation in two spellings, and so are || and CONCAT().
  • *, / and % are applied before + and -; brackets beat both. 2 + 3 * 4 is 14 and (2 + 3) * 4 is 20.
  • A unary - negates a value rather than subtracting one.
  • A number concatenates into text with no cast, and keeps its raw column formatting — decimal places included.
  • Concatenating anything to a NULL returns NULL for the whole expression, which is why COALESCE exists.
  • MINUS is a reserved word in Snowflake, so it only works as an alias in double quotes.
Next in this series

In the next post we will cover comments, case sensitivity and quoted identifiers. It is the last post of Level 1, and it is the reason a query that looks perfectly correct comes back with zero rows.

Every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the script above. The one query shown without a result pane — the unquoted AS MINUS alias — was not captured for this episode, and the page says so where it appears. The EMPLOYEES data is invented demo data created by that script. No performance or benchmark claims are made anywhere in this series. Operator behaviour is documented in the Snowflake operators documentation.

No comments:

Post a Comment

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