WHERE

We learned how to get specific columns using SELECT. What if we're looking for specific rows? That is what the WHERE clause is for.

SELECT *
FROM daters
WHERE eye_color = 'brown';
name
VARCHAR
height_cm
INTEGER
eye_color
VARCHAR
Ray
180
brown
Claude
156
brown
Anita
188
brown

Visually, it looks like this:

col_1 1 2 3 4 5 ... ... ... ... ... col_2 ... ... ... ... ... col_4 brown green brown brown blue color ... ... ... ... ... col_3 col_1 1 3 4 ... ... ... col_2 ... ... ... col_4 brown brown brown color ... ... ... col_3 col_1 1 2 3 4 5 ... ... ... ... ... col_2 ... ... ... ... ... col_4 brown green brown brown blue color ... ... ... ... ... col_3 color = WHERE brown

The expression of the WHERE clause tells us which rows we want. This expression has a special constraint. The WHERE expression must be a BOOL type, which is short for "boolean".

A boolean is 1 of 2 possible values: TRUE and FALSE (or 0 and 1 if you prefer numbers). A boolean can be created literally with the keywords TRUE and FALSE.

SELECT
  TRUE AS true_literal,
  FALSE AS false_literal;
true_literal
BOOL
false_literal
BOOL
TRUEFALSE

They can also be created by comparing values using operators.

SELECT
  2 + 2 = 4 AS something_true,
  2 + 2 = 3 AS something_false;
something_true
BOOL
something_false
BOOL
TRUEFALSE

Most of the time, these comparisons are used in a WHERE clause. The WHERE expression is evaluated per row, and if it outputs TRUE for a row, the row is kept in the result.

Let's try this out in a challenge!

© 2022 Andrew Carlson. All rights reserved.