// strings reference

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.

카테고리
Strings
Returns
integer
In this category
159 of 172

구문

JSON_DEPTH(json_doc)

엔진 지원

엔진Support메모
SQL Server Not built in no equivalent
PostgreSQL Not built in no equivalent; a recursive CTE over jsonb_each can compute it
MySQL 예 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

예시

MySQL

SELECT JSON_DEPTH(config) AS levels FROM settings;

MySQL

SELECT JSON_DEPTH('{}') AS empty_obj, JSON_DEPTH('[[1]]') AS nested;  -- 1, 3

알아 두면 좋은 정보

  • 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.

Cheat sheets for the engines that have it: MySQL.

// fewer lookups

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.