0

I have the following query that checks if two columns of a table are in another The query works, I hope you can optimize the call in because they are equal. I doubt if there is a performance penalty because two calls are made to the same query

SELECT name,lastname FROM TABLA_A
WHERE 
name IN (
  SELECT name FROM TABLE_B
)
OR
lastname IN (
  SELECT lastname FROM TABLE_B
)

ANOTHER WAY

SELECT a.name,a.lastname
FROM TABLE_A as a
join TABLE_B  as b on a.name=b.name
or a.lastname= b.lastname

try to join, is a valid option? there are other ways to make this task more efficient? thank you very much

6
  • Please synchronize two queries. It is hard to understand the columns from two query. If they return same result edit them with same column name. Commented Sep 28, 2016 at 5:53
  • Indeed INNER JOIN is the best and simplest option. Commented Sep 28, 2016 at 5:54
  • You can use EXISTS Commented Sep 28, 2016 at 5:59
  • I replaced the incorrect sql-server tag with mysql because of the question's title Commented Sep 28, 2016 at 6:01
  • Keep in mind that would like to know your options and compare performance (use Sql Sever) Commented Sep 28, 2016 at 6:04

3 Answers 3

1

There is a performance issue in using OR that you can use UNION instead like this:

SELECT name, lastname 
FROM TABLE_A
WHERE name IN (
  SELECT name 
  FROM TABLE_B)
UNION -- If there is not any duplicate use `UNION ALL` instead
SELECT name, lastname 
FROM TABLE_A
WHERE lastname IN (
  SELECT lastname 
  FROM TABLE_B);

[SQL Fiddle Demo]

Sign up to request clarification or add additional context in comments.

4 Comments

this would make return duplicate records if both the value and a.lastname a.name are in the TABLE_B?
Using UNION will remove duplicates !?
It is possible with this solution proposed to eliminate duplicate records returned?
How those records should eliminate? and if you have another question ask another question ;).
1

You can use EXISTS which works more efficiently than IN from every aspects:

SELECT a.name,
    a.lastname
FROM TABLE_A as a
WHERE EXISTS (SELECT b.name 
             FROM TABLE_B b WHERE a.name = b.name OR a.lastname= b.lastname)

1 Comment

0

As you have already done

SELECT a.name, a.lastname
FROM TABLE_A as a
INNER JOIN TABLE_B as b on a.name=b.name OR a.lastname= b.lastname

1 Comment

is the method I made, any other suggestions?

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.