Monday, December 31, 2007

How to avoid Duplicate records in SQL select query

DISTINCT command in SQL collects the unique or distinct records from a field of a table. In the student table we are interested to know how many class records are there and the DISTINCT sql command should return class once only. So if class five is there ten times then it should return once and if class six one record is there then class six should return once.

So using DISTINCT sql command we can avoid duplicate records in SELECT query
by using DISTINCT sql command we can select unique records from DataBase
There is another related command sql group by which groups the data and brings the unique names. This group by command is usually used along with count, average, minimum, maximum commands. Here we will discuss sql distinct command only


DISTINCT command will return records once only.

SELECT DISTINCT class FROM student
This is our table and we will apply DISTINCT command to this table.

id name class mark
1 John Deo Four 75
2 Max Ruin Three 85
3 Arnold Three 55
4 Krish Star Four 60
5 John Mike Four 60
6 Alex John Four 55
Here again the DISTINCT command in SQL
SELECT DISTINCT class FROM `student`
The output is displayed here
class
Four
Three
As you can see only two rows are returned and they are the distinct class in the table

No comments: