Course Resources

Search

Search IconIcon to open search

Last updated Nov 17, 2024

# Select and Filter Data - WHERE Clause and Comparison Operators

The WHERE clause in SQL is used to filter records from a table, returning only those that meet a specific condition.

# Basics of the WHERE Clause

The WHERE clause follows the syntax:

1
2
SELECT column1, column2, ... FROM table_name 
WHERE condition;

# Comparison Operators

There are many different types of operators that can be used in our condition to filter what rows we get back based on the data they contain.

The first type are the comparison operators. These are used to compare values in a column with other values or expressions. These include:

For example, assume we have a table Employees with the following data:

EmployeeIDNameAgeDepartment
1John Doe28Marketing
2Jane Doe32HR
3Alex Ray45IT
4Sara Ali30Finance

To get details of employees from the ‘Marketing’ department we could write:

1
2
SELECT * FROM Employees
WHERE Department = 'Marketing';
# Expected Output:
EmployeeIDNameAgeDepartment
1John Doe28Marketing

If we wanted to find all employees who are not in the ‘HR’ department we could write:

1
2
SELECT * FROM Employees
WHERE Department <> 'HR';
# Expected Output:
EmployeeIDNameAgeDepartment
1John Doe28Marketing
3Alex Ray45IT
4Sara Ali30Finance

If we wanted to see information for employees over the age of 30 we could write:

1
2
SELECT * FROM Employees 
WHERE Age > 30;
# Expected Output:
EmployeeIDNameAgeDepartment
2Jane Doe32HR
3Alex Ray45IT

# Practice Questions

  1. Write a query to select all customers who are from ‘Germany’.

  2. Write a query to select all customers whose contact age is less than or equal to 20.

# Lessons