Arrays and unnesting
Overview
An array holds an ordered collection of elements of one declared type in PostgreSQL. It can represent a small list of labels or readings. Learn to expand elements with their positions, distinguish empty arrays from NULL and decide when a child table is better. SQLite has no native array type; this laboratory uses validated JSON arrays and json_each().
First example
SELECT d.id,e.key,e.value FROM ct_device d JOIN json_each(d.readings) e ORDER BY d.id,e.key;Observed SQLite result (rows in JSON):
[ [ 1, 0, 10 ], [ 1, 1, null ], [ 1, 2, 20 ], [ 3, 0, 5 ]]How it works
PostgreSQL arrays normally start at index 1 but can have other lower bounds. UNNEST expands values; WITH ORDINALITY adds a one-based output position, not necessarily the original subscript. SQLite json_each exposes zero-based array keys. Use ORDER BY explicitly. INNER JOIN drops empty collections; LEFT JOIN can preserve their parent. NULL elements are not absent elements. JSON arrays can mix types, unlike a PostgreSQL integer array.
Practical example
SELECT d.id,COUNT(e.key),COUNT(e.value) FROM ct_device d LEFT JOIN json_each(d.readings) e ON 1=1 GROUP BY d.id ORDER BY d.id;Observed SQLite result (rows in JSON):
[ [ 1, 3, 2 ], [ 2, 0, 0 ], [ 3, 1, 1 ]]Practice and mistakes
Practice: return each device ID and its number of readings, including empty collections and NULL elements. Hint 1: start from the device table. Hint 2: use json_array_length() rather than COUNT(value) to include JSON null. Expected counts: 3, 0, 1. Do not store relationships that require independent foreign keys inside arrays; use a child table with a position column and uniqueness constraint.
PostgreSQL 17 example — NOT RUN
SELECT pos, val FROM unnest(ARRAY[10,NULL,20]::integer[]) WITH ORDINALITY AS u(val,pos) ORDER BY pos;Expected result, not executed: [[1, 10], [2, null], [3, 20]]