Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to find if a value exists in a column?

Author  Topic 

concoran
Starting Member

7 Posts

Posted - 2010-03-05 : 01:13:33
Is there a to find if a certain value exists in a column? For e.g, if zipcode is a column, what is the best way to find if a certain zipcode exists in that column?
TIA

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2010-03-05 : 01:43:13
if exists (select * from tablename where zipcode = value)
select 'already exists'
else
select 'no record'
Go to Top of Page

chriztoph
Posting Yak Master

184 Posts

Posted - 2010-03-05 : 01:46:08
[code]DECLARE @ZipCode varchar(50)

if not exists (select * from TestTable where ZipCode = @ZipCode)
begin
...Do something here!!
end
else
PRINT 'ZipCode already exist'[/code]
Go to Top of Page

raky
Aged Yak Warrior

767 Posts

Posted - 2010-03-05 : 01:50:07
quote:
Originally posted by bklr

if exists (select * from tablename where zipcode = value)
select 'already exists'
else
select 'no record'



Its better to avoid select *. so the statement looks like this

if exists (select 1 from tablename where zipcode = value)
select 'already exists'
else
select 'no record'

Go to Top of Page

vaibhavktiwari83
Aged Yak Warrior

843 Posts

Posted - 2010-03-05 : 02:37:31
I am confused which is faster SELECT 1 or SELECT NULL in exists bracket.
because i always use null in this scenario.

Vabhav T
Go to Top of Page

raky
Aged Yak Warrior

767 Posts

Posted - 2010-03-05 : 02:45:32
quote:
Originally posted by vaibhavktiwari83

I am confused which is faster SELECT 1 or SELECT NULL in exists bracket.
because i always use null in this scenario.

Vabhav T



see this link

http://blog.sqlauthority.com/2010/02/21/sql-server-if-existsselect-null-from-table-vs-if-existsselect-1-from-table/

Go to Top of Page
   

- Advertisement -