SQL

Lesson 2 of 10

Lesson ยท 10 min

Filter rows with WHERE

Rows that match

Most tables have many rows, and you often want only some of them. The WHERE clause keeps the rows for which a condition is true. It goes after FROM.

SELECT title, year FROM books WHERE year > 2018;

Comparing values

Operator Meaning
= is equal to
<> is not equal to
< and > less than, greater than
<= and >= less than or equal to, greater than or equal to

SQL uses a single = to compare. Text goes in single quotation marks, such as 'Mystery'. Numbers do not need quotation marks.

More than one condition

Join conditions with AND and OR.

  • AND: both conditions must be true.
  • OR: at least one condition must be true.
  • NOT: turns a condition around.
SELECT title FROM books WHERE genre = 'Mystery' AND year >= 2020;

When you mix AND and OR, use parentheses to show which part goes first.

Patterns

LIKE compares text to a pattern. In a pattern, % stands for any number of characters, and _ stands for exactly one character.

SELECT title FROM books WHERE title LIKE '%Map%';

Two other useful forms: year BETWEEN 2015 AND 2018, and genre IN ('Fantasy', 'Mystery').

SQL keywords such as SELECT and WHERE are not case-sensitive. Programmers often write them in capital letters, so they are easy to see.

Your turn

Write one query for each task, one after the other. Each query ends with a semicolon. Result 1 is checked by task 1, result 2 by task 2, and so on.

Tasks

4 to do

  1. Task 1, not checked yet. Select every column for the books whose genre is 'Mystery'. Use * for every column.

  2. Task 2, not checked yet. Select the title and price of the books that cost less than 14.

  3. Task 3, not checked yet. Select the title of the books where the genre is 'Fantasy' and the year is 2019 or later. Use AND.

  4. Task 4, not checked yet. Select the title of the books whose title starts with The. Use LIKE and the wildcard %.

Task 1 of 4

Select every column for the books whose genre is 'Mystery'. Use * for every column.

All tasks

query.sql

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.