Lab 18: PostgreSQL JSONB & Arrays
Overview
Step 1: Setup
docker run -d --name pg-lab -e POSTGRES_PASSWORD=rootpass postgres:15
sleep 10
docker exec pg-lab psql -U postgres << 'EOF'
CREATE DATABASE jsonlab;
EOF
docker exec pg-lab psql -U postgres -d jsonlab << 'EOF'
-- Table with array and JSONB columns
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
tags TEXT[], -- array of text
sizes INT[], -- array of integers
metadata JSONB, -- binary JSON (indexed, fast)
created_at TIMESTAMP DEFAULT NOW()
);
INSERT INTO products (name, tags, sizes, metadata) VALUES
(
'Laptop Pro 15',
ARRAY['electronics', 'computers', 'portable'],
ARRAY[256, 512, 1024],
'{"brand": "TechCo", "color": "silver", "specs": {"ram": 16, "cpu": "M2"}, "ratings": [4, 5, 5, 4], "in_stock": true, "price": 1299.99}'
),
(
'Wireless Mouse',
ARRAY['electronics', 'peripherals', 'wireless'],
NULL,
'{"brand": "ClickMaster", "color": "black", "specs": {"dpi": 1600, "buttons": 6}, "ratings": [4, 3, 5], "in_stock": true, "price": 29.99}'
),
(
'SQL Mastery Book',
ARRAY['books', 'education', 'technology'],
NULL,
'{"author": "Jane Doe", "isbn": "978-0-000-00000-0", "edition": 3, "ratings": [5, 5, 4, 5], "in_stock": false, "price": 49.99}'
),
(
'Ergonomic Chair',
ARRAY['furniture', 'office', 'ergonomic'],
ARRAY[1, 2, 3],
'{"brand": "ComfortSeat", "color": "gray", "specs": {"max_weight_kg": 120, "adjustable": true}, "ratings": [4, 4, 3], "in_stock": true, "price": 399.99}'
),
(
'USB-C Hub',
ARRAY['electronics', 'peripherals', 'connectivity'],
NULL,
'{"brand": "ConnectAll", "color": "silver", "specs": {"ports": 7, "usb3": true}, "ratings": [5, 4, 5, 5], "in_stock": true, "price": 49.99}'
);
EOFStep 2: Array Columns — Basic Operations
Step 3: Array Operators
Step 4: JSONB Extraction — -> and ->>
-> and ->>Step 5: JSONB Key Existence and Querying
Step 6: jsonb_set — Update JSONB Values
Step 7: GIN Index on JSONB
Step 8: Capstone — JSONB Analytics
Summary
Feature
Syntax
Description
Last updated
