PostgreSQL Features Deep Dive: Concept
Module: Database-Specific Features
PostgreSQL is the most advanced open-source database with features that eliminate need for external tools. Key features: (1) JSONB: Binary JSON storage (2-3x faster than MySQL JSON, indexable with GIN indexes). (2) Arrays: Native array support (no junction tables for simple lists). (3) MVCC: Multi-Version Concurrency Control (non-blocking reads during writes). (4) Full-text search: Built-in search (no Elasticsearch needed for simple cases). (5) Extensions: PostGIS (geographic data), pg_trgm (fuzzy search), custom extensions. Real-world: Instagram uses arrays for hashtags, MVCC for concurrency. Uber uses PostGIS for location queries, MVCC for ride matching. Shopify uses JSONB for product metadata. GitLab uses full-text search for code search. Trade-off: More features but steeper learning curve than MySQL.
**1. JSONB - Binary JSON Storage:**
JSONB is PostgreSQL's binary JSON format. Faster than MySQL JSON (text-based) for queries.
**JSONB vs JSON:**
- **JSONB (Binary)**: Stored as binary, parsed once on insert, fast queries, indexable with GIN. Use this.
- **JSON (Text)**: Stored as text, parsed on every query, slow, not indexable. Don't use.
**Performance:**
- JSONB insert: Slower (parse on insert)
- JSONB query: 2-3x faster than MySQL JSON
- JSONB with GIN index: 10-100x faster than without index
**JSONB Operators:**
- `->`: Get JSON object field (returns JSON)
- `->>`: Get JSON object field (returns text)
- `#>`: Get nested JSON object
- `#>>`: Get nested JSON object (returns text)
- `@>`: Contains (does left JSON contain right JSON?)
- `?`: Does key exist?
- `?|`: Does any key exist?
- `?&`: Do all keys exist?
**Example: Product metadata**
```sql
CREATE TABLE products (
product_id SERIAL PRIMARY KEY,
name VARCHAR(200),
price DECIMAL(10,2),
attributes JSONB -- Flexible metadata
);
-- Insert product with JSONB attributes
INSERT INTO products (name, price, attributes) VALUES (
'Wireless Headphones',
99.99,
'{"brand": "Sony", "color": "black", "features": ["noise-canceling", "bluetooth"], "rating": 4.5}'
);
-- Query: Get products by brand (-> returns JSON)
SELECT name, attributes->'brand' as brand
FROM products
WHERE attributes->>'brand' = 'Sony';
-- Result: brand is JSON "Sony"
-- Query: Get products by brand (->> returns text)
SELECT name, attributes->>'brand' as brand