Example 1
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.
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;| id | title |
|---|---|
| 1 | Intro |
| 3 | Joins |
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;| id | title |
|---|---|
| 1 | Intro |
| 3 | Joins |
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;| id | title |
|---|---|
| 1 | Intro |
| 3 | Joins |
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;| id | title |
|---|---|
| 1 | Intro |
| 3 | Joins |
The JSON predicate differs by engine, but all return posts whose array contains the string sql.