SQL JSON_KEYS function
JSON_KEYS(config) lists the object's top-level keys as a JSON array, such as ["a", "b", "ccc"]. Pass a path to list the keys of a nested object.
- Category
- Strings
- Returns
JSON array or setof text- In this category
- 157 of 172
Syntax
JSON_KEYS(json_doc [, path])
Engine support
| Engine | Support | Notes |
|---|---|---|
| SQL Server | Not built in | no JSON_KEYS; OPENJSON's key column over the object |
| PostgreSQL | Different name or syntax | jsonb_object_keys / json_object_keys return a rowset |
| MySQL | Yes | Supported under this name. |
| SQLite | Different name or syntax | no json_keys; SELECT key FROM json_each(doc) |
| Oracle | Not built in | no direct twin; shred with JSON_TABLE |
Examples
MySQL
SELECT JSON_KEYS(config) AS keys_arr FROM settings;
MySQL
SELECT JSON_KEYS(config, '$.user') AS user_keys FROM settings;
PostgreSQL
SELECT k FROM settings s, jsonb_object_keys(s.config) k;
Good to know
- Do not rely on order: MySQL stores object keys sorted (shorter keys first, then by byte value) and drops duplicates, so JSON_KEYS('{"b":1,"a":2,"ccc":3}') is ["a", "b", "ccc"].
- Top-level only without the path argument: JSON_KEYS(config, '$.user') digs one level down.
- PostgreSQL's jsonb_object_keys returns a set of rows, one per key. It runs in the SELECT list too, but in FROM with a lateral join you can filter and aggregate the keys.
Questions about JSON_KEYS
How do I iterate all keys and values?
PostgreSQL: jsonb_each. MySQL: JSON_KEYS plus a join over JSON_EXTRACT, or JSON_TABLE. SQLite: json_each does both in one pass, the most convenient of the set.
Why are my keys reordered?
MySQL's JSON type and PostgreSQL's jsonb both store keys sorted (shorter first, then alphabetically). PostgreSQL's json and SQLite's text JSON keep them as written. JSON objects are unordered by definition, so do not depend on it.
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, 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.