Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Select All Or One With A Single Query

DZone's Guide to

Select All Or One With A Single Query

·
Free Resource
Very often, you'll have the need to select either everything from a table or just a single record. This is the way to do both given a single query. When @EmployeeID is NULL, it will return all records from Employee, when a value is present, it will return only the value that is present.


-- Use one query to select a record given an identifier or all records when that ID is NULL

declare @EmployeeID int
set @EmployeeID = 42 -- NULL

select *
from Employee
where EmployeeID = coalesce(@EmployeeID, EmployeeID)
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}