Start learning free

LESSON 38 OF 188 · BACKEND: SQL

AND and OR in Python

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 and or in a Python if.

To compare text, put the text in single quotes and use a single = for equal: 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:

query = (
    "SELECT name, price, stock "
    "FROM products "
    "WHERE price > 20 "
    "AND stock < 5 "
)

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.


STEP 1 OF 8
    Ctrl + Enter to check

    Sql And Or in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free