Skip to main content
Inspiring
April 27, 2007
Question

How to say 'all' in SQL

  • April 27, 2007
  • 3 replies
  • 272 views
I have a form with 3 drop downs to pass values to a query

Select name, class, date
From table
where <cfif #name# is 0>
name in 'this is where I want to say all names'
<cfelse>



This topic has been closed for replies.

3 replies

Inspiring
April 27, 2007
SELECT name, class, date
FROM table
<cfif form.name neq 0>
WHERE name = <cfqueryparam cfsqltype="cf_sql_integer" value="#form.name#>
</cfif>

This works well for the specified requirement. But when one is dealing
with more complex where clauses that one can't completely write out
literals can be used to great effect.

SELECT stuff
FROM aTable
WHERE
1=1 <!--- Will select everything unless further parameters modify
this. --->
<conditional logic>
AND something = somevalue
</conditional logic>

OR
SELECT stuff
FROM aTable
WHERE
1=0 <!--- Will select nothing unless further parameters modify this. --->
<conditional logic>
OR something = somevalue
</conditional logic>

This technique is more useful when one has multiple where clause
conditions that may or may not be used.
Inspiring
April 27, 2007
use reversed logic: if form.name is not 0, select only name that =
form.name. in this case if form.name is 0, no condition will apply and
all records will be pulled:

SELECT name, class, date
FROM table
<cfif form.name neq 0>
WHERE name = <cfqueryparam cfsqltype="cf_sql_integer" value="#form.name#>
</cfif>

NOTE: i have used the <cfqueryparam> tag, which i suggest you get into
the habbit of using, too (unless you always cache your queries).

--

Azadi Saryev
Sabai-dee.com
http://www.sabai-dee.com
jenn1Author
Inspiring
April 27, 2007
Sorry, I hit post before I finished the message:

I have a form with 3 drop downs to pass values to a query. If nothing is selected for "name", I want my query to pull all names. I don't want to do this with a list because the name list is very long. How can I say this in SQL?

Select name, class, date
From table
where <cfif #name# is 0>
name in 'this is where I want to say all names'
<cfelse>
name = #form.name#
</cfif>

Thanks!