Suppose we have the Employee table below, and we want to retrieve all of the cities that the employees live in, but we don’t want any duplicates. How can we do this in SQL? | |||||||||||||||||||||||||||||||||||
In SQL, thedistinct keyword will allow us to do that. Here’s what the simple SQL would look like:
Running this query will return the following results:
So, you can see that the duplicate values for "Russia" and "Canada" are not returned in the results. It’s worth noting that the DISTINCT keyword can be used with more than one column. That means that only the uniquecombination of columns will be returned. Again, this is best illustrated by an example. Suppose we run the following SQL:
If we run the SQL above, it will return this:
Note that the one extra entry for "Alex, Russia" is missing in the result set above. This is because when we select a distinct combination of name and location, if there are 2 entries with the same exact name and location then the sql that we ran above will only return one of those entries. |
Would you like to thankProgrammerInterview.com for being a helpful free resource?Then why not tell a friend about us, orsimply add a link to this page from your webpage using the HTML below.
Link to this page:
Please bookmark with social media, your votes are noticed and appreciated: