Bookmark and Share

SQL - Distinct

SQL SELECT DISTINCT is a very useful way to eliminate retrieving duplicate data reserved for very specific situations. To understand when to use the DISTINCT command, let's look at a real world example where this tool will certainly come in handy.

Advertise on Tizag.com

If you've been following along in the tutorial, we have created an orders table with some data inside that represents different orders made by some of our very loyal customers over a given time period. Let's pretend that we have just heard word from our preferred shipping agent that orders made in August require no shipping charges, and we now have to notify our customers. We do not want to send mailers to all of our customers, just the ones that have placed orders in August. Also, we want to avoid retrieving duplicate customers as our customers may have placed more than one order during the month of August.

We can write a very simple SQL query to extract this information from the orders table:

SQL Select Distinct:

USE mydatabase;

SELECT DISTINCT customer
FROM orders
WHERE day_of_order BETWEEN '7/31/08' AND '9/1/08';

SQL Results:

customer
A+Maintenance
Gerald Garner
Tizag

Running this query yields a list of all the customer's affected by our unexpected news from the shipping agency. With this list, we can now go about contacting each of these customers and informing them of the good news without worrying about contacting the same customer multiple times.

Bookmark and Share




Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials