Using WHERE to Filter Data

Tutorial 3 of 5

Introduction

In this tutorial, we aim at helping you understand how to use the SQL WHERE clause to filter data based on specific conditions. The WHERE clause is a powerful tool that can significantly enhance your data retrieval capabilities in SQL.

By the end of this tutorial, you will be able to:
- Understand the concept of the WHERE clause in SQL
- Apply the WHERE clause in SQL queries to filter data
- Use logical operators with the WHERE clause

Prerequisites: Basic knowledge of SQL and its syntax.

Step-by-Step Guide

The WHERE clause is used in SQL to filter records. It is used to extract only those records that fulfill a specified condition.

Syntax:

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

You can use logical operators like =, <>, >, <, >=, <= along with WHERE clause to filter the results. Let's understand this with examples.

Code Examples

Consider a table called Employees with the following data:

EmpId EmpName EmpAge EmpSalary
1 John 35 5000
2 Smith 40 6000
3 David 30 7000
4 Sara 20 8000

Example 1: Using WHERE with = operator

If you want to fetch records of the employee with EmpId = 1, the SQL query would look like this:

SELECT *
FROM Employees
WHERE EmpId = 1;

This will return the following output:

EmpId EmpName EmpAge EmpSalary
1 John 35 5000

Example 2: Using WHERE with > operator

If you want to fetch records of employees with EmpSalary more than 6000, the SQL query would look like this:

SELECT *
FROM Employees
WHERE EmpSalary > 6000;

This will return the following output:

EmpId EmpName EmpAge EmpSalary
3 David 30 7000
4 Sara 20 8000

Summary

In this tutorial, we learned about the SQL WHERE clause, its purpose, and how to use it with different operators to filter data. Continue practicing with different operators and conditions to grasp the concept better.

Practice Exercises

  1. Write a SQL query to fetch records of employees with EmpAge less than 35.
  2. Write a SQL query to fetch records of employees with EmpName not equal to 'John'.

Solutions:

SELECT *
FROM Employees
WHERE EmpAge < 35;
SELECT *
FROM Employees
WHERE EmpName <> 'John';

Keep experimenting with different conditions and operators to gain more confidence and proficiency with the WHERE clause.