The SELECT DISTINCT statement functions in much the same way as a standard select statement but will only return distinct column values. Meaning any duplicate values within that column will only be returned once, all subsequent occurrences will be omitted from the results.
The statement itself will look something like this, where column_name is the column from which the distinct values will be pulled.
SELECT DISTINCT column_name FROM table_name
It may be that you wish it return distinct values over multiple columns. This is done in much the same way with each column being separated by a comma.
SELECT DISTINCT column_one, column_two FROM table_name
In the above query you would be returning distinct combinations of the two columns. For example a value may appear multiple times in column_one but the rows would still be returned when the column_two values are different. Only rows in which both columns are duplicated will be omitted.
SELECT DISTINCT Example
Below is the ages table that we will be using in this example.
So a valid multiple column distinct query from this table would be.
SELECT DISTINCT name, age FROM ages
And the results would look like this.
Notice that only one row has been omitted from the original database the second occurence of ben. This is the only row which is not distinct under the conditions we have given.
As always you can use the astrix to represent all columns in the database but remember that only rows with identical information will be omitted from the results.
Click the next article below to see how we can use other SQL statements to filter the data in more advanced ways.
blog comments powered by Disqus