// strings reference

SQL JSON_CONTAINS function

JSON_CONTAINS(config->'$.tags', '"pro"') asks whether the value pro is among the tags. The candidate must itself be JSON, quoting included.

類別
Strings
Returns
integer
In this category
150 of 172

語法

JSON_CONTAINS(target, candidate [, path])

引擎支援

引擎Support備註
SQL Server Not built in No built-in equivalent.
PostgreSQL Different name or syntax the @> containment operator on jsonb
MySQL 是 Supported under this name.
SQLite Different name or syntax no JSON_CONTAINS; EXISTS over json_each
Oracle Different name or syntax JSON_EXISTS condition covers the key case

範例

MySQL

SELECT * FROM settings
WHERE JSON_CONTAINS(config->'$.tags', '"pro"');

MySQL

SELECT * FROM settings
WHERE JSON_CONTAINS_PATH(config, 'one', '$.region');

SQLite

SELECT * FROM settings WHERE EXISTS
  (SELECT 1 FROM json_each(config, '$.tags')
   WHERE value = 'pro');

小知識

  • The candidate is JSON, not a literal: to find the string pro you search for '"pro"'; the double quotes are part of the value being matched.
  • Key existence is a different function: JSON_CONTAINS_PATH(doc, 'one'| 'all', '$.region'), the semantic twin of PostgreSQL's ? and ?| operators.
  • Large documents scan linearly without help: a MySQL multi-valued index over the array or a PostgreSQL GIN index on the jsonb column is what makes this fast at scale.

Questions about JSON_CONTAINS

How do I check whether a key exists?

JSON_CONTAINS_PATH(config, 'one', '$.region') on MySQL, config ? 'region' on PostgreSQL jsonb, JSON_EXISTS on Oracle. JSON_CONTAINS is for values, not keys.

Why does my search for pro never match?

You passed the SQL text pro, not the JSON string '"pro"'. JSON_CONTAINS compares JSON to JSON; quote string candidates.

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.