⬅ Previous Topic
SELECT Statement in SQLNext Topic ⮕
ORDER BY Clause in SQL⬅ Previous Topic
SELECT Statement in SQLNext Topic ⮕
ORDER BY Clause in SQLImagine walking into a school library and asking for *every* book. Not practical, right? Instead, you specify — “Books by R.K. Narayan” or “Books for Class 10.” SQL works the same way. The WHERE
clause lets you filter records and get only what matters.
SELECT column1, column2, ...
FROM table_name
WHERE condition;
We’ll use this familiar table for examples:
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10),
age INT,
city VARCHAR(30)
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', '10A', 15, 'Delhi'),
(2, 'Diya Iyer', '9B', 14, 'Chennai'),
(3, 'Rohit Menon', '10A', 15, 'Kochi'),
(4, 'Sneha Patil', '8C', 13, 'Pune'),
(5, 'Mehul Agarwal', '9B', 14, 'Delhi');
Let’s fetch students from Class 9B:
SELECT name, class FROM students
WHERE class = '9B';
name | class
----------------+-------
Diya Iyer | 9B
Mehul Agarwal | 9B
Find students who are 15 years old:
SELECT name, age FROM students
WHERE age = 15;
name | age
----------------+-----
Aarav Sharma | 15
Rohit Menon | 15
Retrieve students from Delhi in Class 9B:
SELECT name FROM students
WHERE city = 'Delhi' AND class = '9B';
name
------------
Mehul Agarwal
Get students from either Delhi or Pune:
SELECT name, city FROM students
WHERE city = 'Delhi' OR city = 'Pune';
name | city
----------------+--------
Aarav Sharma | Delhi
Sneha Patil | Pune
Mehul Agarwal | Delhi
Get students who are not from Delhi:
SELECT name, city FROM students
WHERE NOT city = 'Delhi';
Find students aged between 14 and 15:
SELECT name, age FROM students
WHERE age BETWEEN 14 AND 15;
Get students from specific cities:
SELECT name, city FROM students
WHERE city IN ('Delhi', 'Chennai', 'Kochi');
Find students whose name starts with 'S':
SELECT name FROM students
WHERE name LIKE 'S%';
name
----------
Sneha Patil
=
(equal)!=
or <>
(not equal)<
(less than)>
(greater than)<=
, >=
SELECT name, age FROM students
WHERE age < 14;
name | age
----------------+-----
Sneha Patil | 13
The WHERE
clause is your precision tool in SQL. Whether you’re isolating top scorers, filtering students by class, or narrowing records by location — WHERE helps you focus on what truly matters.
Now that you can filter your data confidently, it’s time to learn how to sort it — with the ORDER BY
clause.
SELECT name FROM students WHERE city = 'Hyderabad';
⬅ Previous Topic
SELECT Statement in SQLNext Topic ⮕
ORDER BY Clause in SQLYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.