SQL CARDINALITY function
CARDINALITY(tags) is the SQL-standard element count. On a multidimensional PostgreSQL array it counts every element across all dimensions.
- Categoría
- Conversion
- Returns
integer- In this category
- 25 of 39
Sintaxis
CARDINALITY(collection)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Not built in | no collection types |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Not built in | no collection types; JSON_LENGTH for JSON |
| SQLite | Different name or syntax | json_length for JSON arrays |
| Oracle | Sí | Supported under this name. |
Ejemplos
PostgreSQL
SELECT * FROM articles WHERE CARDINALITY(tags) > 0;
Oracle
SELECT CARDINALITY(phone_list) AS n FROM contacts;
Conviene saberlo
- CARDINALITY(empty) is 0 while ARRAY_LENGTH(empty, 1) is NULL on PostgreSQL; CARDINALITY is the right tool for WHERE clauses over possibly empty arrays.
- On Oracle it works on nested tables only; a VARRAY raises ORA-00932. A NULL collection (as opposed to an empty one) returns NULL, so COALESCE(CARDINALITY(c), 0) when zero matters.
- For a 3x2 PostgreSQL array, CARDINALITY is 6 while ARRAY_LENGTH(arr, 1) is 3. Use CARDINALITY for 'how many values', ARRAY_LENGTH for the size of one dimension.
Questions about CARDINALITY
CARDINALITY or ARRAY_LENGTH?
CARDINALITY for counts: standard spelling, 0 on empty. ARRAY_LENGTH when you need one dimension of a multidimensional PostgreSQL array.
Why NULL instead of 0?
The array or collection itself is SQL NULL, not empty. An empty one counts 0; COALESCE folds the NULL case into zero.
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.