How to select records without duplicate on just one field in SQL?

Mohammad Saberi picture Mohammad Saberi · Sep 2, 2012 · Viewed 414.1k times · Source

I have a table with 3 columns like this:

+------------+---------------+-------+  
| Country_id | country_title | State |  
+------------+---------------+-------+    

There are many records in this table. Some of them have state and some other don't. Now, imagine these records:

1 | Canada  | Alberta  
2 |  Canada | British  Columbia  
3 | Canada  | Manitoba  
4 | China   |

I need to have country names without any duplicate. Actually I need their id and title, What is the best SQL command to make this? I used DISTINCT in the form below but I could not achieve an appropriate result.

SELECT DISTINCT title,id FROM tbl_countries ORDER BY title

My desired result is something like this:

1, Canada  
4, China

Answer

Mark Byers picture Mark Byers · Sep 2, 2012

Try this:

SELECT MIN(id) AS id, title
FROM tbl_countries
GROUP BY title