DSA Factory
Free SQL queries lessonsSQL queries · Stage 0 · Reading a table · Step 3

Combine conditions

Use AND, OR, NOT and brackets to say exactly which rows you want. About 8 minutes.

AND needs both, OR needs one

One test is often not enough. You want novels that came out after 1950, or poetry or stories. Combine tests with AND and OR.

AND keeps a row only when both tests pass. OR keeps it when at least one passes. NOT flips a test: the rows it would have kept are dropped and the others are kept.

Each side must be a full test: genre = 'Novel' OR genre = 'Poetry', not genre = 'Novel' OR 'Poetry'.

AND: both must pass. OR: one is enough.
In code
WHERE genre = 'Novel' AND year > 1950
WHERE genre = 'Novel' OR genre = 'Poetry'
WHERE NOT genre = 'Novel'

AND goes first, so use brackets

Mix AND with OR and SQL works out the AND first, like multiplication before addition. So genre = 'Novel' OR genre = 'Poetry' AND year > 1950 means any Novel at all, or a Poetry book after 1950. Rarely what you meant.

Brackets fix it. Put the OR inside brackets, and the year test then applies to both genres.

Mixing AND with OR? add brackets. Always.
In code
WHERE (genre = 'Novel' OR genre = 'Poetry')
  AND year > 1950
WHERE (genre = 'Novel' OR genre = 'Poetry') AND year > 1950
books
idtitlegenreyear
1The Tea EstateNovel1968
2MadhushalaPoetry1935
3Jungle TalesFables1960
4River SongsPoetry1987

Every row must pass both: the genre test in brackets, and the year test.

Move 1 of 5
Quick check

WHERE city = 'Pune' OR city = 'Delhi' AND score > 60. Which of these rows is kept?

  1. Acity Pune, score 40
  2. Bcity Delhi, score 40
  3. Ccity Mumbai, score 90
Show the answer

city Pune, score 40. AND runs first, so the query reads Pune, or (Delhi and above 60). Pune alone is enough.

Your problem

Movie night

The movies table has one row per movie. Show the title of every Hindi or Tamil movie that is rated above 8.

Tables
movies(id, title, language, rating, year)

Up to 2,000 movies

Write the query in your browserFree account, no card. Your query runs on real tables, with hints if you get stuck, and your progress is saved.
Sign up free to solve