abdou / classroom

SQL Lesson 2: Queries with Constraints (Pt. 1)

Learn to filter and constrain your SQL queries using WHERE clauses with interactive exercises.

SQL Lesson 2: Queries with Constraints (Pt. 1)

Now we know how to select for specific columns of data from a table, but if you had a table with a hundred million rows of data, reading through all the rows would be inefficient and perhaps even impossible.

In order to filter certain results from being returned, we need to use a WHERE clause in the query. The clause is applied to each row of data by checking specific column values to determine whether it should be included in the results or not.

Select query with constraints

SELECT
column, another_column, ...
FROM
mytable
WHERE
condition
AND/OR another_condition
AND/OR ...

Numerical Operators

OperatorConditionSQL Example
=, !=, <, <=, >, >=Standard numerical operatorscol_name != 4
BETWEEN ... AND ...Number is within range of two values (inclusive)col_name BETWEEN 1.5 AND 10.5
NOT BETWEEN ... AND ...Number is not within range of two values (inclusive)col_name NOT BETWEEN 1 AND 10
IN (...)Number exists in a listcol_name IN (2, 4, 6)
NOT IN (...)Number does not exist in a listcol_name NOT IN (1, 3, 5)

Did you know?

As you might have noticed by now, SQL doesn’t require you to write the keywords all capitalized, but as a convention, it helps people distinguish SQL keywords from column and tables names, and makes the query easier to read.

Exercise

Using the right constraints, find the information we need from the Movies table for each task below.

Table: movies

Exercise 2 — Tasks

  1. Find the movie with a row id of 6
  2. Find the movies released in the years between 2000 and 2010
  3. Find the movies not released in the years between 2000 and 2010
  4. Find the first 5 Pixar movies and their release year

Solve all tasks to continue to the next lesson.

Progress0 of 4 tasks completed