Maps in SQL

Concepts covered: Maps

A map is a collection of key-value pairs where each key maps to exactly one value. Maps are also called dictionaries or associative arrays in other contexts. In SQL, maps provide a way to store flexible, named attributes without defining a fixed schema.

Maps are particularly valuable for storing metadata, configuration settings, or properties that vary between rows. Instead of adding nullable columns for every possible attribute, you store them all in a single map column.

Map Basics

Maps can be created using the MAP constructor with alternating keys and values:

SELECT MAP(
  ARRAY['color', 'size', 'price'],
  ARRAY['red', 'large', '29.99']
) AS product_attrs
FROM system_info
LIMIT 1
Result
product_attrs
{color=red, size=large, price=29.99}

The MAP function takes two arrays: one of keys and one of values. Keys must be unique within a map. Both keys and values have specific types, and all keys must share one type while all values share another.

Accessing Map Values

Retrieve values from a map using bracket notation with the key:

session_idproperties
s001{browser=Chrome, os=Windows, device=desktop}
s002{browser=Safari, os=macOS, device=laptop}
s003{browser=Firefox, os=Linux, device=desktop}
SELECT
  session_id,
  properties['browser'] AS browser,
  properties['os'] AS operating_system
FROM sessions
Result
session_idbrowseroperating_system
s001ChromeWindows
s002SafarimacOS
s003FirefoxLinux

The bracket notation properties['browser'] retrieves the value associated with the key 'browser'. If the key does not exist in the map, the result is NULL.

Comparison & Use Cases

Maps and JSON objects look similar but serve different purposes:

AspectMapJSON Object
StorageBinary, optimizedText string
Key TypesAny SQL typeStrings only
Access SpeedFast O(1)Requires parsing
Nested ObjectsNot supportedSupported
Best ForHomogeneous key-valueComplex documents

Map Use Cases

Maps excel when you need to store and retrieve named properties efficiently without the parsing overhead of JSON.

Common Map Use Cases

About this lesson

This section is part of the Complex Data: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.