Notes

`WHERE` Clause in DBMS (MySQL) [ English ]

< Prev Next >

Introduction

In a Database Management System (DBMS), tables may contain a large amount of data. When retrieving or modifying data, users often need only specific records instead of the entire table. The WHERE clause is used to filter records based on a specified condition.

The WHERE clause is commonly used with SQL commands such as SELECT, UPDATE, and DELETE to work with particular rows in a table.

Definition

The WHERE clause is used in SQL to specify conditions for retrieving, updating, or deleting specific records from a table.

Only the rows that satisfy the given condition are affected by the query.

Syntax

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

Where:

Example Table

Suppose we have a table named students.

id name age course
1 Rahul 20 BCA
2 Anita 21 BBA
3 Rohit 19 BCA
4 Priya 22 BCom

Example 1: Selecting Records with a Condition

SELECT * FROM students
WHERE course = 'BCA';

Output

id name age course
1 Rahul 20 BCA
3 Rohit 19 BCA

Only students enrolled in BCA are displayed.

Example 2: Using WHERE with Numeric Conditions

SELECT * FROM students
WHERE age > 20;

Output

id name age course
2 Anita 21 BBA
4 Priya 22 BCom

Common Comparison Operators

Operator Meaning
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> or != Not equal to

Example:

SELECT * FROM students
WHERE age >= 21;

Using Logical Operators with WHERE

The WHERE clause can also use logical operators to combine conditions.

Operator Description
AND Both conditions must be true
OR At least one condition must be true
NOT Reverses the condition

Example using AND

SELECT * FROM students
WHERE course = 'BCA' AND age > 19;

Example using OR

SELECT * FROM students
WHERE course = 'BCA' OR course = 'BBA';

Using WHERE with UPDATE

UPDATE students
SET course = 'BCA'
WHERE id = 2;

Only the record with id = 2 will be updated.

Using WHERE with DELETE

DELETE FROM students
WHERE id = 3;

This will delete the record where id = 3.

Key Points

Summary

The WHERE clause is an essential part of SQL that allows users to retrieve, update, or delete specific records based on conditions. By filtering data according to requirements, it makes database operations more precise and efficient.

< Prev Next >