In one sentence

SQL uses a declarative syntax that describes the final result. If you can read a list comprehension, you can read SQL.

If you know Python

When you work with lists in Python, one of the first tools you reach for is the for loop.

# Step-by-step instructions
results = []
for customer in customers:
    if customer['is_premium']:
        results.append(customer['name'])

It’s fine. It works. It’s readable. But when we look at the work that it’s doing, it is really just filtering data into another list. List comprehensions are somewhat like a rearranged for loop, but they are also taking a step towards the declarative syntax that SQL uses.

# Python: More declarative (list comprehension)
premium_names = [c['name'] for c in customers if c['is_premium']]

c['name'] for c selects and transforms, in customers specifies the source, and if c['is_premium'] filters. SQL has the same three components: SELECT name selects and transforms, FROM customers specifies the source, and WHERE is_premium = true filters.

-- Describe the result you want
SELECT name FROM customers WHERE is_premium = true

Same logic, same structure.

The usual mistake

I was asking SQL to perform steps to return data. This didn’t work because SQL uses a declarative syntax that describes the final result. Until I realized this, SQL felt hard.

Think of a spreadsheet that lists 1,000 people, where you need to see only the people who live in Texas. The slow way is to look at each row, starting from the top, and copy every Texan to another sheet. The clever way is to sort by state, scroll to Texas, and copy those rows, but you are still performing steps in order to produce the final result. The SQL way: filter the state to Texas. No multiple steps, just describing the end result, and it’s done.

Example

SELECT name, city
FROM customers
WHERE is_premium = true
ORDER BY name

There are no steps here, only a description of the rows you want. It lets the database optimize for faster results, because the database can choose the fastest path to your result. And the syntax stays the same regardless of the amount of data present: it will be described in the same way whether you have 10 rows of data or ten thousand.

Go deeper

SQL Thinks in Sets, Not Loops, post 5 of SQL for Python Developers.