Skip to main content

Data analysis · Intermediate · 18 min

Write shorter analyst SQL with DuckDB's friendly extensions

By Padding · Updated 18 Nov 2026
Python 3.15 · DuckDB 2.0.1 · uv 0.13 (checked on python:3.15-slim)

You will profile, group, filter, reshape and join a small sales dataset with eight DuckDB extensions to SQL, each run next to the standard query it replaces, and know which ones will not carry over to another database.

On this page

Analyst SQL repeats itself. You list every column twice, once in SELECT and again in GROUP BY. You wrap a query in a subquery only to filter on a window function. You write a CASE per month to turn rows into columns. DuckDB accepts standard SQL, and it also adds a set of extensions, which it calls friendly SQL, that remove much of that repetition.

In this tutorial you load two small CSV files, orders from shops in Accra, Lagos and Nairobi plus a price list that changes over time, and work through eight of those extensions. Each one runs next to the standard SQL it replaces, so you can see that both give the same answer. Each step ends with a portability note, because the shorter form only helps while your query stays in DuckDB or in an engine that copied the feature.

You run DuckDB from Python with a five-line script that reads SQL from your terminal, so there is nothing else to install. Everything lives in ~/duckdb-shortcuts-demo, which you can delete in one go at the end.

Step 1 · Set up the project and load the data

Create the project and add DuckDB. The version range allows 2.0 patch releases and nothing newer:

Bash
mkdir -p ~/duckdb-shortcuts-demo
cd ~/duckdb-shortcuts-demo
uv init --no-package --python 3.15
uv add "duckdb>=2.0,<2.1"

Write the two data files. orders.csv has 13 orders over three months; the last one has no sales channel recorded. prices.csv lists each product's price from the date it took effect:

Bash
cd ~/duckdb-shortcuts-demo
cat > orders.csv <<'CSV'
order_id,ordered_at,city,product,quantity,channel
1001,2026-01-05 09:12:00,Accra,rice_5kg,4,shop
1002,2026-01-09 14:30:00,Lagos,cooking_oil_1l,10,whatsapp
1003,2026-01-17 11:05:00,Nairobi,sugar_1kg,6,shop
1004,2026-01-28 16:45:00,Lagos,rice_5kg,8,shop
1005,2026-02-02 10:20:00,Accra,cooking_oil_1l,3,whatsapp
1006,2026-02-11 08:55:00,Nairobi,rice_5kg,5,whatsapp
1007,2026-02-14 13:10:00,Lagos,sugar_1kg,12,whatsapp
1008,2026-02-25 17:40:00,Accra,cooking_oil_1l,7,shop
1009,2026-03-03 09:30:00,Nairobi,cooking_oil_1l,9,shop
1010,2026-03-12 15:15:00,Lagos,rice_5kg,6,whatsapp
1011,2026-03-19 12:00:00,Accra,rice_5kg,2,shop
1012,2026-03-27 18:25:00,Nairobi,sugar_1kg,11,whatsapp
1013,2026-03-30 10:10:00,Lagos,cooking_oil_1l,4,
CSV
cat > prices.csv <<'CSV'
product,valid_from,unit_price
rice_5kg,2026-01-01,6.50
rice_5kg,2026-02-01,6.90
rice_5kg,2026-03-15,7.20
cooking_oil_1l,2026-01-01,2.40
cooking_oil_1l,2026-02-20,2.60
sugar_1kg,2026-01-01,1.10
sugar_1kg,2026-03-01,1.25
CSV

Now the runner. q.py opens a database file, shop.duckdb, runs whatever SQL you pipe into it and prints the result of the last statement:

Bash
cd ~/duckdb-shortcuts-demo
cat > q.py <<'PY'
import sys

import duckdb

con = duckdb.connect("shop.duckdb")
result = con.sql(sys.stdin.read())
if result is not None:
    result.show(max_width=200)
PY

Load both files into tables. This uses the first shortcut: a query may start with FROM, and FROM 'file.csv' on its own means SELECT * FROM 'file.csv'. Prices are read as DECIMAL(10,2) so money sums come out exact rather than as floating-point approximations:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
CREATE OR REPLACE TABLE orders AS FROM 'orders.csv';
CREATE OR REPLACE TABLE prices AS
    FROM read_csv('prices.csv', types = {'unit_price': 'DECIMAL(10,2)'});
DESCRIBE orders;
SQL

Check it worked

DESCRIBE lists six columns. DuckDB detected the types from the file: order_id and quantity are BIGINT, ordered_at is TIMESTAMP, and city, product and channel are VARCHAR. A file named shop.duckdb now sits next to q.py, and every later step reads from it.

Portability: the FROM-first form and querying a file path as if it were a table are DuckDB features. Elsewhere, write SELECT * FROM orders and load files with the engine's own import command.

Step 2 · Profile a table with SUMMARIZE

Before writing any analysis, check what is in the table: ranges, distinct counts, gaps. In standard SQL that is one min, max, count(DISTINCT ...) and count(*) - count(col) per column, glued together with UNION ALL. Here is that for just one column:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT 'quantity' AS column_name,
       min(quantity) AS min, max(quantity) AS max,
       count(DISTINCT quantity) AS distinct_values,
       round(100.0 * (count(*) - count(quantity)) / count(*), 2) AS null_percentage
FROM orders;
SQL

SUMMARIZE does every column at once. Its full output is wide (count, mean, standard deviation and quartiles as well), so select the columns you want from it:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT column_name, column_type, min, max, approx_unique, null_percentage
FROM (SUMMARIZE orders);
SQL

Check it worked

You see one row per column. quantity runs from 2 to 12, ordered_at from 2026-01-05 to 2026-03-30, and channel has a null_percentage of 7.69: one order in 13 has no channel. That gap is worth knowing before you group by channel. approx_unique, like the quartiles in the full output, is an estimate, which is what keeps SUMMARIZE fast on tables with millions of rows; use count(DISTINCT ...) when you need the exact figure.

Portability: SUMMARIZE is DuckDB only. It is an exploration tool, so it rarely needs to leave DuckDB.

Step 3 · Group by every non-aggregated column with GROUP BY ALL

Monthly units per city, the standard way. The month expression appears twice, and if you add a column to SELECT you must remember to add it to GROUP BY too:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city, strftime(ordered_at, '%Y-%m') AS month, sum(quantity) AS units
FROM orders
GROUP BY city, strftime(ordered_at, '%Y-%m')
ORDER BY city, month;
SQL

GROUP BY ALL groups by every SELECT column that is not an aggregate, and ORDER BY ALL sorts by every column from left to right:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city, strftime(ordered_at, '%Y-%m') AS month, sum(quantity) AS units
FROM orders
GROUP BY ALL
ORDER BY ALL;
SQL

Check it worked

Both queries print the same nine rows, from Accra 2026-01 4 to Nairobi 2026-03 20, with Lagos at 18 units in January. The units column shows the type int128: DuckDB widens a sum of BIGINT values so it cannot overflow.

Portability: Snowflake and BigQuery also accept GROUP BY ALL. Many other engines do not, so expand it to the column list before you move a query.

Step 4 · Match each order to the price in force with ASOF JOIN

Prices change on set dates, so an order must take the latest price whose valid_from is on or before the order time. An equality join cannot express "latest earlier row". The standard answer is a correlated subquery:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT o.order_id, o.ordered_at, o.product,
       (SELECT p.unit_price
        FROM prices AS p
        WHERE p.product = o.product AND p.valid_from <= o.ordered_at
        ORDER BY p.valid_from DESC
        LIMIT 1) AS unit_price
FROM orders AS o
WHERE o.product = 'rice_5kg'
ORDER BY o.ordered_at;
SQL

ASOF JOIN says the same thing in the join itself. The equality condition matches the product; the inequality picks, for each order, the closest price row that is not later than it. Save the result as a table, because the next steps use it:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
CREATE OR REPLACE TABLE priced AS
SELECT o.order_id, o.ordered_at, o.city, o.product, o.quantity,
       p.valid_from, p.unit_price,
       o.quantity * p.unit_price AS revenue
FROM orders AS o
ASOF JOIN prices AS p
  ON o.product = p.product
 AND o.ordered_at >= p.valid_from;
FROM priced WHERE product = 'rice_5kg' ORDER BY ordered_at;
SQL

Check it worked

Both queries give the five rice orders the same prices: 6.50 for the two January orders, 6.90 for order 1006 on 11 February and for order 1010 on 12 March, and 7.20 for order 1011 on 19 March, four days after the last price rise. The priced table has all 13 orders, and its revenue column holds exact two-decimal amounts such as 52.00.

An ASOF JOIN is an inner join, so an order placed before a product's first price would disappear. Use ASOF LEFT JOIN to keep such rows with a NULL price, then count the NULLs. The same join matches sensor readings to the last calibration, or local-currency sales to the most recent exchange rate.

Portability: Snowflake has an ASOF JOIN with a different syntax (MATCH_CONDITION). Most other engines need the correlated subquery or a window function.

Step 5 · Pick columns by rule with EXCLUDE, REPLACE and COLUMNS()

Standard SQL has SELECT * or a full column list, nothing between. DuckDB lets you drop columns with EXCLUDE and rewrite one in place with REPLACE, keeping the column order:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT * EXCLUDE (valid_from, unit_price)
         REPLACE (upper(city) AS city)
FROM priced
ORDER BY order_id
LIMIT 3;
SQL

COLUMNS() goes further: it expands into one expression per matching column. Pass a list of names, or a regular expression. Here one sum becomes two output columns, and a regular expression picks the same pair for an average:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city, sum(COLUMNS(['quantity', 'revenue']))
FROM priced
GROUP BY ALL
ORDER BY ALL;
SQL
uv run q.py <<'SQL'
SELECT city, round(avg(COLUMNS('^(quantity|revenue)$')), 2)
FROM priced
GROUP BY ALL
ORDER BY ALL;
SQL

The standard version of the first query is SELECT city, sum(quantity) AS quantity, sum(revenue) AS revenue. With two columns that is no hardship; with twelve monthly columns, or with a table whose columns change each quarter, COLUMNS() saves real typing and real mistakes.

Check it worked

The first query shows six columns with the city names in capitals (ACCRA, LAGOS, NAIROBI) and no valid_from or unit_price. The totals query prints quantity and revenue per city: Accra 16 and 65.80, Lagos 40 and 141.00, Nairobi 31 and 78.25. The averages query prints the same two column names with averages instead, for example Lagos at 8.0 units and 28.2 per order.

Portability: Snowflake has SELECT * EXCLUDE and REPLACE; BigQuery has SELECT * EXCEPT and REPLACE. COLUMNS() is much rarer, so expect to write those expressions out one by one elsewhere.

Step 6 · Filter on a window function with QUALIFY

To keep only the biggest order in each city, you rank the orders with a window function and keep rank 1. WHERE runs before window functions, so standard SQL needs a subquery. If window functions are new to you, the window functions tutorial covers PARTITION BY and ORDER BY inside OVER.

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city, order_id, revenue
FROM (
    SELECT city, order_id, revenue,
           row_number() OVER (PARTITION BY city ORDER BY revenue DESC) AS rank_in_city
    FROM priced
) AS ranked
WHERE rank_in_city = 1
ORDER BY city;
SQL

QUALIFY is a WHERE that runs after window functions, so the subquery goes:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city, order_id, revenue
FROM priced
QUALIFY row_number() OVER (PARTITION BY city ORDER BY revenue DESC) = 1
ORDER BY city;
SQL

It can also filter on a window column by its alias. This finds the order with which each city's running revenue first reached 50:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city, order_id, ordered_at, revenue,
       sum(revenue) OVER (PARTITION BY city ORDER BY ordered_at) AS running
FROM priced
QUALIFY running >= 50 AND running - revenue < 50
ORDER BY city;
SQL

Check it worked

The first two queries print the same three rows: order 1001 (26.00) for Accra, 1004 (52.00) for Lagos and 1006 (34.50) for Nairobi. The running-total query shows Accra crossing 50 with order 1008 at 51.40, Lagos with order 1004 at 76.00 and Nairobi with order 1009 at 64.50. row_number() picks one of the tied rows arbitrarily, and the choice can change between runs; if two orders could share the top revenue, add a second sort column such as order_id.

Portability: QUALIFY works in Snowflake and BigQuery, among others. For engines without it, keep the subquery version to hand.

Step 7 · Turn rows into columns and back with PIVOT and UNPIVOT

A month-by-city revenue grid is a classic report shape. In standard SQL each month is its own conditional sum, and a new month means editing the query:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city,
       sum(CASE WHEN strftime(ordered_at, '%Y-%m') = '2026-01' THEN revenue END) AS "2026-01",
       sum(CASE WHEN strftime(ordered_at, '%Y-%m') = '2026-02' THEN revenue END) AS "2026-02",
       sum(CASE WHEN strftime(ordered_at, '%Y-%m') = '2026-03' THEN revenue END) AS "2026-03"
FROM priced
GROUP BY city
ORDER BY city;
SQL

DuckDB's PIVOT finds the distinct months itself and makes one column per value, so April appears without a code change:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
CREATE OR REPLACE TABLE monthly AS
PIVOT (SELECT city, strftime(ordered_at, '%Y-%m') AS month, revenue FROM priced)
ON month
USING sum(revenue)
GROUP BY city
ORDER BY city;
FROM monthly;
SQL

UNPIVOT reverses it, turning the wide grid back into one row per city and month, which is the shape most charts and joins want. COLUMNS(* EXCLUDE city) means "every month column, whatever they are called":

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
UNPIVOT monthly
ON COLUMNS(* EXCLUDE city)
INTO NAME month VALUE revenue
ORDER BY city, month;
SQL

Check it worked

The CASE query and FROM monthly print the same grid: Accra 26.00, 25.40 and 14.40; Lagos 76.00, 13.20 and 51.80; Nairobi 6.60, 34.50 and 37.15. The UNPIVOT query prints nine rows, ending with Nairobi 2026-03 37.15. Each city's row adds up to its total from the COLUMNS() step, which is a quick way to check that nothing was lost in either direction.

Portability: Snowflake, BigQuery and SQL Server also have PIVOT and UNPIVOT. BigQuery and SQL Server expect you to list the values (IN ('2026-01', ...)); Snowflake can also take IN (ANY). The syntax differs between all three. If you do this reshaping in Python instead, the pandas pivot and melt tutorial does the same with DataFrames.

Step 8 · Keep related values together with lists and structs

A column in DuckDB can hold a list of values, or a struct: a small record with named fields. That lets one row per city carry every product it ordered, in order, plus its biggest order as a single value. The standard-SQL fallback is a comma-joined string that you would have to split apart again later:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city, string_agg(product, ', ' ORDER BY ordered_at) AS products
FROM priced
GROUP BY city
ORDER BY city;
SQL

With list() the result stays typed. {'order_id': ..., 'revenue': ...} builds a struct, and max_by(value, key) keeps the value from the row with the highest key:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
CREATE OR REPLACE TABLE baskets AS
SELECT city,
       list(product ORDER BY ordered_at) AS products,
       max_by({'order_id': order_id, 'revenue': revenue}, revenue) AS biggest
FROM priced
GROUP BY ALL;
FROM baskets ORDER BY city;
SQL

Now query inside those columns. List indexes start at 1, struct fields use a dot, and unnest turns a list back into rows:

Bash
cd ~/duckdb-shortcuts-demo
uv run q.py <<'SQL'
SELECT city,
       len(products) AS orders,
       products[1] AS first_product,
       list_contains(products, 'sugar_1kg') AS bought_sugar,
       biggest.order_id AS biggest_order,
       biggest.revenue AS biggest_revenue
FROM baskets
ORDER BY city;
SQL
uv run q.py <<'SQL'
SELECT count(*) AS product_rows
FROM (SELECT city, unnest(products) AS product FROM baskets);
SQL

Check it worked

FROM baskets shows a products column of type varchar[], such as [rice_5kg, cooking_oil_1l, cooking_oil_1l, rice_5kg] for Accra, and a biggest column of type struct(order_id bigint, revenue decimal(29,2)), such as {'order_id': 1001, 'revenue': 26.00}. The next query shows Accra with 4 orders, rice first and bought_sugar false; Lagos with 5 and Nairobi with 4, both true; and the same biggest orders that QUALIFY found. unnest gives back 13 product rows, one per original order.

Lists also suit text fields that hold several values, such as the languages a customer speaks or the phone numbers on an account, which spreadsheets often cram into one cell separated by semicolons. string_split(text, ';') turns such a cell into a list you can search with list_contains.

Portability: BigQuery has ARRAY and STRUCT, PostgreSQL has arrays and composite types, and Snowflake has ARRAY and OBJECT. Each has its own functions and syntax, so list and struct code is the part of a DuckDB query you will most often rewrite when moving it.

Next steps

You have run eight shortcuts, each against the standard form it replaces. A sensible habit: use the short form while exploring, and when a query moves into a shared pipeline on another engine, expand it using the standard version from this page.

When you are finished, delete the project folder, which also removes shop.duckdb:

Bash
rm -rf ~/duckdb-shortcuts-demo

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.