Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find Column with same (some x value) value repeated more than once? Needs to return those rows.

There is a table called contacts with columns id, name, address, ph_no etc.
I need to find out rows with the same name, if the rows count is more than 1, show those rows.

For example:
Table: contacts

id--------name--------address---------ph_no--------
111       apple       U.K             99*******
112       banana      U.S             99*******
123       grape       INDIA           99*******
143       orange      S.AFRICA        99*******
152       grape       KENYA           99*******

For the above table I need to get rows with same column name data like the below:

id--------name--------address---------ph_no--------
123       grape       INDIA           99*******
152       grape       KENYA           99*******

I need to get the rows based on the name what I given as argument like below example syntax:

select * from contacts where name='grape' and it's count(*) >1 return those rows.

How can I achieve the solution for above problem.

like image 764
Chandra Sekhar Avatar asked Nov 30 '11 13:11

Chandra Sekhar


People also ask

How do you check if a 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.

Which of these is used to find the rows with specific column values quickly?

Indexes are used to find rows with specific column values quickly.

Which of these is used to put the same value in all the rows?

The GROUP BY Clause SQL is used to group rows with same values. The GROUP BY Clause is used together with the SQL SELECT statement.


1 Answers

As @vc74 suggests analytic functions would work work a lot better here; especially if your data has any volume.

select id, name, address, ph_no ...
  from ( select c.*, count(name) over ( partition by name ) as name_ct
           from contacts c )
 where name_ct > 1
       ;

EDIT

restricting on specific names the table contacts should really have an index on name and the query would look like this:

select id, name, address, ph_no ...
  from ( select c.*, count(name) over ( partition by name ) as name_ct
           from contacts c
          where name = 'grape' )
 where name_ct > 1
       ;
like image 59
Ben Avatar answered Sep 22 '22 14:09

Ben