0
0
PostgreSQLquery~5 mins

Why JSON support matters in PostgreSQL

Choose your learning style9 modes available
Introduction

JSON support in PostgreSQL lets you store and work with flexible data easily. It helps when data doesn't fit neatly into tables.

You want to store user preferences that can change often and have different fields.
You need to save data from web APIs that come in JSON format.
You want to combine structured data with flexible extra details without redesigning tables.
You are building a logging system where each log entry can have different information.
You want to query parts of JSON data directly inside the database.
Syntax
PostgreSQL
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;
Use the JSON data type to store JSON text in a column.
Use operators like -> and ->> to access JSON fields.
Examples
This creates a table with a JSON column to store flexible user info.
PostgreSQL
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  info JSON
);
Insert a JSON object with name and age into the info column.
PostgreSQL
INSERT INTO users (info) VALUES ('{"name": "Alice", "age": 30}');
Get the 'name' value from the JSON info for each user.
PostgreSQL
SELECT info->>'name' AS user_name FROM users;
Sample Program

This example creates a products table with JSON details. It inserts two products and then selects their names and prices from the JSON data.

PostgreSQL
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;
OutputSuccess
Important Notes

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.

Summary

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.