WHERE Clause

Introduction

The WHERE clause in SQL is used to filter records in a table based on a specified condition. It allows you to retrieve only the rows that meet certain criteria, making your queries more precise and efficient.

Syntax

SELECT column1, column2
FROM table_name
WHERE condition;
  • SELECT specifies the columns to retrieve.
  • FROM specifies the table to query.
  • WHERE defines the condition that the rows must satisfy.

Example 1: Basic Filtering

Retrieve all employees from the “Employees” table who work in the “Sales” department:

SELECT FirstName, LastName, Department
FROM Employees
WHERE Department = 'Sales';

Example 2: Using Comparison Operators

You can use comparison operators such as =, >, <, >=, <=, <>:

SELECT FirstName, LastName, Salary
FROM Employees
WHERE Salary > 50000;

Example 3: Using Logical Operators

Combine multiple conditions using AND, OR, and NOT:

SELECT FirstName, LastName, Department, Salary
FROM Employees
WHERE Department = 'Sales' AND Salary > 50000;

Example 4: Using Pattern Matching

Use LIKE to search for a specific pattern:

SELECT FirstName, LastName
FROM Employees
WHERE FirstName LIKE 'J%';

This retrieves all employees whose first name starts with “J”.

Example 5: Using NULL Values

Check for NULL values with IS NULL or IS NOT NULL:

SELECT FirstName, LastName, ManagerID
FROM Employees
WHERE ManagerID IS NULL;

Key Points to Remember

  • The WHERE clause always comes after the FROM clause.
  • Conditions can include columns, constants, and expressions.
  • Use parentheses () to group conditions for complex queries.
  • Filtering reduces the number of rows returned, improving query performance.
Home » SQL Foundations Program (SQL-101) > Basic Queries > WHERE Clause