Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
โ† Basic Queries in SQL ยท Lesson 5 of 10

Module Four

๐Ÿ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
5

MODULE 4: FILTERING DATA WITH WHERE

Module Overview

Welcome to Module 4 of Basic Queries! In the previous module, you learned how to use the SELECT statement to retrieve information from a database.

But what happens when a database contains 10,000 student records and you only want to find students who are 13 years old? Do you need to display all 10,000 records before finding them?

No! SQL has a special keyword called WHERE that helps you find specific information by setting conditions.

In this module, you will learn how to filter records, use comparison operators, combine conditions, and search for specific information inside database tables.

Lesson 1: Introduction to the WHERE Clause

The WHERE clause is an SQL keyword used to filter records based on specific conditions.

Think of it this way: Imagine your school has 500 students, but your teacher only wants to see students in JSS 2. Instead of displaying every student, you can use WHERE to find only the students in JSS 2.

Example:

SELECT * FROM Students
WHERE Class = 'JSS 2';

This query tells the database to display only students whose class is JSS 2.

Let's understand the query:

  • SELECT *: Display all columns.
  • FROM Students: Get information from the Students table.
  • WHERE: Apply a condition.
  • Class = 'JSS 2': Find students whose class is JSS 2.

The WHERE clause makes it easier to find exactly what you need without displaying unnecessary information.

Lesson 2: Using Comparison Operators

Comparison operators help us compare values in a database. They allow us to find records that are equal to, greater than, less than, or different from a particular value.

Here are some common SQL comparison operators:

Operator Meaning Example
= Equal to Age = 13
> Greater than Age > 13
< Less than Age < 13
>= Greater than or equal to Age >= 13
<= Less than or equal to Age <= 13
<> Not equal to Age <> 13

Example 1: Find students who are 13 years old.

SELECT * FROM Students
WHERE Age = 13;

Example 2: Find students older than 13.

SELECT * FROM Students
WHERE Age > 13;

Example 3: Find students younger than 13.

SELECT * FROM Students
WHERE Age < 13;

Example 4: Find students who are 13 years old or older.

SELECT * FROM Students
WHERE Age >= 13;

Example 5: Find students who are not 13 years old.

SELECT * FROM Students
WHERE Age <> 13;

Remember: Text values are usually placed inside single quotation marks, while numbers are normally written without quotation marks.

Lesson 3: Using AND and OR Operators

Sometimes, you may need to check more than one condition at the same time. SQL provides AND and OR operators to help you do this.

1. Understanding the AND Operator

The AND operator is used when all the conditions must be true before a record is displayed.

Imagine you want to find students who are 13 years old AND are in JSS 2. Both conditions must be true.

SELECT * FROM Students
WHERE Age = 13 AND Class = 'JSS 2';

The database will display only students who satisfy both conditions.

2. Understanding the OR Operator

The OR operator is used when at least one of the conditions must be true.

Imagine you want to find students who are either in JSS 1 OR JSS 2.

SELECT * FROM Students
WHERE Class = 'JSS 1' OR Class = 'JSS 2';

The database will display students who belong to either class.

Difference Between AND and OR

Operator How It Works
AND All conditions must be true.
OR At least one condition must be true.

Easy way to remember: AND means all conditions must match, while OR means any one of the conditions can match.

Lesson 4: Using the NOT Operator

The NOT operator is used to reverse a condition. It helps you find records that do not match a particular condition.

Imagine you want to find all students who are NOT in JSS 2.

SELECT * FROM Students
WHERE NOT Class = 'JSS 2';

This query displays students who belong to other classes.

You can also write the same query like this:

SELECT * FROM Students
WHERE Class <> 'JSS 2';

Both examples look for students whose class is different from JSS 2.

Another example:

Imagine a supermarket wants to display products that are not in the Drinks category.

SELECT * FROM Products
WHERE NOT Category = 'Drinks';

The database will display products from categories other than Drinks.

Lesson 5: Filtering Text and Numeric Data

Database tables contain different types of information. Some information is made up of numbers, while other information contains words and letters.

SQL allows you to filter both types of information.

1. Filtering Numeric Data

Numeric data includes values such as age, price, quantity, and examination scores.

Example: Find students who scored 80 marks.

SELECT * FROM Results
WHERE Score = 80;

Example: Find products that cost more than โ‚ฆ5,000.

SELECT * FROM Products
WHERE Price > 5000;

2. Filtering Text Data

Text data includes names, addresses, cities, product categories, and other information containing letters.

Example: Find students from Ibadan.

SELECT * FROM Students
WHERE City = 'Ibadan';

Example: Find customers named Mary.

SELECT * FROM Customers
WHERE Name = 'Mary';

Notice that text values are enclosed in single quotation marks.

Lesson 6: Using BETWEEN, IN and LIKE

SQL provides special operators that make filtering easier. Three useful operators are BETWEEN, IN, and LIKE.

1. The BETWEEN Operator

BETWEEN is used to find values within a specified range. The starting and ending values are included.

Imagine you want to find students whose examination scores are between 50 and 80.

SELECT * FROM Results
WHERE Score BETWEEN 50 AND 80;

This displays students whose scores are 50, 60, 70, 80, or any other value within that range.

Another example: Find products priced between โ‚ฆ2,000 and โ‚ฆ10,000.

SELECT * FROM Products
WHERE Price BETWEEN 2000 AND 10000;

2. The IN Operator

The IN operator helps you search for several possible values in one column without writing many OR conditions.

Imagine you want to find students in JSS 1, JSS 2, or JSS 3.

SELECT * FROM Students
WHERE Class IN ('JSS 1', 'JSS 2', 'JSS 3');

This displays students whose class matches any of the values in the list.

Another example: Find customers from Ibadan, Lagos, or Abuja.

SELECT * FROM Customers
WHERE City IN ('Ibadan', 'Lagos', 'Abuja');

3. The LIKE Operator

The LIKE operator is used to search for a particular pattern in text. It is especially useful when you do not know the complete name or word.

For example, imagine you want to find all students whose names begin with the letter A.

SELECT * FROM Students
WHERE Name LIKE 'A%';

The percent sign (%) is a special wildcard that represents zero or more characters.

Here are some examples:

Pattern Meaning Example Matches
'A%' Starts with A Aisha, Amaka
'%a' Ends with a Fatima, Aisha
'%an%' Contains an Daniel, Anthony
'J%' Starts with J John, James

There is another wildcard called the underscore (_). It represents exactly one character.

Example:

SELECT * FROM Students
WHERE Name LIKE 'J_hn';

This pattern can match a four-character name such as John, where the underscore represents the missing character.

Practical Activity: Filtering School Records

You are now working as a junior database assistant at Bright Future Academy in Ibadan.

The school administrator has provided you with this Students table:

ID Name Age Class City
201 John 13 JSS 2 Ibadan
202 Grace 12 JSS 1 Lagos
203 Michael 14 JSS 3 Abuja
204 Aisha 13 JSS 2 Ibadan
205 David 12 JSS 1 Lagos
206 Amaka 14 JSS 3 Enugu

Task 1: Find All Students Who Are 13 Years Old

SELECT * FROM Students
WHERE Age = 13;

Task 2: Find Students Living in Ibadan

SELECT * FROM Students
WHERE City = 'Ibadan';

Task 3: Find Students in JSS 2 Who Are 13 Years Old

SELECT * FROM Students
WHERE Class = 'JSS 2' AND Age = 13;

Task 4: Find Students Who Are Not in JSS 1

SELECT * FROM Students
WHERE Class <> 'JSS 1';

Task 5: Find Students Whose Names Start With A

SELECT * FROM Students
WHERE Name LIKE 'A%';

Practical Challenge: Supermarket Database

Imagine you are helping a supermarket in Ibadan manage its products. The supermarket has a database table called Products.

The table contains these columns:

  • ProductID
  • ProductName
  • Price
  • Category
  • Quantity

Write SQL queries to perform the following tasks:

  1. Find all products that cost more than โ‚ฆ5,000.
  2. Find products in the Drinks category.
  3. Find products with a quantity less than 10.
  4. Find products priced between โ‚ฆ2,000 and โ‚ฆ10,000.
  5. Find products belonging to either the Food or Drinks categories.
  6. Find products whose names start with the letter S.
  7. Find products that do not belong to the Electronics category.
  8. Find products that cost โ‚ฆ5,000 or more and have a quantity greater than 5.

Important SQL Safety Tip

The WHERE clause is very important when updating or deleting records. Without the correct condition, you may accidentally change or delete many records instead of just one.

Example of a dangerous command:

DELETE FROM Students;

This command deletes all records from the Students table.

A safer example:

DELETE FROM Students
WHERE StudentID = 201;

This command deletes only the record matching StudentID 201, assuming that StudentID identifies one student.

Always double-check your WHERE conditions before running UPDATE or DELETE commands.

Module Summary

In this module, you have learned:

  • The WHERE clause filters records using conditions.
  • Comparison operators help compare values.
  • The AND operator requires all conditions to be true.
  • The OR operator allows at least one condition to be true.
  • The NOT operator reverses a condition.
  • Text and numeric values can be filtered using WHERE.
  • BETWEEN searches for values within a range.
  • IN searches for several possible values.
  • LIKE searches for matching text patterns.
  • WHERE conditions help prevent accidental changes or deletion of records.

Module Assessment

Answer the following questions to test your understanding.

  1. What is the purpose of the WHERE clause?
  2. Which operator is used to check whether two values are equal?
  3. What does the greater-than (>) operator mean?
  4. What is the difference between AND and OR?
  5. Which SQL operator reverses a condition?
  6. Which operator is used to search for values within a range?
  7. What is the purpose of the IN operator?
  8. What does the percent sign (%) mean when used with LIKE?
  9. Write a query to find students who are 14 years old.
  10. Write a query to find customers from Lagos who have spent more than โ‚ฆ20,000.
  11. Write a query to find products priced between โ‚ฆ1,000 and โ‚ฆ5,000.
  12. Write a query to find students whose names begin with M.

Congratulations!

You have successfully completed Module 4 of Basic Queries! You can now filter database records and find specific information using SQL conditions and operators.

Keep practising. You are gradually developing the skills of a database professional!

Coming Up Next

Module 5: Sorting and Limiting Query Results

In the next module, you will learn how to arrange information from smallest to largest, largest to smallest, and display only the number of records you need.

CRMNuggets โ€“ Learn. Practice. Get Certified.

๐Ÿ† Get Certified

๐Ÿ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (โ‚ฆ2,000 or 20,000 coins), and get a verified certificate with your name on it.

๐ŸŽ“ Sign Up to Get Certified
๐Ÿ› ๏ธ Practice Tools
Hands-on simulators & labs - subscription required.
โ†’
๐ŸŽฏ Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
โ†’