Anup Pandey
Anup Pandey

Reputation: 15

How to check a value exists in which table in SQL?

I have two tables with identical columns, say Table A and Table B and both have column ID. I have a value of ID 'ABC'. How will I check ABC exists in ID column of which table? I need output as the table name.

Upvotes: 0

Views: 67

Answers (2)

Multisync
Multisync

Reputation: 8787

select tab from (
  select 'A' tab, count(*) n from tabA where id = 'ABC'
  union all 
  select 'B' tab, count(*) n from tabB where id = 'ABC'
) where n > 0;

Upvotes: 0

fancyPants
fancyPants

Reputation: 51868

SELECT 'A' as table_name FROM DUAL WHERE EXISTS( SELECT 1 FROM A WHERE id = 'ABC')
UNION ALL
SELECT 'B' FROM DUAL WHERE EXISTS( SELECT 1 FROM B WHERE id = 'ABC')

DUAL is a kind of placeholder you can use, if you don't have a table to select from.

Upvotes: 1

Related Questions