Skip to content
wannacode

Only the rows you need

Problem

What ran out?

Every morning the manager wants to know which products need ordering because they have run out. The table has 25 products. Tomorrow it will have 2,500.

They do not need all the rows. They need only the ones where the stock is 0.

The idea

WHERE

WHERE keeps only the rows for which the condition is true:

SQLdatabase: shop

The database goes through every row, checks stock = 0 and keeps the true ones. The condition can use any column, not only those in SELECT.

The comparisons are: = equal, <> different, <, >, <=, >=. Numbers are written with a decimal point:

SQLdatabase: shop

Text goes in single quotes:

SQLdatabase: shop
More precisely, if you are curious

SQLite also accepts city = "Plovdiv" in double quotes, but only out of an old habit: if there is no column by that name, it takes it as text. PostgreSQL will say there is no column “Plovdiv”. Write text in single quotes and the query will work everywhere.

Try it

The expensive products

Show the name and price of the products that cost at least 10 €.

SQLdatabase: shop

The idea

AND, OR, NOT

Conditions can be combined:

  • AND: both must be true.
  • OR: at least one is true.
  • NOT: turns the condition around.

Cheap products there are plenty of (for a “take three” offer):

SQLdatabase: shop

See it

The OR trap

Marketing wants the customers from Sofia or Plovdiv who signed up since the start of 2026. Here is a first attempt. Run it and look at the dates:

SQLdatabase: shop
1. The query with OR and AND returned Maria, who signed up in 2025. Why?

With brackets, the condition says exactly what you mean:

SQLdatabase: shop

Whenever you mix AND and OR, add brackets, even when they are not required. Whoever reads the query after you will not have to wonder.

Try it

The waiting orders

Show the number, customer and status of the orders that are new or paid, but not yet shipped.

SQLdatabase: shop

Exercise

Two tasks

1. All orders except the cancelled ones (cancelled). Show the number and status. Try it with NOT.

The orders that are not cancelled:

SQLdatabase: shop

2. The shop opens a warehouse on the coast. Which customers from Varna or Burgas have been with us since 2025? Show the name, city and sign-up date.

Customers from Varna or Burgas who signed up before 2026:

SQLdatabase: shop

Test

Check yourself

1. How do you write “the city is Varna”?
2. Which condition finds the products that do NOT cost 2.50 €?
3. What does WHERE status = 'new' AND status = 'paid' return?
4. In what order are the parts of a query written?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·