Introduction
JSON support in PostgreSQL lets you store and work with flexible data easily. It helps when data doesn't fit neatly into tables.
JSON support in PostgreSQL lets you store and work with flexible data easily. It helps when data doesn't fit neatly into tables.
CREATE TABLE table_name ( id SERIAL PRIMARY KEY, data JSON ); -- Insert JSON data INSERT INTO table_name (data) VALUES ('{"key": "value"}'); -- Query JSON data SELECT data->>'key' FROM table_name;
CREATE TABLE users ( id SERIAL PRIMARY KEY, info JSON );
INSERT INTO users (info) VALUES ('{"name": "Alice", "age": 30}');
SELECT info->>'name' AS user_name FROM users;
This example creates a products table with JSON details. It inserts two products and then selects their names and prices from the JSON data.
CREATE TABLE products ( id SERIAL PRIMARY KEY, details JSON ); INSERT INTO products (details) VALUES ('{"name": "Pen", "color": "blue", "price": 1.5}'), ('{"name": "Notebook", "color": "red", "price": 3.0}'); SELECT details->>'name' AS product_name, details->>'price' AS product_price FROM products;
JSON columns let you store data without a fixed structure.
You can index JSON fields for faster queries using GIN indexes.
PostgreSQL also supports JSONB, a binary format that is faster to query.
JSON support allows flexible data storage inside PostgreSQL tables.
You can query and manipulate JSON data directly in SQL.
This helps when data structure changes or is not fixed.
users with a JSON column profile, what does this query return?SELECT profile->>'name' FROM users WHERE profile->>'age' = '30';
SELECT * FROM orders WHERE details->'price' = 100;
events with a JSONB column data storing event details. You want to find all events where the nested JSON key location.city is 'Paris'. Which query correctly achieves this?Pass the test and this pattern moves unknown