First Basket
pick every flower, and then learn the far cleverer trick of picking only some
Page 2 · Welcome
A garden, but for SQL
tables are beds, rows are flowers, and you, my friend, are the gardener
Now listen carefully, because this is important.
Behind the gate in front of you is a garden. Not an ordinary garden. There are flower beds in it, and winding paths, and a greenhouse with foggy windows, and a directory nailed up by the gate, and a long wooden table where you can tip out whatever you've gathered and sort through it. It is, I'm sorry to tell you, a little bit overgrown. The last gardener was a very serious person who wrote everything down in capital letters and never once picked a flower for fun. He has gone. You have his job now.
In this chapter you'll learn the very first word of SQL. The word is SELECT, and it means go and get. You'll walk the rose bed with a basket. You'll pick every rose. Then you'll pick only the pink ones. Then you'll line up your basket tallest to shortest. Then you'll take just the first two and leave the rest. That is the whole lesson, and I promise it is not nearly as difficult as the serious gardener made it look.
The SQL you'll write is real. A small SQL engine is living inside this very page, humming quietly, waiting for you to say something. There is nothing to install. The roses are already planted. Let's open the gate.
You can press → to go to the next page and ← to go back, or click Next at the bottom. The breadcrumb up top ("First Basket") shows you the whole map of the chapter, in case you want to peek ahead. I would.
Page 3 · The bed
Tables are beds
a bed of roses, every rose a row
Every database in the world is a garden. Every single one. The enormous ones that banks keep in cold, windowless buildings are gardens. The tiny one living in this page is a garden. Inside each garden are tables, and tables are flower beds. Each bed holds one kind of thing and one kind only. A bed of roses. A bed of tulips. A bed of daffodils that nobody has watered since March.
Today we are tending one bed and nothing else: the rose_bed.
Five roses live in it. Some are pink. One is purple. One is white. They are not all the same height, because roses, like people, do not take instructions. Madame Hardy is tall and rather grand about it. Iceberg is the shortest at 16 centimeters and does not care what you think.
Here is the clever part. If you came back tomorrow and planted a sixth rose, the bed would have six roses in it. If a rabbit ate one, it would have four. But the bed itself would not change one bit. It would still be the rose bed, the same shape, the same soil, the same little wooden sign. That is exactly what a table is: the named container that stays put while the flowers come and go.
Page 4 · Flowers and tags
Rows are flowers,
columns are traits
each rose carries a tag with its name, color, and height
Crouch down. Right down, knees in the dirt. Pick any rose and look at its stem, and you'll find a small wooden tag tied on with string. The serious gardener did this, and it is the one thing he got absolutely right.
Stamped on every tag are four things: an id number (no two roses share one, ever), the species, the color, and the height in centimeters. Every rose in the bed has a tag. Every tag has the same four blanks filled in. Those four blanks are the columns. Each rose, tag and all, is a row.
| id | species | color | height |
|---|---|---|---|
| 1 | Old English | pink | 18 |
| 2 | Reine des Violettes | purple | 22 |
| 3 | Madame Hardy | pink | 24 |
| 4 | Iceberg | white | 16 |
| 5 | Carefree Beauty | pink | 20 |
The bed on the left and the table on the right are the same five roses, shown two ways. There is no trick. When you're a gardener you'll walk the bed. When you're speaking SQL you'll look at the table. The secret, and it is a very good secret, is that every time you write a query you should shut your eyes for one second and picture the bed.
Page 5 · The basket
The basket
SELECT is you, walking the bed with a basket
Beside the gate, hanging on a nail, is a wicker basket. It is a little worn at the handle and smells faintly of onions, and it is the most important tool you will ever own. Take it down.
Here is what you're going to do with it. You will walk along the row of roses, slowly, and at every single rose you will stop and ask one question: does this one go in the basket? Yes or no. No dithering. When you reach the far end of the bed you turn around, look down, and see what you've got.
That walk, start to finish, is what a SELECT statement is. Nothing more, nothing less. The basket at the end is your result. Some walks fill the basket to the brim. Some leave nearly every rose standing where it was. Some tip the basket out and arrange everything neatly before handing it back. It is always the same walk. It is only ever the basket that is different.
On the next page you'll write your very first query, and that empty basket is going to fill up faster than you can say semicolon.
Page 6 · SELECT *
Your first basket
pick everything in the bed
The simplest walk of all is the greedy one. Stop at every rose. Take every rose. The basket comes
back bulging. Two little phrases tell SQL to do exactly this: SELECT *,
which means "pick everything," and FROM rose_bed, which means "from this bed,
not the tulips, thank you very much." That funny star, the *, is shorthand for
"all columns": keep every single word on every single tag.
Go on, then. Press Run query and watch what happens to the basket.
* means every last one) and which table to read FROM.
The semicolon at the end is a small polite cough that means "I've finished talking."
Page 7 · SELECT specific columns
Don't read every tag
pick only the columns you care about
Now, the serious gardener read every word on every tag, every time, even when he only wanted to know
the color. It took him all afternoon. You are cleverer than that. If all you need is the color and the
height, say so. Take out the * and put in the names of the columns you want,
with commas between them, like a shopping list:
Quick check
Most of the query is written for you. Fill in the blank marked ___, then press Check.
Pick just the species and height of every rose in the bed.
Page 8 · WHERE on text
Only the pink ones
filter rows with WHERE
This time you only want the pink ones. The purple rose stays exactly where it is. The white rose stays exactly where it is. You walk past them both without so much as a glance. To tell SQL "skip anything that isn't pink," you add one more line, and it begins with the word WHERE.
The condition reads almost like plain English: color = 'pink'. Two
small things that trip up nearly everybody on the first go. There is a single =,
not two. And the word 'pink' is wrapped in single quotes, because it is
a word and not a number, and SQL is very particular about the difference.
Quick check
The serious gardener left this query behind. It is meant to fetch the white rose, and it does not work. Find the mistake, fix it, and press Check.
Fix the query so it brings back the white rose, with every column on its tag.
Page 9 · WHERE on numbers
Only the tall ones
numbers let you ask for "more than" and "less than"
With a word, there is really only one question you can ask: is it exactly this? Pink or not pink. But a number is a far more obliging thing. You can ask a number a whole family of questions, and it will answer every one of them without complaint:
- more than
height > 16 - at least
height >= 18 - less than
height < 20 - at most
height <= 18 - not equal
height != 18(or<>, same thing) - in a range
height >= 18 AND height <= 22
That last one smuggles in a new word, AND, which glues two conditions together. A flower has to pass both tests to earn its place in the basket. There is also OR, for passing either one, and NOT, which turns a condition inside out. You'll get to play with those in the sandbox at the end of the chapter.
For now, let's find every rose taller than 16 centimeters. Notice there are no quotes around the 16. It is a number, and numbers go about bare. Then try the chips underneath and watch each one pick a different handful of roses.
= equals,
!= or <> not equal,
< less than,
> greater than,
<= at most,
>= at least.
Quick check
Fill in the blank with the right comparison, and mind the difference between less than and at most.
Pick the species and height of every rose that is 20 cm or shorter.
Page 10 · ORDER BY
Tallest first
arrange the basket before handing it over
The roses stand in the bed in whatever order the serious gardener happened to plant them, which was no order at all. That is fine for a bed. It is no good for a basket. Nobody wants to rummage. ORDER BY lets you arrange what you've picked before you hand it over.
Let's keep our three pink roses but lay them out tallest first. DESC
is short for "descending," which means biggest at the top and smallest at the bottom, like a staircase
going down. ASC is the staircase going up, and if you don't say either,
SQL quietly assumes you meant up.
Page 11 · LIMIT
Just two please
take only the first few
Suppose somebody at the gate asks you a very specific question: which are the two tallest roses in the whole bed? Not all of them. Not the pink ones. The two tallest, full stop. You already know how to sort tallest first. All that's left is to stop picking after two.
LIMIT is the wicker lid you drop over the basket the moment it has enough. Clunk. No more roses get in. It always comes last in the query, because you can't put the lid on before you've done the picking.
Quick check
Four blanks this time: what to show, the column to sort by, the direction, and how many to keep.
Find the shortest pink rose. Show its species only, and nothing else in the basket.
Page 12 · Putting it together
The anatomy of a query
five clauses, always in this order
That's all of them. You have now met every clause in this chapter, and here they are lined up in a row like children for a photograph. The order is fixed. You may leave some of them out of the picture, but you may never, ever swap their places.
SELECT species, color, height FROM rose_bed WHERE color = 'pink' ORDER BY height DESC LIMIT 2;
Now here is a secret that a great many grown-ups who write SQL every day have never properly noticed. The order you write is not the order the work gets done. The garden does it like this: walk this bed (FROM), keep these flowers (WHERE), copy down these traits from the tags (SELECT), arrange the basket (ORDER BY), stop at this many (LIMIT). The odd one out is SELECT. It is written first, bold as brass, and yet it does its work only after the bed has been walked and the flowers chosen. That is the whole trick of SQL. You say what you want, and the garden works out how.
Page 13 · A word before you go on
How is it going?
one minute of your time, and it goes straight to the person writing this book
You have met every clause now. Before you're let loose in the sandbox, I'd like to know one thing: did it click? Not whether you were polite about it. Whether you could understand and write queries yourself. If a page was confusing, or a picture didn't help, or you got stuck, say so. This book is still being written, and you are one of the people helping to write it.
Page 14 · Your own basket
Walk the bed yourself
write anything you like; the bed will answer
The query box below is yours now, and nobody is watching. Type any SELECT, WHERE or ORDER BY that comes into your head. The bed still holds the same five roses, and nothing you type here can hurt them. Press Run query when you're ready, and underneath the scene you'll see your basket laid out as a proper table, the way a serious person would want it.
rose_bed — schema
SELECT species, height FROM rose_bed WHERE color = 'pink' OR color = 'purple';
·
SELECT * FROM rose_bed WHERE NOT color = 'pink';
·
SELECT color, height FROM rose_bed ORDER BY height DESC LIMIT 3;
Page 15 · End of Chapter I
The basket comes home
what you've learned, and what's next
You walked the rose bed five different ways today, and five times the basket came back holding something different. And here is the thing you may not have noticed while you were busy doing it: every word of that was real SQL, run by a small SQL engine living inside this browser tab. The serious gardener took three years to learn what you've just done before lunch.
Check your basket
Three questions, to find out whether it has really gone in or only looked as if it had. The shape of each query is given; fill in every blank marked ___ and press Check. The basket is honest and will tell you.
1. Pick just the species and color of every pink rose.
2. Pick the species and height of every pink rose taller than 18 cm.
3. Find the two tallest roses. Show their species and height, tallest first.
There is more of Spring to come, and two more places in it to visit. The first is called
Tending the Bed, and it is where you finally get your hands dirty: planting new roses, changing
the ones already there, and pulling out the ones that have to go. The words for those jobs are
INSERT, UPDATE and
DELETE, and they are a good deal more powerful than they look. The second
is the Greenhouse, where there are no flowers at all yet, only a card on a bench, on which you
write down what a brand-new bed will be like and what rules it must keep. From that card, when the
time is right, a real bed gets dug.
After that comes Summer, and two stranger places still. One is the Flight Path, which belongs to the bees. It runs from the hive to the open flower and back, and it is never quite the same path twice. The other is the Sorting Table, where the day's whole basket is tipped out and sorted into smaller baskets, one color to each.
But that is for another day. For now the basket has come home, the gate is shut, and the path between the beds is empty. The day's work is done. And I will tell you something: it was a very good walk.
and the gate clicks shut behind you