Start learning free

LESSON 38 OF 173 · BACKEND: SQL

AND and OR

Practice

A WHERE can hold more than one condition. Join two conditions with AND and a row is kept only when both are true. Join them with OR and a row is kept when at least one is true. They work like && and || in a JavaScript if.

To compare text, put the text in single quotes and use a single = for equal, not JavaScript's ===: name = 'Lamp'. Without the quotes, SQL would look for a column named Lamp. This query finds the products that cost more than 20 and are almost sold out, the Lamp and the Teapot:

const query = [
  "SELECT name, price, stock",
  "FROM products",
  "WHERE price > 20",
  "AND stock < 5",
].join(" ");

Write a whole condition on each side of OR: name = 'Mug' OR name = 'Lamp', not name = 'Mug' OR 'Lamp'. SQL doesn't fill in the missing name = for you.

Your code asks two questions, and the check prints both answers, with a blank line between them:

name | category | price
Pen | office | 2
(1 row)

name | category | price
Mug | kitchen | 12
Lamp | home | 29
Plant | home | 15
Teapot | kitchen | 22
(4 rows)

Your task: both queries read each product's name, category and price from products. In query, keep the office products that cost less than 5. In query2, keep the products whose category is home or kitchen.


Assignment
Follow the Coding Tutorial to write two queries: one that joins two conditions with AND, and one that joins them with OR.


Hint
A product has only one category, so it can never be home and kitchen at once: that question needs OR. Each condition after AND or OR is a whole one: column, comparison, value. The single quotes around a text sit inside the JavaScript string's double quotes.


STEP 1 OF 8
    Ctrl + Enter to check