// strings reference

MySQL JSON_SEARCH

JSON_SEARCH(doc, 'one', 'x') answers 'where in this document is the string x?' with a path such as "$.a".

Категория
Strings
Returns
JSON (a path string or an array of paths), or NULL
In this category
170 of 172

Синтаксис

JSON_SEARCH(doc, 'one' | 'all', search_str [, escape_char [, path ...]])

Поддержка движка

ДвижокSupportЗаметки
SQL Server Not built in no direct function; recursive OPENJSON can rebuild paths
PostgreSQL Different name or syntax jsonb_path_exists with a filter tests for a value but returns no path
MySQL Да JSON_SEARCH
SQLite Different name or syntax json_tree(doc) with WHERE atom = 'x' returns fullkey paths
Oracle Different name or syntax JSON_EXISTS with a filter tests for a value but returns no path

Примеры

MySQL

SELECT JSON_SEARCH('{"a":"x","b":["y","x"]}', 'one', 'x') AS first_path,
       JSON_SEARCH('{"a":"x","b":["y","x"]}', 'all', 'x') AS all_paths;  -- "$.a", ["$.a", "$.b[1]"]

MySQL

SELECT JSON_REMOVE(doc, JSON_UNQUOTE(JSON_SEARCH(doc, 'one', 'old'))) AS cleaned
FROM (SELECT '["new", "old"]' AS doc) AS t;  -- ["new"]

SQLite

SELECT fullkey FROM json_tree('{"a":"x","b":["y","x"]}') WHERE atom = 'x';  -- $.a, $.b[1]

Полезно знать

  • It finds string values only: JSON_SEARCH('[1,2]', 'one', '1') is NULL.
  • The search string is a LIKE pattern, so % and _ are wildcards: 'ab%' matches both "abc" and "abd". Pass an escape character as the fourth argument to search for them literally.
  • 'one' returns a single path as a JSON string and 'all' returns an array. Wrap the result in JSON_UNQUOTE before passing it to JSON_EXTRACT or JSON_REMOVE.

Questions about JSON_SEARCH

How do I remove an array element by value in MySQL?

Find its path and remove it: JSON_REMOVE(doc, JSON_UNQUOTE(JSON_SEARCH(doc, 'one', 'old'))). Guard against a NULL path when the value is absent, because JSON_REMOVE with a NULL path returns NULL.

Can JSON_SEARCH find numbers?

No. For numbers use JSON_CONTAINS(doc, '1') to test, or JSON_TABLE to unnest and filter.

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.