// conversion reference

SQL UNNEST function

SELECT unnest(tags) turns one array value into one row per element, so array columns can be joined, filtered and grouped like ordinary rows.

類別
Conversion
Returns
setof element type
In this category
26 of 39

語法

UNNEST(array)
unnest(array) WITH ORDINALITY

Each block is a separate form. The support table and the examples show which engine takes which.

引擎支援

引擎Support備註
SQL Server Not built in no array type; OPENJSON for JSON arrays
PostgreSQL 是 Supported under this name.
MySQL Not built in no array type; JSON_TABLE for JSON arrays
SQLite Different name or syntax json_each for JSON arrays
Oracle Different name or syntax TABLE(collection) unwraps nested tables

範例

PostgreSQL

SELECT unnest(tags) AS tag FROM articles;

PostgreSQL

SELECT t.tag, t.pos
FROM articles a,
unnest(a.tags) WITH ORDINALITY AS t(tag, pos);

PostgreSQL

SELECT count(*) FROM unnest(ARRAY['a', 'b', 'c']);

小知識

  • unnest(a, b) in FROM zips arrays by position and pads the shorter one with NULL: unnest(ARRAY[1,2,3], ARRAY['x','y']) gives (1,x), (2,y), (3,NULL). Two unnest calls in the SELECT list behave the same way on PostgreSQL 10+.
  • unnest returns elements in array order, but a later join or GROUP BY can reorder rows. WITH ORDINALITY adds the position so you can ORDER BY it.
  • SQLite's json_each and MySQL's JSON_TABLE fill this role for JSON arrays; SQL Server uses OPENJSON. The concept ports, the syntax does not.

Questions about UNNEST

How do I keep the element index?

WITH ORDINALITY: unnest(a.tags) WITH ORDINALITY AS t(tag, pos) adds a bigint position column, 1-based, matching the array order.

Why did rows with empty arrays vanish?

Each outer row is repeated once per element, so an empty or NULL array contributes no rows and the outer row drops out. Keep it with LEFT JOIN LATERAL unnest(a.tags) AS t(tag) ON true.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.