Introduction
JSON columns let you store flexible data inside a table. This helps when data doesn't fit fixed columns.
JSON columns let you store flexible data inside a table. This helps when data doesn't fit fixed columns.
CREATE TABLE table_name ( column_name JSON );
JSON type to store JSON data as text with validation.JSONB for faster queries and indexing.info to store user data.CREATE TABLE users ( id SERIAL PRIMARY KEY, info JSON );
JSONB column for efficient JSON storage and queries.CREATE TABLE products ( id SERIAL PRIMARY KEY, details JSONB );
This example creates an employees table with a JSON column attributes. It inserts two employees with JSON data about age and skills, then selects all rows.
CREATE TABLE employees ( id SERIAL PRIMARY KEY, name TEXT, attributes JSON ); INSERT INTO employees (name, attributes) VALUES ('Alice', '{"age": 30, "skills": ["SQL", "Python"]}'), ('Bob', '{"age": 25, "skills": ["Java", "React"]}'); SELECT id, name, attributes FROM employees;
JSON columns store data as text but check it is valid JSON.
Use JSONB if you want faster searching inside JSON data.
Remember to use single quotes around JSON strings in SQL.
JSON columns let you store flexible, structured data inside tables.
Use CREATE TABLE with JSON or JSONB type to add JSON columns.
Insert JSON data as strings inside single quotes.
JSON column in a PostgreSQL table?data?CREATE TABLE products (id SERIAL, info JSONB); and the insert statement:INSERT INTO products (info) VALUES ('{"name": "Pen", "price": 1.5}');SELECT info->>'name' FROM products WHERE id = 1;CREATE TABLE users (id INT, profile JSONB DEFAULT {});orders with a JSONB column details that stores order info. You also want to ensure each order has a customer_id and a details JSON with a total field as a number. Which approach correctly creates the table and enforces the total field presence?Pass the test and this pattern moves unknown