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.
Related on SQLly
- List foreign keys and the tables/columns they point at Snippet
- Find foreign keys without a supporting index in PostgreSQL Snippet
- Generate DDL for missing foreign-key indexes in SQL Server Snippet
- Split a comma-separated field into rows in SQL Snippet
- Show who blocks whom in PostgreSQL Snippet
Cheat sheets for the engines that have it: PostgreSQL, SQLite, Oracle.
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.