// strings reference

SQL JSON_LENGTH function

JSON_LENGTH(config, '$.tags') returns how many elements the tags array holds, which is the usual test for empty arrays and the basis for per-row item counts.

カテゴリ
Strings
Returns
integer
In this category
158 of 172

構文

JSON_LENGTH(json_doc [, path])  -- MySQL
json_array_length(json [, path])  -- SQLite
jsonb_array_length(jsonb)  -- PostgreSQL

Each block is a separate form. The support table and the examples show which engine takes which.

エンジンサポート

エンジンSupportメモ
SQL Server Not built in no JSON_LENGTH; (SELECT count(*) FROM OPENJSON(...))
PostgreSQL Different name or syntax jsonb_array_length for arrays; count jsonb_object_keys for objects
MySQL はい Supported under this name.
SQLite Different name or syntax json_array_length, arrays only
Oracle Different name or syntax the size() item method: JSON_VALUE(doc, '$.tags.size()')

例

MySQL

SELECT JSON_LENGTH(config, '$.tags') AS tag_count
FROM settings;

SQLite

SELECT json_array_length(payload, '$.items') AS item_count
FROM events;

PostgreSQL

SELECT jsonb_array_length(data->'tags') AS tag_count
FROM payloads;

知っておくと便利なこと

  • Only MySQL's JSON_LENGTH counts object members. SQLite's json_array_length returns 0 for an object, and PostgreSQL's jsonb_array_length raises 'cannot get array length of a non-array'.
  • On MySQL a scalar and JSON null both have length 1, an empty array or object 0, and a missing path returns SQL NULL, not 0.
  • PostgreSQL takes no path argument: navigate first, jsonb_array_length(config->'tags'). MySQL and SQLite accept the path inline.

Questions about JSON_LENGTH

How do I find rows with empty JSON arrays?

WHERE JSON_LENGTH(config, '$.tags') = 0 (MySQL), json_array_length(config, '$.tags') = 0 (SQLite) or jsonb_array_length(data->'tags') = 0 (PostgreSQL). A missing path gives NULL, so add OR ... IS NULL if absence counts as empty.

How do I count an object's keys on PostgreSQL?

There is no jsonb_object_length. Use (SELECT count(*) FROM jsonb_object_keys(doc)) as a scalar subquery.

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: PostgreSQL, MySQL, SQLite, Oracle.

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