Example 1
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.
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;| id | tag_count |
|---|---|
| 1 | 2 |
| 2 | 1 |
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;| id | tag_count |
|---|---|
| 1 | 2 |
| 2 | 1 |
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;| id | tag_count |
|---|---|
| 1 | 2 |
| 2 | 1 |
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;| id | tag_count |
|---|---|
| 1 | 2 |
| 2 | 1 |
SQL Server counts rows returned by OPENJSON because it does not expose a direct JSON_ARRAY_LENGTH scalar function.