sqlcmd.net validated sql reference
intermediate json MySQL MariaDB SQL Server PostgreSQL SQLite

Count Elements In A JSON Array

Return the number of items stored in a JSON array value.

Docker-validated Not currently validation-green

Count tags stored in a JSON array column

The first JSON array has two elements and the second has one. The array is not split into output rows; each post remains one row with a count.

MySQL MariaDB
Engine-specific syntax
Setup
CREATE TABLE posts (id INT, tags VARCHAR(200));

INSERT INTO
  posts
VALUES
  (1, '["sql","json"]'),
  (2, '["database"]');
SQL
SELECT
  id,
  JSON_LENGTH (tags) AS tag_count
FROM
  posts
ORDER BY
  id;
idtag_count
12
21
SQL Server
Engine-specific syntax
Setup
CREATE TABLE posts (id INT, tags NVARCHAR (200));

INSERT INTO
  posts
VALUES
  (1, '["sql","json"]'),
  (2, '["database"]');
SQL
SELECT
  id,
  (
    SELECT
      COUNT(*)
    FROM
      OPENJSON (tags)
  ) AS tag_count
FROM
  posts
ORDER BY
  id;
idtag_count
12
21
PostgreSQL
Engine-specific syntax
Setup
CREATE TABLE posts (id INT, tags JSONB);

INSERT INTO
  posts
VALUES
  (1, '["sql","json"]'),
  (2, '["database"]');
SQL
SELECT
  id,
  JSONB_ARRAY_LENGTH (tags) AS tag_count
FROM
  posts
ORDER BY
  id;
idtag_count
12
21
SQLite
Engine-specific syntax
Setup
CREATE TABLE posts (id INT, tags TEXT);

INSERT INTO
  posts
VALUES
  (1, '["sql","json"]'),
  (2, '["database"]');
SQL
SELECT
  id,
  json_array_length (tags) AS tag_count
FROM
  posts
ORDER BY
  id;
idtag_count
12
21

SQL Server counts rows returned by OPENJSON because it does not expose a direct JSON_ARRAY_LENGTH scalar function.

Where this command helps.

  • finding rows with at least one JSON tag
  • auditing how many items are stored in a JSON array column

What the command is doing.

JSON array length functions are useful when records store tags, selected options, or embedded child values as JSON. Each engine uses a different function name or JSON path convention, but the task is the same: count the elements at a JSON array path.