SQL array subscripting
tags[1] on a PostgreSQL array and '$[0]' in a JSON path both mean the first element. Out-of-range reads return NULL rather than an error.
- Returns
element type- In this category
- 29 of 39
語法
array[subscript] -- PostgreSQL, 1-based
json_path '$[i]' -- JSON, 0-based
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Different name or syntax | JSON paths only: JSON_VALUE(config, '$.tags[0]') |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Different name or syntax | See the examples and notes below. |
| SQLite | 是 | Supported under this name. |
| Oracle | Not built in | no array subscripts in SQL over collections; use TABLE() and rownum |
範例
PostgreSQL
SELECT tags[1] AS first_tag FROM articles;
MySQL
SELECT config->>'$.tags[0]' AS first_tag FROM settings;
SQLite
SELECT json_extract(payload, '$.items[0]') AS first_item FROM events;
SQL Server
SELECT JSON_VALUE(config, '$.tags[0]') AS first_tag FROM settings;
小知識
- PostgreSQL arrays are 1-based: tags[1] is the first element and tags[0] is NULL. JSON paths on MySQL, SQL Server and SQLite are 0-based: '$[0]' is first. Same data, two conventions.
- Out-of-range array subscripts return NULL on PostgreSQL instead of erroring; writing beyond the current end pads with NULLs up to the index.
- Last element: tags[array_upper(tags, 1)] on PostgreSQL arrays, data->-1 on PostgreSQL jsonb, '$[last]' on MySQL, '$[#-1]' on SQLite. '$[-1]' is an invalid path on MySQL and SQLite, and arr[-1] on a PostgreSQL array is just NULL.
Questions about Array indexing
Why is arr[0] NULL?
PostgreSQL arrays start at 1. The first element is arr[1]; index 0 sits below the lower bound and reads as NULL rather than erroring.
Which indexing does my JSON use?
Zero-based, always, in the JSON path of MySQL, SQL Server and SQLite, even though PostgreSQL array columns are 1-based. Check the type before writing the subscript.
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: SQL Server, PostgreSQL, MySQL, SQLite.
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.