Let’s Get Certified
Module 13 / 21 · Delta Lake and Spark

SQL commands and logic

Work through joins, windows, higher-order functions, and nested records in Spark SQL, then inspect the tables behind the results.

Conditional logic and CTEs

WITH recent AS (
  SELECT * FROM main.silver.orders WHERE order_date >= current_date() - INTERVAL 30 DAYS
)
SELECT customer_id,
       CASE WHEN SUM(amount) > 1000 THEN 'gold'
            WHEN SUM(amount) > 100  THEN 'silver'
            ELSE 'bronze' END AS tier,
       COUNT_IF(status = 'returned') AS returns,
       COALESCE(MAX(coupon), 'none') AS last_coupon
FROM recent
GROUP BY customer_id
HAVING COUNT(*) >= 2;
  • CASE WHEN works in SELECT, WHERE and ORDER BY.
  • COUNT(*) counts rows; COUNT(col) ignores nulls; COUNT(DISTINCT col); approx_count_distinct(col).
  • Gotcha: COUNT(age IS NULL) counts every row because the boolean is never null. Use COUNT_IF(age IS NULL) or COUNT(*) - COUNT(age).
  • WHERE filters rows before grouping; HAVING filters groups. QUALIFY filters on window function results.
  • Null comparisons: col = NULL is never true; use IS NULL. <=> is null-safe equality.
  • try_cast(x AS INT) returns null instead of failing on bad values.

Joins in SQL

SELECT o.order_id, o.customer_name, p.amount
FROM orders o
LEFT JOIN payments p ON o.order_id = p.order_id;      -- all orders, amount null if unpaid

SELECT * FROM customers c LEFT SEMI JOIN orders o ON c.id = o.customer_id;  -- customers with orders
SELECT * FROM customers c LEFT ANTI JOIN orders o ON c.id = o.customer_id;  -- customers without orders
SELECT * FROM sizes CROSS JOIN colors;                                      -- Cartesian product

Window functions

SELECT *,
  ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_ts DESC) AS rn,
  SUM(amount)  OVER (PARTITION BY customer_id ORDER BY order_ts
                     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
  LAG(amount)  OVER (PARTITION BY customer_id ORDER BY order_ts) AS prev_amount
FROM main.silver.orders
QUALIFY rn = 1;      -- latest order per customer

ROW_NUMBER gives unique numbers; RANK leaves gaps after ties; DENSE_RANK does not.

PIVOT, UNPIVOT and set operations

PIVOT

SELECT * FROM (SELECT country, quarter, amount FROM sales)
PIVOT (SUM(amount) FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4'));

UNPIVOT

UNPIVOT does the reverse:

SELECT * FROM sales_wide
UNPIVOT (amount FOR quarter IN (q1, q2, q3, q4));    -- wide to long

Set operations

SELECT id FROM a UNION SELECT id FROM b;      -- removes duplicates
SELECT id FROM a UNION ALL SELECT id FROM b;  -- keeps duplicates
SELECT id FROM a INTERSECT SELECT id FROM b;
SELECT id FROM a EXCEPT SELECT id FROM b;     -- in a, not in b

Semi-structured and nested data

-- JSON stored as a STRING column: colon syntax
SELECT raw:customer.name, raw:items[0].sku, raw:total::double FROM bronze.events;

-- parse JSON string into a STRUCT
SELECT from_json(raw, schema_of_json('{"id":1,"tags":["a"]}')) AS parsed FROM bronze.events;

-- STRUCT fields: dot notation; expand all fields with .*
SELECT parsed.id, parsed.* FROM t;

-- arrays
SELECT order_id, explode(items) AS item FROM orders;      -- one row per element
SELECT size(items), array_contains(tags, 'vip'), array_distinct(tags), flatten(nested_arrays),
       collect_list(sku), collect_set(sku) FROM ...;     -- collect_* aggregate rows into arrays

-- VARIANT type
SELECT parse_json(raw) AS v FROM bronze.events;          -- then v:customer.name

Higher-order functions

They apply a lambda to every array element without exploding:

SELECT
  FILTER(items, i -> i.qty > 0)                     AS valid_items,
  TRANSFORM(items, i -> i.price * 1.2)             AS prices_with_vat,
  EXISTS(items, i -> i.sku = 'X1')                 AS has_x1,
  AGGREGATE(items, 0D, (acc, i) -> acc + i.price)  AS total     -- also called REDUCE
FROM orders;

SQL user-defined functions

CREATE OR REPLACE FUNCTION main.util.vat(price DOUBLE)
RETURNS DOUBLE
RETURN price * 1.2;

SELECT main.util.vat(amount) FROM orders;
DESCRIBE FUNCTION EXTENDED main.util.vat;

SQL UDFs are stored in Unity Catalog (governed with EXECUTE privilege), are optimized like built-in SQL, and are the basis of row filters and column masks (Access control). Python UDFs can also be registered in Unity Catalog with LANGUAGE PYTHON.

Hashing with a SQL UDF

CREATE OR REPLACE FUNCTION main.util.hash_email(email STRING)
RETURNS STRING
RETURN sha2(lower(email), 256);
SELECT main.util.hash_email(email) FROM main.silver.customers;

Hashing is one-way, not encryption: you cannot get the email back.

Parameters and variables

DECLARE VARIABLE run_date DATE DEFAULT current_date();
SET VAR run_date = DATE'2026-11-01';
SELECT * FROM orders WHERE order_date = run_date;
SELECT * FROM orders WHERE order_date = :run_date;     -- named parameter from a job, widget or dashboard
SELECT * FROM IDENTIFIER(:table_name);                  -- parameterized object name
SET vs SET VAR

SET x = 1 sets a Spark configuration, not a SQL variable. Referencing x later fails with "Configuration x is not available". Declare the variable, then assign it with SET VAR (or SET VARIABLE); a scalar subquery is allowed:

DECLARE VARIABLE project_id BIGINT;
SET VAR project_id = (SELECT id FROM main.app.projects ORDER BY id LIMIT 1);
SELECT * FROM main.app.tasks AS t WHERE t.project_id = session.project_id;

Variables work in notebooks and in the SQL editor. Legacy ${var} substitution is deprecated in favor of named parameter markers (:param).

DESCRIBE commands

DESCRIBE FUNCTION, used above on a UDF, is one of a family of commands that return the metadata of an object:

CommandReturns
DESCRIBE CATALOG [EXTENDED] mainName, comment, owner, type; EXTENDED adds properties, created by/at
DESCRIBE SCHEMA [EXTENDED] main.sales (= DATABASE)Name, comment, location, properties
DESCRIBE TABLE [EXTENDED] tColumns; EXTENDED adds type, location, owner, properties
DESCRIBE VOLUME vVolume type (MANAGED or EXTERNAL) and storage location
DESCRIBE EXTERNAL LOCATION locName, URL (cloud path), storage credential, owner
DESCRIBE CREDENTIAL cName, owner, cloud identity it wraps
DESCRIBE CONNECTION cFederation connection: type, URL/host, owner, options
DESCRIBE FUNCTION [EXTENDED] fSignature, class, usage; EXTENDED adds body or examples
DESCRIBE QUERY SELECT ...Output columns and types of a query (no data)
DESCRIBE SHARE / RECIPIENT / PROVIDER xDelta Sharing objects: share contents and owner; recipient auth type and activation link; provider auth type, cloud, region, metastore id
Exam pattern

"Where is this data stored?" Table: DESCRIBE DETAIL or DESCRIBE TABLE EXTENDED (Location). External location: DESCRIBE EXTERNAL LOCATION (URL). Volume: DESCRIBE VOLUME. The video author got the external location question on the real exam.

Loading and querying files from SQL

SELECT * FROM json.`/Volumes/main/raw/landing/events/`;           -- direct query of files
SELECT * FROM read_files('/Volumes/main/raw/landing/orders/',
                         format => 'csv', header => true);        -- schema inference, options

COPY INTO main.bronze.orders
FROM '/Volumes/main/raw/landing/orders/'
FILEFORMAT = CSV
FORMAT_OPTIONS ('header' = 'true', 'inferSchema' = 'true')
COPY_OPTIONS ('mergeSchema' = 'true');

COPY INTO is covered in depth in Auto Loader, COPY INTO, and Lakeflow Connect.

Predict null behavior

Three payment rows have amounts 10, NULL, and 30. Predict COUNT(*), COUNT(amount), and AVG(amount).

Check your reasoning

The results are 3, 2, and 20. The aggregate over the column omits the null amount.

Product reference

SQL language reference in the Databricks documentation

Knowledge check

SQL commands and logic quiz

Answer 8 questions. Check each answer for an explanation.