Pull rows out, then filter them

INPUT · Slides

Only the rows that match

01 / 05

You do not want all of it

Every query so far handed back every record in the table. You could pick the columns, but not the rows.

What you actually want is nearly always just the rows that match — "item number 4", "the things that cost 200".

02 / 05

How WHERE looks

Add WHERE condition after FROM table and only the records that match come back.

Read it as "from stocks, select everything — but only where id is 4". It is a condition tacked on at the end.

SELECT * FROM stocks WHERE id = 4;

Result

4 | ruler | 150 | Hoshiya Works | 12

03 / 05

"Equals" is a single equals sign

"Equals" in SQL is one = and nothing more. It is not JavaScript's ===, so switch over here.

SQL has no = that means "put this value in", so there is nothing to get it confused with.

SELECT * FROM stocks WHERE amount = 8;

Result

5 | colour pencils | 480 | Midori Stationery | 8

04 / 05

More than one row can match

If two or more records match, all of them come back. Nothing promises you a single row.

And if nothing matches, the result is empty. That is not an error, it is an answer of "none".

SELECT * FROM stocks WHERE price = 200;

Result

2 | notebook | 200 | Aoba Paper | 25
6 | paper clips | 200 | Hoshiya Works | 100

05 / 05

Choose the rows and the columns

SELECT picks the columns, WHERE picks the rows. Put them together and you can cut out exactly the piece of the table you want.

Let us write some.

SELECT item, price FROM stocks WHERE id = 1;

Result

pencil | 120