Wednesday, 26 June 2013

How to use SELECT DISTINCT In SQL

sql - distinct

In previous chapter i have explained you How To Use Between statement In SQL
Now i am gonna eplain you How To Use SELECT DISTINCT In SQL

SQL SELECT DISTINCT is a very useful way to eliminate retrieving duplicate data reserved for very specific situations. To understand when to use theDISTINCT 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
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.

No comments: