I have MySQL database and a have a table named CALLER. In table caller I need to check if in column USERNAME there are values which exist more than once and if exist to list all these values.
Thank you
To find duplicate values in SQL, you must first define your criteria for duplicates and then write the query to support the search. In order to see how many of these names appear more often than others, you could add an additional ORDER BY statement to the end of the query and order by DESC.
To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.
The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.
Ususlly you can do this using GROUP BY
and HAVING COUNT(*)>1
SELECT USERNAME FROM CALLER
GROUP BY USERNAME
HAVING COUNT(*)>1
Update: To get all duplicate rows:
SELECT * FROM CALLER WHERE USERNAME IN
(
SELECT USERNAME FROM CALLER
GROUP BY USERNAME
HAVING COUNT(*)>1
)
Before getting to the answer....
It would have been a help if you'd provided the full table structure (as a CREATE TABLE statement)
If you need to apply this exercise it implies your database design is wrong - and after you've identified the duplicates and resolved them then you should add a unique index on the relevant column.
Assuming that you've got an auto-increment field, or some other value (such as created date) which differentiates between rows with the same USERNAME....
SELECT a.id, username, b.id
FROM caller a
INNER JOIN caller b
ON a.username=b.username
AND b.id>a.id
Note that this will report some rows more than once if the username exists for more than 2 rows. Alternately:
SELECT username, COUNT(DISTINCT id), MIN(id), MAX(id)
FROM caller
GROUP BY username
HAVING count(*)>1
But this won't explicitly identify all the ids where there are more than 2 rows with a specific username.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With