Preloader

SELECT DISTINCT and WHERE Clause in SQL

PHP Tutorials
codevigyaan php

SELECT DISTINCT and WHERE Clause are two very important SQL concepts used to control and filter data. They help you remove duplicate values and fetch only the data you actually need from a table.

SELECT DISTINCT in SQL

The SELECT DISTINCT keyword is used to return only unique values from a column. It removes duplicate data from the result.

Why SELECT DISTINCT Is Used

Many tables contain repeated values. SELECT DISTINCT helps you
avoid duplicate results
get clean output
analyze data easily

Syntax of SELECT DISTINCT

SELECT DISTINCT column_name
FROM table_name;

Example Table: students

idnamecity
1RahulDelhi
2AmitMumbai
3NehaDelhi
4PriyaMumbai

Example 1: Get Unique Cities

SELECT DISTINCT city
FROM students;

Output

Delhi
Mumbai

Even though cities repeat in the table, SQL shows each value only once.

Using DISTINCT with Multiple Columns

SELECT DISTINCT name, city
FROM students;

This removes duplicate rows based on both columns together.

WHERE Clause in SQL

The WHERE clause is used to filter records based on a condition. It helps you get only the rows that match your requirement.

Syntax of WHERE Clause

SELECT column_name
FROM table_name
WHERE condition;

Example 2: Fetch Students from Delhi

SELECT * 
FROM students
WHERE city = 'Delhi';

This query returns only students who live in Delhi.

WHERE Clause with Numbers

SELECT * 
FROM students
WHERE id > 2;

This shows students whose id is greater than 2.

WHERE Clause with Multiple Conditions

Using AND

SELECT * 
FROM students
WHERE city = 'Delhi' AND id > 1;

Using OR

SELECT * 
FROM students
WHERE city = 'Delhi' OR city = 'Mumbai';

WHERE Clause with LIKE

SELECT * 
FROM students
WHERE name LIKE 'R%';

This fetches names starting with R.

Using SELECT DISTINCT with WHERE Clause

You can combine both to get filtered unique data.

SELECT DISTINCT city
FROM students
WHERE city = 'Delhi';

This returns Delhi only once.

Why SELECT DISTINCT and WHERE Clause Matter

They help you
remove duplicate values
filter required data
write clean and efficient queries
work with real world databases

Almost every SQL query uses WHERE in some form.

Summary

SELECT DISTINCT removes duplicate values.
WHERE clause filters records using conditions.
Both are essential for writing useful SQL queries.

Check out our resources!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *