Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you query an int column for any value?

Tags:

How can you query a column for any value in that column? (ie. How do I build a dynamic where clause that can either filter the value, or not.)

I want to be able to query for either a specific value, or not. For instance, I might want the value to be 1, but I might want it to be any number.

Is there a way to use a wild card (like "*"), to match any value, so that it can be dynamically inserted where I want no filter?

For instance:

select int_col from table where int_col = 1  // Query for a specific value select int_col from table where int_col = *  // Query for any value 

The reason why I do not want to use 2 separate SQL statements is because I am using this as a SQL Data Source, which can only have 1 select statement.

like image 282
Bill Software Engineer Avatar asked May 16 '12 15:05

Bill Software Engineer


People also ask

How do I SELECT just the value of an integer in SQL?

select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$'; The query wherein we have used regular expression. This will output only the integer value.

What is INT data type in SQL?

The int data type is the primary integer data type in SQL Server. The bigint data type is intended for use when integer values might exceed the range that is supported by the int data type. bigint fits between smallmoney and int in the data type precedence chart.


1 Answers

Sometimes I would query for actual value (like 1, 2...) so I can't not have a condition either.

I take it you want some dynamic behavior on your WHERE clause, without having to dynamically build your WHERE clause.

With a single parameter, you can use ISNULL (or COALESCE) like this:

 SELECT * FROM Table WHERE ID = ISNULL(@id, ID) 

which allows a NULL parameter to match all. Some prefer the longer but more explicit:

 SELECT * FROM Table WHERE (@id IS NULL) OR (ID = @id) 
like image 182
Mark Brackett Avatar answered Oct 02 '22 20:10

Mark Brackett