SQL JSON_DEPTH function
JSON_DEPTH('[[1]]') is 3. It is a quick way to flag documents that nest deeper than your queries or indexes expect.
- Kategorie
- Strings
- Returns
integer- In this category
- 159 of 172
Syntax
JSON_DEPTH(json_doc)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Not built in | no equivalent |
| PostgreSQL | Not built in | no equivalent; a recursive CTE over jsonb_each can compute it |
| MySQL | Ja | Supported under this name. |
| SQLite | Not built in | no json_depth; json_tree's fullkey paths show the nesting |
| Oracle | Not built in | no equivalent |
Beispiele
MySQL
SELECT JSON_DEPTH(config) AS levels FROM settings;
MySQL
SELECT JSON_DEPTH('{}') AS empty_obj, JSON_DEPTH('[[1]]') AS nested; -- 1, 3
Gut zu wissen
- A scalar, an empty array and an empty object all have depth 1. A non-empty array or object adds 1 to the deepest thing it contains: '[1]' is 2, '[[1]]' is 3.
- There is no path argument: depth is for the whole value. Pass JSON_EXTRACT(doc, '$.items') to measure a subtree.
- MySQL rejects documents nested deeper than 100 levels on input, so JSON_DEPTH never returns more than 100.
Questions about JSON_DEPTH
Why is {} depth 1 but {"a": 1} depth 2?
Empty containers count as one level, like scalars. A container only adds a level when it holds something, so {"a": 1} is 2 and {"a": {"b": 1}} is 3.
How do I measure depth on SQLite?
Walk the tree: json_tree returns one row per node with its fullkey path, such as $.a.b[0]. Counting the path separators in the longest fullkey gives the nesting depth.
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: MySQL.
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.