question on if exists?

dkim18
dkim18 used Ask the Experts™
on
Hi,
I am trying to check if something exists.
How do I do this in sql?

table1(id1,name)
table2(id2,name)
if exists (select * from table1 OR Select * from table2)..

Do I need to do this instead?
if exists( select * from table1) OR exist(Select * from table2)

Can I use OR like this?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
SQL Server DBA
Top Expert 2011
Commented:
You can use UNION

IF EXISTS (SELECT ID1,Name from table1 UNION SELECT ID2, Name from table2)
BEGIN
         PRINT 'records exists'
END
awking00Information Technology Specialist
Commented:
In pure sql (i.e. not PL/SQL), exists is a boolean operator and is only used in a where clause, so the syntax is where exists and not if exists. To say something like select * from tableA where exists (select * from tableB) would return everything as long as tableB contained at least one row and, therefore, be superfluous. However, if you were trying to only get records from tableA where some column matched some column in tableB, you should use where exists - Select * from tableA where exists(select column from tableB where column = tableA.column).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial