Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL check if value exist more than once [closed]

Tags:

mysql

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

like image 570
Fi3n1k Avatar asked Nov 22 '13 11:11

Fi3n1k


People also ask

How do you check if value appears more than once in SQL?

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.

How do you check if a row already exists in MySQL?

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.

How do I check if a record exists in SQL?

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.


2 Answers

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
  )
like image 194
valex Avatar answered Oct 17 '22 02:10

valex


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.

like image 24
symcbean Avatar answered Oct 17 '22 02:10

symcbean