Courses / Databases for Backend Interviews / Chapter 15
Module 7 · SQL patterns: comparing, sequencing and reshaping · Chapter 15 of 27
Transformation Patterns: Pivoting, Unpivoting, Text and JSON
Builds on Normalisation: Anomalies, 1NF to BCNF, and When to Denormalise, Aggregation Patterns: Tally Counts, Group Buckets and Rolling Totals and Sequencing and Hierarchy Patterns: Streaks, Sessions and Recursive Trees. Next up: Timed SQL Practice: Three Rounds Across Every Pattern.
Part 1 · Pivot: rows to columns
Long and wide tables
Reports are usually read as grids, months across and cities down, while the database stores one row per fact. Turning one shape into the other is a transformation.
A long table has one row per observation: city, month and revenue. A wide table has one row per entity and one column per category: a city with a column for each month. To pivot is to turn long into wide, and to unpivot is the reverse. Dashboards and spreadsheets want wide, while storage and filtering are easier on long.
This chapter uses a small summary table that a daily job could have written, with the monthly revenue of three cities for January to March 2026, plus a few tables from the grocery schema for the later lessons. Nagpur has no row for February, which is a hole the pivot has to handle on purpose. Results are printed with the helper from the SQL chapter.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE revenue_by_month ( city text NOT NULL, month date NOT NULL, revenue numeric(12,2) NOT NULL, PRIMARY KEY (city, month) );
INSERT INTO revenue_by_month (city, month, revenue) VALUES ('Pune', '2026-01-01', 120000.00), ('Pune', '2026-02-01', 135000.00), ('Pune', '2026-03-01', 150000.00), ('Mumbai', '2026-01-01', 210000.00), ('Mumbai', '2026-02-01', 190000.00), ('Mumbai', '2026-03-01', 230000.00), ('Nagpur', '2026-01-01', 60000.00), ('Nagpur', '2026-03-01', 75000.00);
SELECT city, month::text AS month, revenue FROM revenue_by_month ORDER BY city, month;
city | month | revenue -------+------------+---------- Mumbai | 2026-01-01 | 210000.00 Mumbai | 2026-02-01 | 190000.00 Mumbai | 2026-03-01 | 230000.00 Nagpur | 2026-01-01 | 60000.00 Nagpur | 2026-03-01 | 75000.00 Pune | 2026-01-01 | 120000.00 Pune | 2026-02-01 | 135000.00 Pune | 2026-03-01 | 150000.00 (8 rows)
Pivot with FILTER or CASE
The standard pivot is a GROUP BY on the row label with one conditional aggregate per output column. Each aggregate looks only at the rows of its month. You met FILTER for counting in the aggregation chapter, and it works the same way with sum.
SELECT city, sum(revenue) FILTER (WHERE month = date '2026-01-01') AS jan, sum(revenue) FILTER (WHERE month = date '2026-02-01') AS feb, sum(revenue) FILTER (WHERE month = date '2026-03-01') AS mar FROM revenue_by_month GROUP BY city ORDER BY city;
city | jan | feb | mar -------+-----------+-----------+---------- Mumbai | 210000.00 | 190000.00 | 230000.00 Nagpur | 60000.00 | NULL | 75000.00 Pune | 120000.00 | 135000.00 | 150000.00 (3 rows)
The grain is now one row per city. Look at Nagpur in February: the value is NULL. No row matched, and the sum of no rows is NULL, not zero. That is the honest answer, since "no data" and "zero revenue" are different statements, and a chart can leave a gap for the first and draw a flat line for the second.
The older form uses CASE inside the aggregate. It works in every database. Here the ELSE 0 was written, so the missing month becomes a zero.
SELECT city, sum(CASE WHEN month = date '2026-01-01' THEN revenue ELSE 0 END) AS jan, sum(CASE WHEN month = date '2026-02-01' THEN revenue ELSE 0 END) AS feb, sum(CASE WHEN month = date '2026-03-01' THEN revenue ELSE 0 END) AS mar FROM revenue_by_month GROUP BY city ORDER BY city;
city | jan | feb | mar -------+-----------+-----------+---------- Mumbai | 210000.00 | 190000.00 | 230000.00 Nagpur | 60000.00 | 0 | 75000.00 Pune | 120000.00 | 135000.00 | 150000.00 (3 rows)
Both forms are correct, and the choice is about the meaning of the gap. Choose zero only when the business really means zero. A pivot can also carry a total next to the months. The total is an ordinary sum with no filter, and the result can be sorted by it.
SELECT city, sum(revenue) FILTER (WHERE month = date '2026-01-01') AS jan, sum(revenue) FILTER (WHERE month = date '2026-02-01') AS feb, sum(revenue) FILTER (WHERE month = date '2026-03-01') AS mar, sum(revenue) AS total FROM revenue_by_month GROUP BY city ORDER BY total DESC;
crosstab and its limits
PostgreSQL ships a helper for this in the tablefunc extension. It is a contrib extension, which the documentation calls trusted: a user who is not a superuser can install it with the CREATE privilege on the database. crosstab takes a source query that returns a row label, a category and a value. The source query has to be ordered so that the rows of one row label are together. The documentation advises ORDER BY 1 for the form with a category list, and ORDER BY 1, 2 for the one-argument form, where the category column decides the position across the page.
CREATE EXTENSION tablefunc;Inside PGlite the extension is bundled and has to be passed in when the database is created, then CREATE EXTENSION switches it on.
import { PGlite } from '@electric-sql/pglite' import { tablefunc } from '@electric-sql/pglite/contrib/tablefunc' const db = new PGlite({ extensions: { tablefunc } })
crosstab with a category list
The two-argument form also takes a query that lists the categories. Because the function returns a set of records, the caller has to declare the output columns, with their names and types. The categories are matched to the columns in the order they are listed, so that order must match the declared columns. The category query must return at least one row and no duplicates, or the function raises an error.
SELECT city, jan, feb, mar FROM crosstab( 'SELECT city, month, revenue FROM revenue_by_month ORDER BY 1, 2', $$VALUES ('2026-01-01'::date), ('2026-02-01'), ('2026-03-01')$$ ) AS ct (city text, jan numeric, feb numeric, mar numeric) ORDER BY city;
city | jan | feb | mar -------+-----------+-----------+---------- Mumbai | 210000.00 | 190000.00 | 230000.00 Nagpur | 60000.00 | NULL | 75000.00 Pune | 120000.00 | 135000.00 | 150000.00 (3 rows)
The result matches the FILTER version, with NULL for the missing month. The one-argument form has no category list, and it is risky. It fills the output columns by position, so a group with a missing category shifts everything after the gap to the left. The documentation says that if a group has fewer rows than there are value columns, the extra columns are filled with nulls.
SELECT * FROM crosstab( 'SELECT city, month, revenue FROM revenue_by_month ORDER BY 1, 2' ) AS ct (city text, c1 numeric, c2 numeric, c3 numeric) ORDER BY city;
city | c1 | c2 | c3 -------+-----------+-----------+---------- Mumbai | 210000.00 | 190000.00 | 230000.00 Nagpur | 60000.00 | 75000.00 | NULL Pune | 120000.00 | 135000.00 | 150000.00 (3 rows)
Nagpur's March revenue of 75,000 now sits in the column called c2, and the NULL is at the end. No error was raised. Use the two-argument form whenever a category can be missing.
Both approaches share a limit: the output columns are part of the query text. If next month adds a fourth column, you must change the query, or build the SQL text in your application from the list of months. A pure SQL pivot cannot choose its own columns. When the set of categories is open-ended, return the long table and pivot in the application, or return JSON instead.
Why does the FILTER pivot show NULL for Nagpur in February while the CASE ... ELSE 0 pivot shows 0?
Part 2 · Unpivot: columns to rows
Wide data back to long
Data often arrives wide: a spreadsheet export with one column per month, or a legacy table with phone1, phone2 and phone3. Filtering, grouping and charting all want one value per row. Unpivoting turns each such column into a row of its own.
To have something to unpivot, this lesson saves the wide result of the previous lesson as a table, city_quarter, with one row per city and the columns jan, feb and mar.
CREATE TABLE city_quarter AS SELECT city, sum(revenue) FILTER (WHERE month = date '2026-01-01') AS jan, sum(revenue) FILTER (WHERE month = date '2026-02-01') AS feb, sum(revenue) FILTER (WHERE month = date '2026-03-01') AS mar FROM revenue_by_month GROUP BY city;
The classic SQL answer is a UNION ALL of one query per column, which reads the table once for every column. PostgreSQL has a shorter way, which reads each row once. A VALUES list creates a small table of pairs, and LATERAL lets that list refer to the current row of city_quarter. A lateral join is a join where the right side may use columns of the left side, evaluated once for each left row. Each city row is paired with three rows, one for each month column.
SELECT c.city, v.month, v.revenue FROM city_quarter AS c CROSS JOIN LATERAL (VALUES ('2026-01', c.jan), ('2026-02', c.feb), ('2026-03', c.mar) ) AS v (month, revenue) ORDER BY c.city, v.month;
city | month | revenue -------+---------+---------- Mumbai | 2026-01 | 210000.00 Mumbai | 2026-02 | 190000.00 Mumbai | 2026-03 | 230000.00 Nagpur | 2026-01 | 60000.00 Nagpur | 2026-02 | NULL Nagpur | 2026-03 | 75000.00 Pune | 2026-01 | 120000.00 Pune | 2026-02 | 135000.00 Pune | 2026-03 | 150000.00 (9 rows)
Nine rows come out of three, and the label column holds the month names that were column names before. The labels are written by hand in the VALUES list, so the month names stay under your control.
NULLs in the result
The unpivoted table has a row for Nagpur in February with a NULL revenue, the cell that had no data. Whether to keep that row is a question about the output. A chart would want the gap. A table that is going to be loaded into a database where revenue is required would not. A WHERE revenue IS NOT NULL after the join removes the placeholder rows.
SELECT c.city, v.month, v.revenue FROM city_quarter AS c CROSS JOIN LATERAL (VALUES ('2026-01', c.jan), ('2026-02', c.feb), ('2026-03', c.mar) ) AS v (month, revenue) WHERE v.revenue IS NOT NULL ORDER BY c.city, v.month;
city | month | revenue -------+---------+---------- Mumbai | 2026-01 | 210000.00 Mumbai | 2026-02 | 190000.00 Mumbai | 2026-03 | 230000.00 Nagpur | 2026-01 | 60000.00 Nagpur | 2026-03 | 75000.00 Pune | 2026-01 | 120000.00 Pune | 2026-02 | 135000.00 Pune | 2026-03 | 150000.00 (8 rows)
Eight rows are left, which is the shape of the original table. This is a useful check, since a pivot followed by an unpivot that drops the NULLs should return the rows that were stored.
The lateral VALUES form has one more advantage: the columns do not have to share a type with each other, as long as each output column has one type. If the columns hold different types, such as a number in one and a date in the other, cast them to a common type, usually text, inside the list.
Why unpivot at all
Unpivoting is not only for loading data. Many calculations are easier on long rows. Take the total of a city over the three months. The wide way adds the columns, and the long way adds up the rows of one city.
SELECT city, jan + feb + mar AS wide_total FROM city_quarter ORDER BY city;
city | wide_total -------+----------- Mumbai | 630000.00 Nagpur | NULL Pune | 405000.00 (3 rows)
SELECT c.city, sum(v.revenue) AS long_total FROM city_quarter AS c CROSS JOIN LATERAL (VALUES (c.jan), (c.feb), (c.mar)) AS v (revenue) GROUP BY c.city ORDER BY c.city;
city | long_total -------+----------- Mumbai | 630000.00 Nagpur | 135000.00 Pune | 405000.00 (3 rows)
Adding columns with + gives NULL as soon as one of them is NULL, so Nagpur has no total at all. The sum over the unpivoted rows skips the NULL and returns 135000.00 for the two months that exist. Neither is automatically right, and the difference is exactly the gap decision from the previous page. The point is that the long form lets aggregates, filters and joins treat every month in one way, and the wide form needs one edit for every column you add.
Arrays with unnest
PostgreSQL has real array columns. This page adds a small products table with a list of tags for each product, and one product has an empty list. The array equivalent of unpivoting is unnest, which returns one row per element. Used in a lateral join it pairs each product with each of its tags.
CREATE TABLE products ( product_id int PRIMARY KEY, name text NOT NULL, price numeric(10,2) NOT NULL, tags text[] NOT NULL );
INSERT INTO products (product_id, name, price, tags) VALUES (1, 'Toned milk 1 L', 58.00, ARRAY['dairy', 'chilled']), (2, 'Curd 500 g', 40.00, ARRAY['dairy', 'chilled', 'probiotic']), (3, 'Salted peanuts 200 g', 70.00, ARRAY['snack']), (4, 'Basmati rice 5 kg', 640.00, ARRAY[]::text[]);
SELECT p.name, t.tag FROM products AS p CROSS JOIN LATERAL unnest(p.tags) AS t (tag) ORDER BY p.product_id, t.tag;
name | tag ---------------------+---------- Toned milk 1 L | chilled Toned milk 1 L | dairy Curd 500 g | chilled Curd 500 g | dairy Curd 500 g | probiotic Salted peanuts 200 g | snack (6 rows)
Salted peanuts has one tag, and the milk and the curd have two and three. Basmati rice has an empty array, so it vanishes from the result, because a cross join with zero rows gives zero rows. If every product must appear, use a LEFT JOIN LATERAL ... ON true. WITH ORDINALITY adds the position of each element in its array.
SELECT p.name, t.tag, t.pos FROM products AS p LEFT JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS t (tag, pos) ON true ORDER BY p.product_id, t.pos;
name | tag | pos ---------------------+-----------+----- Toned milk 1 L | dairy | 1 Toned milk 1 L | chilled | 2 Curd 500 g | dairy | 1 Curd 500 g | chilled | 2 Curd 500 g | probiotic | 3 Salted peanuts 200 g | snack | 1 Basmati rice 5 kg | NULL | NULL (7 rows)
Rice is now there, with NULL for both the tag and the position. Once the tags are rows, ordinary grouping works on them. Counting products per tag is the normal case, and it is the reason to unnest before aggregating.
SELECT t.tag, count(*) AS products FROM products AS p CROSS JOIN LATERAL unnest(p.tags) AS t (tag) GROUP BY t.tag ORDER BY products DESC, t.tag;
tag | products ----------+--------- chilled | 2 dairy | 2 probiotic | 1 snack | 1 (4 rows)
Part 3 · Reshaping text and dates
Splitting and joining text
Real data carries structure inside text: a full name, a phone number with punctuation, a list that someone stored in a single cell. Most cleaning is a few functions. The customers table has three names and two phone numbers written in different styles, and orders with their lines provide a basket to join. The lesson creates these tables first. The products table is the one from the previous lesson, and the orders have fewer columns than the grocery schema because only the time matters here.
CREATE TABLE cities ( city_id int PRIMARY KEY, name text NOT NULL, state text NOT NULL ); CREATE TABLE customers ( customer_id int PRIMARY KEY, name text NOT NULL, city_id int NOT NULL REFERENCES cities (city_id), phone text );
CREATE TABLE orders ( order_id int PRIMARY KEY, customer_id int NOT NULL REFERENCES customers (customer_id), placed_at timestamptz NOT NULL ); CREATE TABLE order_items ( order_id int NOT NULL REFERENCES orders (order_id), product_id int NOT NULL REFERENCES products (product_id), qty int NOT NULL, unit_price numeric(10,2) NOT NULL, PRIMARY KEY (order_id, product_id) );
INSERT INTO cities (city_id, name, state) VALUES (1, 'Pune', 'Maharashtra'); INSERT INTO customers (customer_id, name, city_id, phone) VALUES (1, 'Asha Rao', 1, '+91 04412-345678'), (2, 'Ravi Kumar Naik', 1, '(020) 2551 0044'), (3, 'Meera', 1, NULL);
INSERT INTO orders (order_id, customer_id, placed_at) VALUES (1, 1, '2026-03-02 09:15'), (2, 2, '2026-03-15 18:40'), (3, 1, '2026-03-20 11:05'); INSERT INTO order_items (order_id, product_id, qty, unit_price) VALUES (1, 1, 2, 58.00), (1, 4, 1, 640.00), (2, 2, 3, 40.00), (2, 3, 2, 70.00), (2, 1, 1, 58.00);
split_part(text, delimiter, n) returns the nth piece, counting from 1. A negative n counts from the end. A position beyond the last piece gives an empty string and not NULL, which matters when you test for missing data.
SELECT name, split_part(name, ' ', 1) AS first_name, split_part(name, ' ', 2) AS second_word, split_part(name, ' ', -1) AS last_word FROM customers ORDER BY customer_id;
name | first_name | second_word | last_word
----------------+------------+-------------+----------
Asha Rao | Asha | Rao | Rao
Ravi Kumar Naik | Ravi | Kumar | Naik
Meera | Meera | | Meera
(3 rows)Cleaning with regular expressions
regexp_replace(text, pattern, replacement, flags) rewrites every part of the text that matches a pattern. The flag g means all matches, and without it only the first one is replaced. The pattern \D matches any character that is not a digit, so replacing it with nothing keeps just the digits.
SELECT name, phone, regexp_replace(phone, '\D', '', 'g') AS digits_only FROM customers ORDER BY customer_id;
name | phone | digits_only ----------------+------------------+-------------- Asha Rao | +91 04412-345678 | 9104412345678 Ravi Kumar Naik | (020) 2551 0044 | 02025510044 Meera | NULL | NULL (3 rows)
Both numbers are now only digits, ready to be compared with a phone number from another system. The plus sign of the country code is gone as well, so decide whether you need it before you strip. A NULL phone stays NULL, since a function of NULL is NULL for most functions. Keep the raw value in its own column too, because cleaning loses information that you may want later.
A regular expression is also a good place to be careful. The pattern is text, so a backslash in a SQL string needs thought: with the default settings of PostgreSQL the single quoted string above is passed to the function exactly as written. If you are unsure, test the pattern on a short literal first.
Dates, numbers and casts
to_char turns a timestamp or a number into text with a format picture. Use it for display and for building labels such as an ISO week, and not as the way to store a date. The times below are shown in the session time zone, Asia/Kolkata.
SELECT order_id, to_char(placed_at, 'DD Mon YYYY, HH12:MI AM') AS pretty, to_char(placed_at, 'IYYY-"W"IW') AS iso_week FROM orders ORDER BY order_id;
order_id | pretty | iso_week ---------+-----------------------+--------- 1 | 02 Mar 2026, 09:15 AM | 2026-W10 2 | 15 Mar 2026, 06:40 PM | 2026-W11 3 | 20 Mar 2026, 11:05 AM | 2026-W12 (3 rows)
Numbers have format pictures too. FM removes the padding spaces, and a 0 in the picture forces a digit, so 42 can be printed as 0042. The commas in this run fall in groups of three digits. Indian lakh and crore grouping, as in 12,34,567, is not what this picture gives, so format money for people in the application when the grouping matters.
SELECT to_char(1234567.5, 'FM9,999,999.00') AS grouped, to_char(42, 'FM0000') AS padded;
grouped | padded -------------+------- 1,234,567.50 | 0042 (1 row)
Casts are where dirty data bites. A cast of invalid text stops the whole query with an error. PostgreSQL does check that a date exists: February 30 is rejected, not rolled into March.
SELECT '2026-02-30'::date;
ERROR 22008: date/time field value out of range: "2026-02-30"
To handle a column in which some values are bad, pg_input_is_valid(text, type) returns true or false instead of raising an error, and can be placed in a CASE before the cast. The values that do not parse become NULL, and you can count them.
SELECT s, pg_input_is_valid(s, 'integer') AS is_int, CASE WHEN pg_input_is_valid(s, 'integer') THEN s::integer END AS as_int FROM (VALUES ('42'), ('4 2'), ('42.5'), (''), ('7')) AS t (s);
s | is_int | as_int -----+--------+------- 42 | true | 42 4 2 | false | NULL 42.5 | false | NULL | false | NULL 7 | true | 7 (5 rows)
SELECT s, pg_input_is_valid(s, 'date') AS is_date FROM (VALUES ('2026-03-15'), ('2026-02-30'), ('15/03/2026'), ('2026-13-01')) AS t (s);
s | is_date -----------+-------- 2026-03-15 | true 2026-02-30 | false 15/03/2026 | false 2026-13-01 | false (4 rows)
Part 4 · Reshaping JSON
Building nested JSON from rows
APIs speak nested JSON, and the database stores flat rows. A common job is to return one document for each order with its lines inside it, without making the application stitch the rows together. PostgreSQL has functions for building JSON from rows and for taking it apart again, and they work on the jsonb type, the binary form that stores parsed JSON.
jsonb_build_object makes an object from alternating keys and values. jsonb_agg is an aggregate that collects the values of a group into a JSON array, and takes an ORDER BY inside the call like string_agg does. Two steps make the document: first build the array of lines for each order in a CTE, then put it into an object next to the order's own columns. The order of the lines is fixed by the sort inside the aggregate.
WITH items AS ( SELECT oi.order_id, jsonb_agg( jsonb_build_object('product', p.name, 'qty', oi.qty) ORDER BY p.name) AS list FROM order_items AS oi JOIN products AS p ON p.product_id = oi.product_id GROUP BY oi.order_id ) SELECT jsonb_pretty(jsonb_build_object( 'order_id', o.order_id, 'customer', c.name, 'items', coalesce(i.list, '[]'::jsonb))) AS "RAW" FROM orders AS o JOIN customers AS c ON c.customer_id = o.customer_id LEFT JOIN items AS i ON i.order_id = o.order_id WHERE o.order_id = 1;
{
"items": [
{
"qty": 1,
"product": "Basmati rice 5 kg"
},
{
"qty": 2,
"product": "Toned milk 1 L"
}
],
"customer": "Asha Rao",
"order_id": 1
}Two things to see in the output. The keys are not in the order they were written, items comes before customer and qty before product. The documentation says that jsonb does not preserve the order of object keys. It also mentions, while explaining how objects are compared, that shorter keys are stored before longer ones, which is what this run shows. Never depend on the key order of a jsonb value. And the array of items keeps its order, because arrays are ordered.
Orders without lines
An order with no lines produces no row in the items CTE, since a group needs at least one row. The LEFT JOIN keeps the order, and coalesce turns the missing list into an empty array. Without it the document would have a null where every client expects a list.
WITH items AS ( SELECT oi.order_id, jsonb_agg( jsonb_build_object('product', p.name, 'qty', oi.qty) ORDER BY p.name) AS list FROM order_items AS oi JOIN products AS p ON p.product_id = oi.product_id GROUP BY oi.order_id ) SELECT jsonb_build_object( 'order_id', o.order_id, 'customer', c.name, 'items', coalesce(i.list, '[]'::jsonb))::text AS doc FROM orders AS o JOIN customers AS c ON c.customer_id = o.customer_id LEFT JOIN items AS i ON i.order_id = o.order_id WHERE o.order_id = 3;
doc
----------------------------------------------------
{"items": [], "customer": "Asha Rao", "order_id": 3}
(1 row)The same pattern builds the nested result of a whole report in one query. It is worth knowing, and it has a cost: a large document is built in memory, and the client receives it as one value. For pages of a list, fetch rows. Use nested JSON when the consumer wants the document.
To practise taking documents apart, the lesson stores the documents in a table, order_docs, with one jsonb column.
CREATE TABLE order_docs AS WITH items AS ( SELECT oi.order_id, jsonb_agg( jsonb_build_object('product', p.name, 'qty', oi.qty) ORDER BY p.name) AS list FROM order_items AS oi JOIN products AS p ON p.product_id = oi.product_id GROUP BY oi.order_id ) SELECT o.order_id, jsonb_build_object( 'customer', c.name, 'items', coalesce(i.list, '[]'::jsonb)) AS doc FROM orders AS o JOIN customers AS c ON c.customer_id = o.customer_id LEFT JOIN items AS i ON i.order_id = o.order_id;
Reading and flattening JSON
The arrow operators read a document. -> returns JSON, so it can be followed by another arrow, and ->> returns text. A key that is not there gives NULL, and so does an array index out of range.
SELECT order_id, doc ->> 'customer' AS customer, jsonb_array_length(doc -> 'items') AS item_lines, doc -> 'items' -> 0 ->> 'product' AS first_product FROM order_docs ORDER BY order_id;
order_id | customer | item_lines | first_product ---------+-----------------+------------+------------------ 1 | Asha Rao | 2 | Basmati rice 5 kg 2 | Ravi Kumar Naik | 3 | Curd 500 g 3 | Asha Rao | 0 | NULL (3 rows)
To get one row for each element of an array, jsonb_array_elements is the JSON counterpart of unnest. It is used in a lateral join, and ->> plus a cast reads the fields.
SELECT d.order_id, e.item ->> 'product' AS product, (e.item ->> 'qty')::int AS qty FROM order_docs AS d CROSS JOIN LATERAL jsonb_array_elements(d.doc -> 'items') AS e (item) ORDER BY d.order_id, product;
order_id | product | qty ---------+----------------------+---- 1 | Basmati rice 5 kg | 1 1 | Toned milk 1 L | 2 2 | Curd 500 g | 3 2 | Salted peanuts 200 g | 2 2 | Toned milk 1 L | 1 (5 rows)
jsonb_to_recordset does the same and also names and types the columns in one step, so the fields are read for you.
SELECT d.order_id, r.product, r.qty FROM order_docs AS d CROSS JOIN LATERAL jsonb_to_recordset(d.doc -> 'items') AS r (product text, qty int) ORDER BY d.order_id, r.product;
order_id | product | qty ---------+----------------------+---- 1 | Basmati rice 5 kg | 1 1 | Toned milk 1 L | 2 2 | Curd 500 g | 3 2 | Salted peanuts 200 g | 2 2 | Toned milk 1 L | 1 (5 rows)
There are two ways to go wrong. The first is order 3, whose array is empty: a cross join would drop it, as it did with the empty tag array. A left join keeps it.
SELECT d.order_id, count(r.product) AS item_rows FROM order_docs AS d LEFT JOIN LATERAL jsonb_to_recordset(d.doc -> 'items') AS r (product text, qty int) ON true GROUP BY d.order_id ORDER BY d.order_id;
All chapters · Previous: Sequencing and Hierarchy Patterns: Streaks, Sessions and Recursive Trees