SQL > SQL Commands > Distinct

The SELECT keyword allows us to grab all information from a column (or columns) on a table. This, of course, necessarily means that there will be redundancies. What if we only want to select each DISTINCT element? This is easy to accomplish in SQL. All we need to do is to add DISTINCT after SELECT. The syntax is as follows:

SELECT DISTINCT "column_name"
FROM "table_name";

For example, to select all distinct stores in Table Store_Information,

Table Store_Information

Store_NameSalesTxn_Date
Los Angeles1500Jan-05-1999
San Diego250Jan-07-1999
Los Angeles300Jan-08-1999
Boston700Jan-08-1999

we key in,

SELECT DISTINCT Store_Name FROM Store_Information;

Result:

Store_Name
Los Angeles
San Diego
Boston

Exercises

For these exercises, assume we have a table called Users with the following data:

Table Users

First_NameLast_NameBirth_DateGenderJoin_Date
SophieLeeJan-05-1960FApr-05-2015
RichardBrownJan-07-1975MApr-05-2015
JamalSantoOct-08-1983MApr-09-2015
CaseyHealySep-20-1969MApr-09-2015
JillWilkesNov-20-1979FApr-15-2015

1. Which of the following SQL statement is valid?
a) SELECT DISTINCT * FROM Users;
b) SELECT DISTINCT First_Name FROM Users;
c) SELECT DISTINCT First_Name Last_Name FROM Users;

2. What's the result of the following query?
SELECT DISTINCT Join_Date From Users;

3. What's the result of the following query?
SELECT DISTINCT Gender, Join_Date From Users;

Next: SQL WHERE




Copyright © 2015   1keydata.com   All Rights Reserved.     Privacy Policy     About   Contact