Interview Question: "Compare ARRAY vs JSONB for storing lists. When would you use Range types? Explain the performance implications of using complex types." â Asked at MongoDB, Couchbase, Databricks for Data Modeling roles
âšī¸
Difficulty: Advanced | Companies: MongoDB, Couchbase, Databricks, Snowflake, Google BigQuery | Time: 45-60 minutes
Choosing a type is choosing a query plan
Complex types exist to avoid a join, and every one of them charges rent for that convenience. An array is a list with a fixed element type, a map is a set of key-value pairs, a struct is a row with named fields, and a range is an interval with set operations built in. The right question is never which type is most expressive, but which operators, indexes, and cast rules the database must apply when the column appears in a predicate. A column that is convenient to insert and impossible to index becomes a sequential scan with a filter, repeated for every query that touches it. This lesson compares the four families on typing discipline, index support, storage overhead, and the failure modes that only appear once the table holds millions of rows, then works through the conversions and index choices that keep them fast.
ARRAY Type
-- Create table with ARRAY columns
CREATE TABLE product_tags (
product_id SERIAL PRIMARY KEY,
product_name VARCHAR(100),
tags TEXT[],
prices DECIMAL(10,2)[],
attributes JSONB
);
INSERT INTO product_tags VALUES
(1, 'Laptop', ARRAY['electronics', 'computers', 'sale'], ARRAY[999.99, 899.99], '{"color": "silver", "weight": 2.5}'),
(2, 'Phone', ARRAY['electronics', 'mobile'], ARRAY[699.99, 599.99], '{"color": "black", "weight": 0.3}'),
(3, 'Book', ARRAY['education', 'reference'], ARRAY[29.99, 24.99], '{"pages": 500, "format": "hardcover"}');
-- Array operations
SELECT
product_name,
tags,
array_length(tags, 1) AS tag_count,
tags[1] AS first_tag,
array_append(tags, 'new_tag') AS with_new_tag,
array_remove(tags, 'sale') AS without_sale,
array_cat(tags, ARRAY['extra']) AS concatenated,
array_to_string(tags, ', ') AS tags_string
FROM product_tags;
-- Array containment
SELECT * FROM product_tags
WHERE tags @> ARRAY['electronics'];
-- Array overlap
SELECT * FROM product_tags
WHERE tags && ARRAY['electronics', 'education'];
-- Array uniqueness
SELECT * FROM product_tags
WHERE array_ndims(tags) = 1;
-- Unnest array to rows
SELECT
product_name,
UNNEST(tags) AS tag
FROM product_tags
ORDER BY product_name, tag;
Output:
| product_name | tag |
|---|---|
| Book | education |
| Book | reference |
| Laptop | computers |
| Laptop | electronics |
| Laptop | sale |
| Phone | electronics |
| Phone | mobile |
Arrays are typed lists with one-based subscripting, and their operators split into three groups: construction and reshape such as array_append and array_cat, membership tested with containment or overlap, and expansion through UNNEST, which turns one row into many. The expansion is the trap â unnesting a table of orders that carry five line items each multiplies the row count fivefold, so any aggregate computed after unnesting must be folded back per parent before it joins to a dimension. Indexing follows usage: a GIN index answers containment and overlap questions, while an expression index on the first element serves the common "does this product carry that tag" filter. A pair of prices belongs in rows rather than in an array, because comparing element positions across rows has no meaning.
MAP Type (HStore)
-- PostgreSQL uses hstore for map-like structures
CREATE EXTENSION IF NOT EXISTS hstore;
CREATE TABLE user_profiles (
user_id SERIAL PRIMARY KEY,
name VARCHAR(100),
settings HSTORE,
preferences JSONB
);
INSERT INTO user_profiles VALUES
(1, 'Alice',
'theme => dark, language => en, notifications => true'::hstore,
'{"color": "blue", "font_size": 12}'::jsonb),
(2, 'Bob',
'theme => light, language => es'::hstore,
'{"color": "red", "font_size": 14}'::jsonb);
-- Hstore operations
SELECT
name,
settings,
settings->'theme' AS theme,
settings['language'] AS language,
settings ? 'notifications' AS has_notifications,
settings - 'theme' AS without_theme,
settings || 'font => large'::hstore AS with_new_key,
akeys(settings) AS all_keys,
avals(settings) AS all_values
FROM user_profiles;
-- Convert between hstore and jsonb
SELECT
name,
hstore_to_jsonb(settings) AS as_jsonb,
jsonb_to_hstore(preferences) AS as_hstore
FROM user_profiles;
PostgreSQL has no native map type, so hstore fills the role: a flat key-value store of text pairs with operators for lookup, removal, merge, and key existence. Flat is the constraint that matters â values are strings, nesting is not allowed, and keys are unordered, so a sorted key list is the only structure you get. When the payload is genuinely a document with nested objects, jsonb wins because it preserves shape and supports a path query language; when the payload is a fixed set of flat settings probed individually, hstore wins on storage and on operator clarity. Whichever you choose, keys discovered at runtime deserve a generated column or an expression index, otherwise every probe reads the whole value instead of a single entry.
STRUCT Type (Composite)
-- Create composite type
CREATE TYPE address AS (
street VARCHAR(100),
city VARCHAR(50),
state VARCHAR(2),
zip VARCHAR(10)
);
CREATE TYPE person_info AS (
name VARCHAR(100),
birth_date DATE,
home address,
work address
);
-- Use composite type
CREATE TABLE employees (
emp_id SERIAL PRIMARY KEY,
info person_info,
salary DECIMAL(12,2)
);
INSERT INTO employees VALUES
(1, ROW('Alice', '1990-01-01',
ROW('123 Main St', 'SF', 'CA', '94102'),
ROW('456 Work Ave', 'SF', 'CA', '94105')::address
)::person_info,
120000.00);
-- Access composite fields
SELECT
(info).name,
(info).birth_date,
(info).home,
(info).work,
((info).home).city AS home_city,
((info).work).city AS work_city
FROM employees;
-- Expand composite to columns
SELECT
(info).name AS name,
(info).home AS home_address
FROM employees;
-- Create table from composite
CREATE TABLE employee_addresses AS
SELECT
emp_id,
(info).name AS name,
((info).home).* AS home
FROM employees;
Composite types give a column named subfields, so a person record carries home and work addresses without three extra joins. Access uses the field syntax shown above, and expanding a composite with the record star operator is the usual way to land the pieces in a reportable table. The trade-off is schema rigidity: adding a field to the type rewrites dependent views, and two systems that agree on field names but disagree on order will silently read the wrong element rather than fail. Treat a composite as a strongly typed struct for data you own end to end, and prefer separate columns or jsonb when the shape is dictated by an external feed that will change without asking you first.
Range Types
-- PostgreSQL range types
CREATE TABLE reservations (
reservation_id SERIAL PRIMARY KEY,
room_id INT,
during TSRANGE,
guest_name VARCHAR(100)
);
INSERT INTO reservations VALUES
(1, 101, '[2024-06-01 14:00, 2024-06-05 11:00)'::tsrange, 'Alice'),
(2, 101, '[2024-06-06 14:00, 2024-06-10 11:00)'::tsrange, 'Bob'),
(3, 102, '[2024-06-01 14:00, 2024-06-03 11:00)'::tsrange, 'Charlie');
-- Range operations
SELECT
reservation_id,
room_id,
guest_name,
during,
lower(during) AS start_time,
upper(during) AS end_time,
upper(during) - lower(during) AS duration,
isempty(during) AS is_empty,
lower_inf(during) AS start_infinite,
upper_inf(during) AS end_infinite
FROM reservations;
-- Range containment
SELECT * FROM reservations
WHERE during @> '2024-06-02'::timestamp;
-- Range overlap
SELECT r1.*, r2.*
FROM reservations r1
JOIN reservations r2 ON r1.room_id = r2.room_id
AND r1.during && r2.during
WHERE r1.reservation_id < r2.reservation_id;
-- Range adjacency
SELECT * FROM reservations
WHERE room_id = 101
ORDER BY during;
-- Range union
SELECT
room_id,
range_merge(during) AS merged_range,
array_agg(guest_name) AS guests
FROM reservations
GROUP BY room_id;
-- Int4range, Numrange, Date ranges
SELECT '[1, 10]'::int4range; -- Integer range
SELECT '[1.5, 9.5]'::numrange; -- Numeric range
SELECT '[2024-01-01, 2024-12-31]'::daterange; -- Date range
Range types encode an interval as a single value with set semantics, which is what makes double-booking impossible to express. The GiST index on the booking window enforces exclusion at write time, so the defensive overlap query you would otherwise run before every insert disappears â the insert fails instead. Bounds are half-open by convention in scheduling, so a checkout at eleven and the next check-in at fourteen share no time. Everything reporting needs comes as functions: lower and upper for the endpoints, isempty for empty intervals, containment and overlap operators for filters, and range_merge to collapse adjacent bookings. Discrete ranges such as int4range normalise automatically, so an inclusive and an exclusive spelling of the same bounds compare equal once the upper bound rounds down.
JSONB vs ARRAY vs HStore
| Feature | JSONB | ARRAY | HStore |
|---|---|---|---|
| Type Safety | No | Yes | No |
| Nested Data | Yes | Limited | No |
| Indexing | GIN | GiST | GIN |
| Query Language | Path | Operators | Keys |
| Schema Flexibility | High | Medium | High |
| Storage | Medium | Low | Low |
-- Compare performance
CREATE TABLE jsonb_table (data JSONB);
CREATE TABLE array_table (data TEXT[]);
CREATE TABLE hstore_table (data HSTORE);
-- Insert test data
INSERT INTO jsonb_table
SELECT jsonb_build_object('key', i)
FROM generate_series(1, 100000) i;
INSERT INTO array_table
SELECT ARRAY[i::text]
FROM generate_series(1, 100000) i;
INSERT INTO hstore_table
SELECT hstore('key', i::text)
FROM generate_series(1, 100000) i;
-- Compare query times
\timing on
SELECT * FROM jsonb_table WHERE data @> '{"key": 50000}';
SELECT * FROM array_table WHERE data @> ARRAY['50000'];
SELECT * FROM hstore_table WHERE data @> 'key => 50000';
The comparison table earns its place when you ask what each type costs at read time. JSONB keeps its GIN index and a path language but pays for parsing on write and stores keys redundantly unless a generated column projects them out; arrays give type safety and cheap storage yet search only by position or membership; hstore sits between them with key operators and no nesting. A load of 100,000 equivalent payloads typically leaves jsonb at roughly double the footprint of a text array, because every key repeats with every row. The decision rule: use an array when the elements share a type and you query membership, jsonb when the shape varies or must evolve without DDL, and hstore for a fixed flat settings bag read by key.
Advanced Type Operations
-- Array aggregation
SELECT
department,
ARRAY_AGG(name ORDER BY salary DESC) AS employees_by_salary,
ARRAY_AGG(DISTINCT skill) AS unique_skills
FROM employee_skills
GROUP BY department;
-- JSONB to array
SELECT
product_name,
jsonb_array_elements_text(tags) AS tag
FROM product_tags;
-- Array to JSONB
SELECT
product_name,
to_jsonb(tags) AS tags_jsonb
FROM product_tags;
-- Nested array operations
CREATE TABLE matrix (
id SERIAL PRIMARY KEY,
data INT[][]
);
INSERT INTO matrix VALUES
(1, '{{1,2,3},{4,5,6},{7,8,9}}'::int[][]);
SELECT
data[1][1] AS element,
array_length(data, 1) AS rows,
array_length(data, 2) AS cols
FROM matrix;
Aggregation and reshaping are where the types interoperate. ARRAY_AGG with an explicit ORDER BY produces a deterministic list, which matters as soon as the array is read positionally, while ARRAY_AGG(DISTINCT ...) deduplicates in a single pass. Move between representations on purpose â to_jsonb when a payload is serialized to an API, jsonb_array_elements_text when a document must be shredded into rows, and a cast back when a service expects the original shape. Multidimensional arrays exist, but the database does not police rectangularity for you, so a ragged nested array fails at read time rather than at insert time. Build the invariant into the load: assert dimensions once, and the downstream query never has to.
Mathematical Properties
For array operations:
For range operations:
For JSONB containment:
âšī¸
Performance Tip: Use ARRAY for simple lists, JSONB for complex nested structures, and HStore for key-value pairs with known keys.
Type Conversion Patterns
-- Convert between types
SELECT
ARRAY[1, 2, 3]::TEXT[], -- Cast array
'{1,2,3}'::INT[], -- Parse text to array
'[1,2,3]'::JSONB, -- Text to JSONB
'[1,2,3]'::JSONB->0, -- Get first element
'{"a":1}'::HSTORE, -- Text to hstore
ROW(1, 'test')::RECORD; -- Create record
-- Safe conversion
CREATE OR REPLACE FUNCTION safe_cast(text, anyelement)
RETURNS anyelement AS $$
BEGIN
RETURN $1::text::anyelement;
EXCEPTION
WHEN OTHERS THEN
RETURN $2; -- Return default
END;
$$ LANGUAGE plpgsql;
SELECT safe_cast('123', 0); -- Returns 123
SELECT safe_cast('abc', 0); -- Returns 0
Conversions are where complex types fail late at night. The safe_cast wrapper above is the pattern worth keeping: a cast that raises is caught and a default is returned, which matters when one malformed payload in a nightly feed would otherwise abort the whole load. Conversion between arrays and jsonb is lossless in one direction only â object keys become array elements, and the order that comes back is the document's storage order rather than a semantic one, so never rely on it for ranking. Cast explicitly instead of depending on assignment casts, record which rows failed, and keep the rejects in a quarantine table you can replay.
Type-Specific Indexing
-- GIN index for arrays
CREATE INDEX idx_tags_gin ON product_tags USING gin(tags);
-- GIN index for JSONB
CREATE INDEX idx_attributes_gin ON product_tags USING gin(attributes);
-- GiST index for ranges
CREATE INDEX idx_reservations_gist ON reservations USING gist(during);
-- B-tree index for specific array elements
CREATE INDEX idx_first_tag ON product_tags ((tags[1]));
-- Expression index for JSONB
CREATE INDEX idx_color ON product_tags ((attributes->>'color'));
â ī¸
Storage Overhead: Complex types increase storage. Monitor with pg_column_size() and consider normalization for frequently queried fields.
When a complex type is the wrong tool
The column should go back to normal columns when any of these signs appear: you filter on the same nested element more than once per query, the array routinely grows past a few hundred elements, a generated column had to be added before the predicate could be indexed, or two services write conflicting shapes into the same key. Each sign means the join you were avoiding would have been cheaper than the full scan you now run. Measure before you decide: pg_column_size for footprint, EXPLAIN for a filter that still sits above the scan, and a count of queries touching the column per second. Three lookups a day rarely justify denormalization; three hundred a second usually do, and the migration is far cheaper before the type spreads across the schema.
Common Mistakes
Aggregating after UNNEST without folding back to the parent grain
Fix: Aggregate per parent id first, then join the result to dimensions
Storing prices or timestamps inside an array and comparing them positionally
Fix: Model ordered measurements as rows so comparisons have a defined meaning
Leaving a complex column unindexed because the operators looked simple
Fix: Add a GIN, GiST, or expression index that matches the predicate you actually write
Best Practices
- Pick the type from the predicate you will write, not from the shape you find convenient to insert
- Project hot nested fields into generated columns before indexing them
- Assert array dimensions and document shape during the load, not at read time
- Keep casts explicit and quarantine rows that fail instead of aborting the batch
- Re-measure storage and plan shape whenever a complex column passes a few million rows
Interview Questions
Q1: ARRAY or JSONB for storing a list?
ARRAY when the elements share a type and you query membership or position; JSONB when the shape varies, nests, or must evolve without a schema change
Q2: What do range types give you that a pair of timestamps does not?
Set semantics plus a GiST exclusion constraint that makes overlapping bookings impossible to store
Q3: Why add a generated column over a JSONB payload?
To project a nested field into a real column that a B-tree or GIN index can serve, instead of re-parsing the document per row
Q4: What is the storage cost of a map implemented in JSONB?
Keys repeat with every row, so equivalent payloads commonly use about twice the space of a typed array of the same values
Key Takeaways
- A complex type trades a join for operators, index support, and cast rules you must check first
- UNNEST multiplies rows, so fold aggregates back to the parent grain before joining
- hstore is flat, JSONB is nested, and arrays are typed â choose from the predicate, not the payload
- Range types turn double-booking into a write-time error instead of a read-time check
- Index the expression you query, and move the column back to columns when the scan wins