// strings reference

SQL JSON_EXTRACT function

JSON_EXTRACT(config, '$.region') walks a path into a JSON document. The returned value is still JSON, which is the source of half the confusion.

Categoria
Strings
Returns
JSON value
In this category
137 of 172

Sintaxe

JSON_EXTRACT(json_doc, path [, path ...])

Suporte a mecanismos

MotorSupportNotas
SQL Server Different name or syntax no JSON_EXTRACT; JSON_VALUE for scalars, JSON_QUERY for fragments
PostgreSQL Different name or syntax the -> operator is the same job
MySQL Sim Supported under this name.
SQLite Sim Supported under this name.
Oracle Different name or syntax JSON_VALUE or simple dot-notation paths

Exemplos

MySQL

SELECT JSON_EXTRACT(config, '$.region') AS region
FROM settings;

SQLite

SELECT json_extract(payload, '$.items[0].sku') AS sku
FROM orders;

MySQL

SELECT JSON_EXTRACT(config, '$.tags[1]') AS second_tag
FROM settings;

Bom saber

  • The result is a JSON value, not text: MySQL returns an extracted string still double-quoted ('"eu"') until you unwrap it with ->> or JSON_UNQUOTE. SQLite's json_extract returns strings unquoted, which is the usual porting surprise.
  • Both engines require a path that starts with $; SQLite rejects json_extract(doc, 'a.b') as a bad path. Only SQLite's -> and ->> operators accept a bare key like 'a'.
  • There are no negative indexes: '$[-1]' is an error on both. The last element is '$[last]' on MySQL and '$[#-1]' on SQLite.
  • Several paths return an array of the results: JSON_EXTRACT(doc, '$.a', '$.b') gives [va, vb] on MySQL and SQLite.

Questions about JSON_EXTRACT

Why is my result wrapped in quotes?

Because it is a JSON string, not SQL text. Use ->> (MySQL, PostgreSQL) or JSON_UNQUOTE (MySQL) to strip the JSON quoting; SQLite's json_extract already returns unwrapped text.

How do I extract from an array?

Zero-based indexes in the path: '$.tags[0]', or with member access '$.items[2].sku'. For the last element, write '$.tags[last]' on MySQL and '$.tags[#-1]' on SQLite.

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: SQL Server, 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.