SQL chapters

Chapter 10 of 17

Arrays and Collections

Try this in our SQLite Compiler →

Storing many values

A single variable holds one value, but most programs deal with lists of things: users, orders, scores. SQL provides a built-in collection type — usually called an array or list — that holds many values under a single name and indexes them with a number starting at 0.

-- Aggregate functions summarise many rows into one:
SELECT COUNT(*), AVG(age), MAX(age)
FROM users
WHERE active = TRUE;

Common operations

You will spend a lot of time looping over collections, adding items, removing items, searching for an item, sorting, and transforming each element into something else. Learn your language's standard library helpers for these tasks — they are faster and clearer than hand-written loops.

Other collection types

Beyond arrays, SQL usually offers sets (no duplicates), maps (key → value pairs) and queues / stacks. Choosing the right collection for the job makes your code shorter and your program faster.

Try it yourself

SQLite Compiler
Output
Code runs on the Play with Coding execution engine — your code is saved locally for next time.