22 Votes

MySQL: Exclude double Values from Search Result

Question by Guest | Last update on 2021-05-04 | Created on 2016-02-13

Is there any possibility in MySQL with which you can exclude double values or records from the search results?

In my case, I want to write out all last names or cities from a table with data, for example. The cities and names can appear multiple times in their corresponding column, but I only want to have them once in my result.

If I write "SELECT city FROM tab" oder "SELECT name FROM tab", I get many duplicate values. What can I do to read out and list only the different values?

ReplyPositiveNegative
2Best Answer2 Votes

You can work with the keyword DISTINCT, for example.

In order to read out all different cities and names and to prevent duplicate entries in the search result, you can write the following:

SELECT DISTINCT city FROM tab;
SELECT DISTINCT name FROM tab;

SELECT DISTINCT is also working over multiple columns. You can use that for example, if you also want to read out the postal code for each town:

SELECT DISTINCT postalcode, city FROM tab;

Another approach is to work with GROUP BY:

SELECT COUNT(id), city FROM tab GROUP BY city;

With this query, we are counting how often each city is appearing in the table and we are showing the number as well as the name of the city in the result.
Last update on 2021-05-04 | Created on 2016-02-13

ReplyPositive Negative
Reply

Related Topics

The Askingbox Search

Info | 0 Comments

Google Tips

Tip | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.