Select UNIQUE or DISTINCT MySQL/PHP Queries

How to filter / remove duplicate items in your database query result using DISTINCT

Say you wanted to show a list of client names from using a portfolio projects database. The problem is you may have multiple portfolio projects for the same client. So if you ran that list, you could get something like: Nike, Nike, Audi, BMW, BMW, Kmart and Ford. Here is how to clean up all duplicate using the “DISTINCT” clause.

$query = "SELECT DISTINCT Client_Name FROM Portfolio ORDER BY Client_Name ASC";
$result = query_db($query);
 
while ($myrow = mysql_fetch_array($result))
{
echo $myrow[Client_Name].", ";
}

Notice how we did not add in “limit 0,1”. DISTINCT does this for us. It will only return one item.

You want to use it without any other columns, otherwise you are going to need a GROUP BY clause.

You may also like...

4 Responses

  1. Johan says:

    This saved me alot of time I accidently added duplicate data 9 pieces of each data. puhhh

  2. This seems like a good query!

  3. web designer says:

    This example has saved me a lot of time. thanks.

  4. arungtm says:

    I need a query which selects unique amounts only,
    for example,

    ID, AMOUNT, CLIENT
    1, 2.3, JOHN
    2, 2.6, MAXTHON
    3, 2.3, HARKE
    4, 2.2, SHYAM
    5, 2.1, JAXON
    6, 2.1, CELINA
    7, 2.6, RAM

    I NEED TO PICK 2.3 as AMOUNT i.e. UNIQUE AND HIGHEST

    Please help me,
    thankx in advance……

Leave a Reply