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

Filter JSON Arrays Containing A Value

Return rows where a JSON array contains a specific scalar value.

Docker-validated Not currently validation-green

Find posts whose tags array contains sql

Posts 1 and 3 include sql in the tags array. Post 2 contains only json, so it is excluded.

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

INSERT INTO
  posts
VALUES
  (1, 'Intro', '["sql","tutorial"]'),
  (2, 'API', '["json"]'),
  (3, 'Joins', '["sql","joins"]');
SQL
SELECT
  id,
  title
FROM
  posts
WHERE
  JSON_CONTAINS (tags, '"sql"')
ORDER BY
  id;
idtitle
1Intro
3Joins
SQL Server
Engine-specific syntax
Setup
CREATE TABLE posts (id INT, title VARCHAR(50), tags NVARCHAR (200));

INSERT INTO
  posts
VALUES
  (1, 'Intro', '["sql","tutorial"]'),
  (2, 'API', '["json"]'),
  (3, 'Joins', '["sql","joins"]');
SQL
SELECT
  id,
  title
FROM
  posts
WHERE
  EXISTS (
    SELECT
      1
    FROM
      OPENJSON (tags)
    WHERE
      VALUE = 'sql'
  )
ORDER BY
  id;
idtitle
1Intro
3Joins
PostgreSQL
Engine-specific syntax
Setup
CREATE TABLE posts (id INT, title VARCHAR(50), tags JSONB);

INSERT INTO
  posts
VALUES
  (1, 'Intro', '["sql","tutorial"]'),
  (2, 'API', '["json"]'),
  (3, 'Joins', '["sql","joins"]');
SQL
SELECT
  id,
  title
FROM
  posts
WHERE
  tags ? 'sql'
ORDER BY
  id;
idtitle
1Intro
3Joins
SQLite
Engine-specific syntax
Setup
CREATE TABLE posts (id INT, title TEXT, tags TEXT);

INSERT INTO
  posts
VALUES
  (1, 'Intro', '["sql","tutorial"]'),
  (2, 'API', '["json"]'),
  (3, 'Joins', '["sql","joins"]');
SQL
SELECT
  id,
  title
FROM
  posts
WHERE
  EXISTS (
    SELECT
      1
    FROM
      json_each (tags)
    WHERE
      VALUE = 'sql'
  )
ORDER BY
  id;
idtitle
1Intro
3Joins

The JSON predicate differs by engine, but all return posts whose array contains the string sql.

Where this command helps.

  • finding posts tagged with a specific label
  • filtering records that contain a selected option in JSON data

What the command is doing.

JSON containment queries check whether an array stored in a JSON column includes a target value. MySQL and MariaDB provide JSON_CONTAINS; PostgreSQL can use the ? operator on JSONB arrays of strings; SQL Server and SQLite expand the array with JSON table functions and test with EXISTS.