SQL ARRAY_LENGTH function
ARRAY_LENGTH(tags, 1) counts the elements in the first dimension of a PostgreSQL array. Only PostgreSQL has array columns and Oracle has nested-table collections; the other engines keep lists in JSON.
- Категория
- Conversion
- Returns
integer- In this category
- 24 of 39
Синтаксис
ARRAY_LENGTH(array, dimension) -- PostgreSQL
CARDINALITY(collection) -- Oracle
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; count via OPENJSON or a subquery |
| PostgreSQL | Да | Supported under this name. |
| MySQL | Not built in | no array type; JSON_LENGTH over JSON arrays |
| SQLite | Different name or syntax | json_length over JSON arrays |
| Oracle | Different name or syntax | CARDINALITY over nested tables (not varrays) |
Примеры
PostgreSQL
SELECT ARRAY_LENGTH(tags, 1) AS n FROM articles;
PostgreSQL
SELECT CARDINALITY(tags) AS n FROM articles;
Oracle
SELECT CARDINALITY(phone_list) AS n FROM contacts;
Полезно знать
- PostgreSQL's ARRAY_LENGTH takes a dimension: ARRAY_LENGTH(tags, 1) for the first. On an empty array it returns NULL while CARDINALITY returns 0; the two disagree on empties.
- The dimension argument is required: ARRAY_LENGTH(tags) is an error. For a multidimensional array, ARRAY_LENGTH(grid, 2) counts the second dimension.
- SQL Server and MySQL have no array type: length belongs to JSON (OPENJSON row count, JSON_LENGTH) or to COUNT over STRING_SPLIT for delimited text.
Questions about ARRAY_LENGTH
Why is ARRAY_LENGTH NULL for an empty array?
PostgreSQL's empty array has no elements in any dimension, so the length is NULL. CARDINALITY(empty) is 0; prefer it in WHERE clauses to dodge the trap.
Do arrays start at 0 or 1?
PostgreSQL arrays are 1-based unless built with explicit bounds such as '[0:2]={a,b,c}'; array_lower(arr, 1) tells you. JSON array paths are 0-based on every engine.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
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.