Bird
Raised Fist0
PostgreSQLquery~10 mins

Creating JSON columns in PostgreSQL - Visual Walkthrough

Choose your learning style10 modes available
Concept Flow - Creating JSON columns
Start: Define Table
↓
Specify Column Name and Type JSON or JSONB
↓
Execute CREATE TABLE Statement
↓
Table Created with JSON Column
↓
Insert JSON Data into Column
↓
Query JSON Data from Table
This flow shows how to create a table with a JSON column, insert JSON data, and query it.
Execution Sample
PostgreSQL
CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  info JSONB
);

INSERT INTO users (info) VALUES ('{"name": "Alice", "age": 30}');
Creates a table with a JSONB column and inserts a JSON object into it.
Execution Table
StepSQL CommandActionResult
1CREATE TABLE users (id SERIAL PRIMARY KEY, info JSONB);Create table with JSONB columnTable 'users' created with columns 'id' and 'info' (JSONB)
2INSERT INTO users (info) VALUES ('{"name": "Alice", "age": 30}');Insert JSON data into 'info' columnOne row inserted with JSON data in 'info'
3SELECT * FROM users;Query all rowsReturns rows with 'id' and JSON data in 'info' column
4SELECT info->>'name' FROM users;Extract 'name' from JSONReturns 'Alice' from JSON data
5ENDNo more commandsExecution complete
💡 All commands executed successfully; JSON column created and data inserted.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
Table 'users'Does not existExists with columns 'id' and 'info' (JSONB)SameSameSame
Row count00111
info column dataN/AN/A{"name": "Alice", "age": 30}{"name": "Alice", "age": 30}{"name": "Alice", "age": 30}
Key Moments - 3 Insights
Why do we use JSONB instead of JSON for the column type?
JSONB stores JSON data in a binary format that is faster to query and index, as shown in Step 1 where the column is defined as JSONB.
How is JSON data inserted into the JSONB column?
In Step 2, JSON data is inserted as a string literal representing a JSON object, which PostgreSQL converts into JSONB format automatically.
How do we extract a value from the JSON column?
Step 4 shows using the ->> operator to extract the 'name' field as text from the JSONB column.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the data type of the 'info' column after Step 1?
ATEXT
BJSONB
CVARCHAR
DINTEGER
💡 Hint
Check Step 1 in the execution table where the table is created.
At which step is JSON data inserted into the table?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look for the INSERT command in the execution table.
If we want to get the 'age' from the JSON column, which SQL operator would we use similar to Step 4?
A||
B::json
C->>
D->
💡 Hint
Step 4 uses ->> to extract 'name' as text from JSON.
Concept Snapshot
CREATE TABLE table_name (
  column_name JSON or JSONB
);

Use JSONB for efficient storage and querying.
Insert JSON data as string literals.
Use ->> operator to extract text values from JSON columns.
Full Transcript
This lesson shows how to create a table with a JSON column in PostgreSQL. First, you define the table with a column of type JSON or JSONB. JSONB is preferred because it stores data in a binary format that is faster to query. Then, you insert JSON data as a string literal into the JSONB column. Finally, you can query the table and extract values from the JSON data using the ->> operator. The execution table traces these steps with commands and results. The variable tracker shows the table and data state after each step. Key moments clarify why JSONB is used, how data is inserted, and how to extract values. The quiz tests understanding of these steps and operators.

Practice

(1/5)
1. What is the main purpose of creating a JSON column in a PostgreSQL table?
easy
A. To enforce strict relational data types
B. To create indexes automatically
C. To speed up numeric calculations
D. To store flexible, structured data inside a single column

Solution

  1. Step 1: Understand JSON column usage

    JSON columns allow storing data that can have varying structure, unlike fixed columns.
  2. Step 2: Compare with other options

    Options A, C, and D do not describe JSON columns' purpose; they relate to other database features.
  3. Final Answer:

    To store flexible, structured data inside a single column -> Option D
  4. Quick Check:

    JSON columns = flexible data storage [OK]
Hint: JSON columns store flexible data, not fixed types [OK]
Common Mistakes:
  • Thinking JSON columns enforce strict types
  • Confusing JSON with indexing features
  • Assuming JSON speeds numeric calculations
2. Which of the following is the correct syntax to create a table with a JSON column named data?
easy
A. CREATE TABLE mytable (id INT, data JSONB STRING);
B. CREATE TABLE mytable (id INT, data JSON);
C. CREATE TABLE mytable (id INT, data TEXT JSON);
D. CREATE TABLE mytable (id INT, data STRING);

Solution

  1. Step 1: Recall JSON column syntax

    In PostgreSQL, JSON columns are declared with type JSON or JSONB directly.
  2. Step 2: Check each option

    CREATE TABLE mytable (id INT, data JSON); uses correct syntax. Options A, B, and C use invalid or mixed types.
  3. Final Answer:

    CREATE TABLE mytable (id INT, data JSON); -> Option B
  4. Quick Check:

    JSON column syntax = CREATE TABLE mytable (id INT, data JSON); [OK]
Hint: Use JSON or JSONB as column type directly [OK]
Common Mistakes:
  • Using STRING or TEXT with JSON incorrectly
  • Combining JSON with other types in declaration
  • Missing commas or parentheses
3. Given the table created as CREATE TABLE products (id SERIAL, info JSONB); and the insert statement:
INSERT INTO products (info) VALUES ('{"name": "Pen", "price": 1.5}');
What will be the result of the query:
SELECT info->>'name' FROM products WHERE id = 1;
medium
A. {"name": "Pen", "price": 1.5}
B. 1.5
C. Pen
D. NULL

Solution

  1. Step 1: Understand JSONB insert and query

    The JSONB column stores the JSON object. The operator ->> extracts the text value of the key.
  2. Step 2: Analyze the query

    The query selects the 'name' field as text from the JSONB column for id 1, which is 'Pen'.
  3. Final Answer:

    Pen -> Option C
  4. Quick Check:

    info->>'name' = 'Pen' [OK]
Hint: Use ->> to get JSON text value by key [OK]
Common Mistakes:
  • Using -> instead of ->> returns JSON, not text
  • Expecting full JSON instead of single value
  • Not matching the correct id in WHERE clause
4. You try to create a table with a JSON column using:
CREATE TABLE users (id INT, profile JSONB DEFAULT {});
But get a syntax error. What is the problem?
medium
A. Missing quotes around the default JSON value
B. JSONB columns cannot have default values
C. Empty braces {} are not valid default for JSONB
D. INT type cannot be used with JSONB columns

Solution

  1. Step 1: Check default value syntax for JSONB

    Default JSON values must be valid JSON strings, so '{}' must be in single quotes.
  2. Step 2: Identify the error cause

    Using {} without quotes causes syntax error. Correct is DEFAULT '{}'.
  3. Final Answer:

    Missing quotes around the default JSON value -> Option A
  4. Quick Check:

    Default JSON must be quoted [OK]
Hint: Always quote JSON default values as strings [OK]
Common Mistakes:
  • Using unquoted braces {} as default
  • Assuming JSONB cannot have defaults
  • Confusing data types in table definition
5. You want to create a table 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?
hard
A. CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL CHECK (details->>'total' IS NOT NULL));
B. CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT, details JSONB DEFAULT '{}');
C. CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL);
D. CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL CHECK (details ? 'total'));

Solution

  1. Step 1: Understand JSONB constraints

    To ensure 'total' key exists and is not null, use a CHECK with details->>'total' IS NOT NULL.
  2. Step 2: Evaluate options

    CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL CHECK (details ? 'total')); checks only key presence (details ? 'total'), but does not check value is not null. CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL CHECK (details->>'total' IS NOT NULL)); checks both key and value presence correctly.
  3. Final Answer:

    CREATE TABLE orders (id SERIAL PRIMARY KEY, customer_id INT NOT NULL, details JSONB NOT NULL CHECK (details->>'total' IS NOT NULL)); -> Option A
  4. Quick Check:

    CHECK ensures 'total' key with value [OK]
Hint: Use CHECK with details->>'key' IS NOT NULL to enforce JSON key presence [OK]
Common Mistakes:
  • Using ? operator without checking value
  • Not adding NOT NULL constraints
  • Setting default empty JSON without validation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard