Distinct Keyword Explained in SQL

Distinct Keyword Explained in SQL

The Distinct keyword is a part of SELECT statement. The term distinct refers to uniqueness. This keyword, in conjunction with the SELECT statement is used to return the distinct or unique values residing within the table rather than all the values.

A column within the same table, may contain many duplicate values; and sometimes, it may be required to list only the different and unique (distinct) values.

Syntax

SELECT DISTINCT column_name_1,column_name_2, … ,column_name_n
FROM tbl_name;

Example

SELECT DISTINCT City from Customers;

The result of above command is that, the DBMS has returned only the City column and one entry of “Birmingham” is missing from the list because of applying distinct keyword.

City
London
Birmingham
Manchester
Cardiff

Distinct keyword works more like an “And” operator meaning, that if Distinct is applying to more columns that it will look for duplicate values in all columns of a particular row and will only function if the whole row is a duplicate otherwise it will mark it as a distinct row.

For example:

SELECT DISTINCT ID, C_Name, City FROM Customers

The above command will return the following records:

ID C_Name Contact_No City Email Status
1 Tim Robbins +44 54 443-4434 London tim@myemail.uk Active
2 James Chris +44 54 498-3476 Birmingham james@myemail.uk Active
3 Kevin Sputnik +44 54 487-6987 Manchester kevin@myemail.uk Inactive
4 Richard Butler +44 54 422-2345 Birmingham richard@myemail.uk Active
5 David McGregor +44 54 413-0989 Cardiff david@myemail.uk Active

Now, the above table shows all record, even the records where 2 rows showing same city entry (i.e. Birmingham). This is because, the rest of the entries within the rows are different and are not duplicated.

More Related Articles For You

    DBMS Tutorial

    SQL and DBMS Interview Questions with Answers

    DBMS and SQL Practice Tests , Questions and Quizzes

Search

Shortcodes Ultimate

 
Follow Us
 
BGP