About Me

Wednesday, 18 April 2012

SQL - Distinct

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.


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
Tia
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.

0 comments:

Post a Comment