Skip to main content

WHERE

Editorial

Introduction

WHERE decides which rows a query returns. Without it, a SELECT returns every row of its table; with it, only the rows that pass a test you write.

Here you will:

  • filter rows with a condition
  • compare values with =, !=, >, <, >= and <=
  • join conditions with AND, OR and NOT, and see which one SQL works out first
  • test ranges, lists and patterns with BETWEEN, IN and LIKE
  • find missing values with IS NULL, and see why = NULL finds none

What is the WHERE Clause?

WHERE filters rows by a condition. The condition is tested on each row, and only the rows that pass it appear in the result.

Basic Syntax

SELECT columns
FROM table_name
WHERE condition;

How It Works

  1. The database reads the table's rows one at a time.
  2. For each row it works out the condition. The answer is TRUE, FALSE or NULL, which means unknown: a value the test needs is missing.
  3. The row is kept only when the answer is TRUE. A FALSE row and a NULL row are both left out.

Example

SELECT customer_id, customer_city, customer_state
FROM olist_customers_dataset
WHERE customer_state = 'SP';

It returns every customer row whose customer_state is SP, the state of São Paulo: 41,746 of the table's 99,441 rows. The page shows the first 30 of them.

WHERE keeps the rows whose test is TRUE. Every row is tested on its own; a FALSE or NULL answer leaves it out. Three stages. 1, FROM: the table olist_customers_dataset, 8 of its 99,441 rows, each with its customer_city and customer_state: sao paulo, SP; campinas, SP; rio de janeiro, RJ; sao goncalo, RJ; belo horizonte, MG; porto alegre, RS; santos, SP; salvador, BA; an arrow takes every row on to the test. 2, WHERE customer_state = 'SP': each row's state against 'SP' and its answer, SP, TRUE; SP, TRUE; RJ, FALSE; RJ, FALSE; MG, FALSE; RS, FALSE; SP, TRUE; BA, FALSE; the FALSE rows stop at a bar, and each TRUE row goes on to the result; 3 TRUE and 5 FALSE. 3, the result: the 3 rows whose answer was TRUE, closed up: sao paulo, SP; campinas, SP; santos, SP; run on the whole table, the same WHERE keeps 41,746 of all 99,441 rows. Under them, the order SQL works in, WHERE coming before GROUP BY: FROM, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY, then LIMIT; WHERE is marked as the step that filters rows. And a NULL answer leaves the row out too: a product whose category is NULL, tested with = 'perfumaria', gets NULL and stops at a bar; on the products table, = NULL keeps 0 rows and IS NULL keeps 610.

Watch WHERE Test Each Row

Pick a table and a condition, then test the rows one at a time or all at once. Each part of the condition shows its own answer, the row's lamp shows the answer for the whole condition, and only a TRUE row goes through the gate into the result. Two of the products have no category: see what = NULL, IS NULL and != do with them.

Eight real customers and six real products from the course's tables, with each answer as SQLite gives it. Test one row at a time, or every row at once.

Comparison Operators

A comparison tests a value. Its answer is TRUE or FALSE, or NULL when a value it needs is missing.

Available Operators

OperatorMeaningExample
=Equal tocustomer_state = 'SP'
!= or <>Not equal toorder_status != 'delivered'
>Greater thanprice > 100
<Less thanfreight_value < 20
>=Greater than or equal topayment_installments >= 3
<=Less than or equal toprice <= 200

Most examples below count the rows a WHERE keeps with COUNT(*), so each answer is one number you can check; GROUP BY explains COUNT with the other ways to sum up rows.

Numeric Comparisons

SELECT COUNT(*) AS items
FROM olist_order_items_dataset
WHERE price > 100;

40,313 order items cost more than 100.

SELECT COUNT(*) AS payments
FROM olist_order_payments_dataset
WHERE payment_installments >= 3;

38,925 payments were split into 3 installments or more.

Text Comparisons

SELECT COUNT(*) AS orders
FROM olist_orders_dataset
WHERE order_status != 'delivered';

2,963 orders have a status other than delivered. Written with <>, the same test counts the same 2,963 orders; SQLite and PostgreSQL both accept either sign.

Text goes in single quotes: 'SP'. In SQL, double quotes name a column. SQLite bends that rule: "SQLite will also interpret a double-quotes string as string literal if it does not match any valid identifier." So customer_state = "SP" still counts 41,746 rows on SQLite, while PostgreSQL stops with column "SP" does not exist.

Combining Conditions with AND

AND joins two conditions, and a row is kept only when both are TRUE.

Syntax

WHERE condition1 AND condition2

Example

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_state = 'SP'
  AND customer_city = 'sao paulo';

15,540 rows: the state is SP and the city is sao paulo.

Multiple AND Conditions

SELECT COUNT(*) AS items
FROM olist_order_items_dataset
WHERE price >= 50
  AND price <= 200
  AND freight_value < 20;

41,426 items cost from 50 to 200 and have a freight value under 20.

Truth Table for AND

Condition 1Condition 2Result
TRUETRUETRUE
TRUEFALSEFALSE
FALSETRUEFALSE
FALSEFALSEFALSE

A NULL on one side adds rows to this table: see Working with NULL Values below.

Combining Conditions with OR

OR joins two conditions, and a row is kept when either one is TRUE.

Syntax

WHERE condition1 OR condition2

Example

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_state = 'SP'
   OR customer_state = 'RJ';

54,598 rows are in SP or in RJ.

Multiple OR Conditions

SELECT COUNT(*) AS orders
FROM olist_orders_dataset
WHERE order_status = 'shipped'
   OR order_status = 'delivered'
   OR order_status = 'invoiced';

97,899 orders are shipped, delivered or invoiced.

Truth Table for OR

Condition 1Condition 2Result
TRUETRUETRUE
TRUEFALSETRUE
FALSETRUETRUE
FALSEFALSEFALSE

The NOT Operator

NOT turns a condition round: TRUE becomes FALSE, and FALSE becomes TRUE. NOT NULL stays NULL.

Syntax

WHERE NOT condition

Examples

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE NOT customer_state = 'SP';

57,695 rows are outside SP.

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_state != 'SP';

!= counts the same 57,695 rows. Every row of this table has a state; where a value is NULL, both forms leave that row out.

NOT with Other Operators

SELECT COUNT(*) AS orders
FROM olist_orders_dataset
WHERE order_status NOT IN ('canceled', 'unavailable');

98,207 orders are neither canceled nor unavailable.

SELECT COUNT(*) AS products
FROM olist_products_dataset
WHERE product_category_name IS NOT NULL;

32,341 products have a category.

Combining AND and OR

AND and OR can share one condition, and then their order matters.

Precedence Rule

AND is worked out before OR, the way multiplication comes before addition.

Problem Example

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_state = 'SP' OR customer_state = 'RJ'
  AND customer_city = 'rio de janeiro';

It counts 48,628 rows, because SQL reads it as:

  • customer_state = 'SP'
  • OR (customer_state = 'RJ' AND customer_city = 'rio de janeiro')

That is all 41,746 rows of SP, plus the 6,882 rows of the city of Rio de Janeiro.

Solution: Use Parentheses

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE (customer_state = 'SP' OR customer_state = 'RJ')
  AND customer_city = 'rio de janeiro';

6,882 rows: the brackets make OR go first, and only the customers of the city of Rio de Janeiro are left.

Best Practice: when a condition mixes AND and OR, write the brackets, even where SQL would group the same way. Above, test A OR B AND C and then (A OR B) AND C: the dashed brackets show how SQL groups the first.

BETWEEN Operator

BETWEEN keeps the values inside a range, both ends included.

Syntax

WHERE column BETWEEN value1 AND value2

Example

SELECT COUNT(*) AS items
FROM olist_order_items_dataset
WHERE price BETWEEN 50 AND 100;

33,313 items cost from 50 to 100.

SELECT COUNT(*) AS items
FROM olist_order_items_dataset
WHERE price >= 50 AND price <= 100;

The two tests count the same 33,313 items.

NOT BETWEEN

SELECT COUNT(*) AS items
FROM olist_order_items_dataset
WHERE price NOT BETWEEN 50 AND 100;

79,337 items: with the 33,313 above, all 112,650 of the table.

BETWEEN with Dates

A timestamp in this dataset is text, such as 2018-01-31 00:04:39, and text compares character by character. '2018-01-31 00:04:39' comes after '2018-01-31', so this query leaves out every order placed on 31 January:

SELECT COUNT(*) AS orders
FROM olist_orders_dataset
WHERE order_purchase_timestamp BETWEEN '2018-01-01' AND '2018-01-31';

7,013 orders. Test up to the first moment of the next month instead:

SELECT COUNT(*) AS orders
FROM olist_orders_dataset
WHERE order_purchase_timestamp >= '2018-01-01'
  AND order_purchase_timestamp < '2018-02-01';

7,269 orders: the 256 placed on 31 January are counted now.

IN Operator

IN keeps a row when its value matches any value of a list.

Syntax

WHERE column IN (value1, value2, value3)

Example

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_state IN ('SP', 'RJ', 'MG', 'RS');

71,699 rows are in one of the four states.

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_state = 'SP'
   OR customer_state = 'RJ'
   OR customer_state = 'MG'
   OR customer_state = 'RS';

The four OR tests count the same 71,699 rows.

NOT IN

NOT IN keeps the rows that match no value of the list, such as the 98,207 orders that are neither canceled nor unavailable, counted above. A NULL in the list changes that: see Working with NULL Values.

IN Is Shorter Than Many ORs

SELECT COUNT(*) AS payments
FROM olist_order_payments_dataset
WHERE payment_type IN ('credit_card', 'debit_card', 'voucher');

84,099 payments. With OR it takes three tests (payment_type = 'credit_card', payment_type = 'debit_card' and payment_type = 'voucher'), and they count the same 84,099.

LIKE Operator for Pattern Matching

LIKE tests text against a pattern.

Wildcards

WildcardMeaningExample
%Any run of characters, or none'sao%' matches 'sao paulo'
_Exactly one character'_ao paulo' matches 'sao paulo'

In SQLite's words: "A percent symbol ("%") in the LIKE pattern matches any sequence of zero or more characters in the string."

Syntax

WHERE column LIKE 'pattern'

Examples

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_city LIKE 'sao%';

20,988 rows have a city starting with sao. The most common are sao paulo (15,540 rows), sao bernardo do campo (938) and sao jose dos campos (691).

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_city LIKE '%paulo';

15,542 cities end with paulo.

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_city LIKE '%de%';

12,584 contain de.

Case Sensitivity

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_city LIKE 'SAO%';

'SAO%' counts the same 20,988 rows: "SQLite only understands upper/lower case for ASCII characters by default." PostgreSQL's LIKE minds the case: there LIKE 'SAO%' finds no city written in small letters, and "The key word ILIKE can be used instead of LIKE to make the match case-insensitive according to the active locale."

NOT LIKE

SELECT COUNT(*) AS customer_rows
FROM olist_customers_dataset
WHERE customer_city NOT LIKE 'sao%';

78,453 rows: with the 20,988 above, all 99,441.

Working with NULL Values

NULL stands for a missing value. A comparison with NULL gives NULL, not TRUE or FALSE, and WHERE leaves such a row out. PostgreSQL's documentation puts it this way: "Ordinary comparison operators yield null", meaning unknown, "not true or false, when either input is null."

IS NULL and IS NOT NULL

SELECT COUNT(*) AS products
FROM olist_products_dataset
WHERE product_category_name IS NULL;

610 products have no category, and 32,341 have one, as counted above.

Wrong Way to Check for NULL

SELECT COUNT(*) AS products
FROM olist_products_dataset
WHERE product_category_name = NULL;

It counts 0 rows. product_category_name = NULL is NULL for every row, even for the 610 products whose category is missing, so no row is kept. Use IS NULL.

NULL Is Not FALSE

SELECT COUNT(*) AS products
FROM olist_products_dataset
WHERE product_category_name != 'perfumaria';

31,473 products are not perfumaria, and 868 are. Together that is 32,341, not all 32,951: the 610 products with no category are in neither count, because NULL != 'perfumaria' is NULL too.

NULL Inside AND and OR

SELECT NULL = NULL AS null_eq_null,
       1 AND NULL AS true_and_null,
       0 AND NULL AS false_and_null,
       1 OR NULL AS true_or_null,
       0 OR NULL AS false_or_null,
       NOT NULL AS not_null;

SQLite answers NULL, NULL, 0, 1, NULL and NULL, where 1 is TRUE and 0 is FALSE:

ABA AND BA OR B
TRUENULLNULLTRUE
FALSENULLFALSENULL

NULL = NULL is NULL as well, and NOT NULL stays NULL. PostgreSQL gives the same answers. SQLite's documentation: "When paired with NULL: AND evaluates to 0 (false) when the other operand is false; and OR evaluates to 1 (true) when the other operand is true."

SELECT COUNT(*) AS products
FROM olist_products_dataset
WHERE product_category_name != 'perfumaria'
  AND product_weight_g > 1000;

12,619 products weigh more than 1000 g and are not perfumaria. 225 more weigh more than 1000 g but have no category: for them the first test is NULL, NULL AND TRUE is NULL, and the row is left out.

NOT IN with a NULL in Its List

SELECT COUNT(*) AS orders
FROM olist_orders_dataset
WHERE order_status NOT IN ('canceled', NULL);

It counts 0 orders. NOT IN ('canceled', NULL) asks that the status differs from 'canceled' and from NULL, and the second test is NULL for every row, so no row is TRUE. PostgreSQL counts 0 as well.

Introduction to NULLs and IS NULL & IS NOT NULL take NULL further.

Practice

Each exercise runs on the course's tables: press Run to see its rows.

Exercise 1: Simple Comparison

Find the delivered orders:

-- Filter orders by status

SELECT order_id, customer_id, order_status
FROM olist_orders_dataset
WHERE order_status = 'delivered'
LIMIT 10;

The page shows 10 rows, each with the status delivered.

Exercise 2: Numeric Comparison

Find the order items priced over 500:

-- Filter by price

SELECT order_id, product_id, price
FROM olist_order_items_dataset
WHERE price > 500
LIMIT 10;

3,216 items cost more than 500; LIMIT 10 shows 10 of them, the first at 810.

Exercise 3: Multiple Conditions with AND

Find the customers of the city of São Paulo, in SP:

-- Combine conditions with AND

SELECT customer_id, customer_city, customer_state
FROM olist_customers_dataset
WHERE customer_state = 'SP' 
  AND customer_city = 'sao paulo'
LIMIT 10;

Every row reads sao paulo and SP.

Exercise 4: Using IN Operator

Find the customers in SP, RJ, MG or RS:

-- Use IN to check multiple values

SELECT customer_id, customer_city, customer_state
FROM olist_customers_dataset
WHERE customer_state IN ('SP', 'RJ', 'MG', 'RS')
LIMIT 10;

The first row is from timoteo in MG: IN keeps any of the four states.

Exercise 5: Pattern Matching with LIKE

Find the places whose city starts with rio:

-- Use LIKE for pattern matching

SELECT DISTINCT customer_city, customer_state
FROM olist_customers_dataset
WHERE customer_city LIKE 'rio%'
ORDER BY customer_city, customer_state
LIMIT 10;

52 pairs of city and state start with rio; sorted, the first is rio acima in MG. The ORDER BY decides which 10 come back: "If a SELECT statement that returns more than one row does not have an ORDER BY clause, the order in which the rows are returned is undefined."

Exercise 6: BETWEEN for Ranges

Find the order items priced from 100 to 300:

-- Use BETWEEN for range filtering

SELECT order_id, product_id, price
FROM olist_order_items_dataset
WHERE price BETWEEN 100 AND 300
LIMIT 10;

The first row costs 239.9; every price shown is from 100 to 300, both ends included.

Summary

Key Takeaways

  • WHERE keeps a row only when its condition is TRUE; FALSE and NULL rows are left out
  • Comparisons: =, != (or <>), >, <, >=, <=
  • AND needs both sides TRUE, OR needs one, and NOT leaves NULL as NULL
  • AND comes before OR: write the brackets when you mix them
  • BETWEEN includes both ends; for timestamps, test < the start of the next day or month
  • IN matches any value of a list; LIKE matches patterns with % and _
  • IS NULL finds missing values; = NULL finds none

Quick Reference

-- Basic comparison
WHERE column = value

-- Multiple conditions
WHERE condition1 AND condition2
WHERE condition1 OR condition2
WHERE (condition1 OR condition2) AND condition3

-- Range
WHERE column BETWEEN low AND high

-- List of values
WHERE column IN (val1, val2, val3)

-- Pattern matching
WHERE column LIKE 'pattern%'

-- NULL check
WHERE column IS NULL
WHERE column IS NOT NULL

What's Next?

ORDER BY sorts the rows a query returns.