1

I have a huge dataset with about 400,000 rows. I want to select only the rows where the value of the second column (val) exists in the third column (ecr) in the same table.

For example, in the sample screenshot shown below, the value of the column val on the second row (4294939057) is equal to third row value of column ecr.

I tried with the following query but it doesn't seem to give the correct rows.

Any tips would be very much appreciated.

use dbTest

select val, ecr 
from tableTest 
group by val 
having COUNT (val) > 1

I am using SQL Server 2008.

enter image description here

1
  • do you have a primary key column on this table? Commented Feb 20, 2017 at 17:54

3 Answers 3

3

You should use a self join (could be you need proper separated index on val and ecr due the dimension of your table )

select a.*, b.* 
from tableTest as a 
  inner join tableTest as b  
    on a.val  = b.ecr 
Sign up to request clarification or add additional context in comments.

1 Comment

@DestaHaileselassieHagos change where to on
2

If you do not want the full output from an inner join, you could use something like this:

select *
from tableTest as t
where exists (
  select 1 
  from tableTest as i  
  where t.val  = i.ecr
  )

4 Comments

This is the better solution, because it does not multiply the number of rows.
This is actually better where you don't have to show all the output of the inner join.
@sqlzim, But why select 1?
@DestaHaileselassieHagos There is no runtime performance difference between select 1 and select * when using exists(). Although using select 1 will avoid having to examine any unneeded metadata for that table during query compilation. EXISTS Subqueries: SELECT 1 vs. SELECT * - Conor Cunningham
1

The other option besides the join is a subquery:

SELECT *
FROM tableTest
WHERE val IN (SELECT ecr FROM tableTest)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.