Can I make a parameterized equality based condition in the where clause of a SQL statement always true



  • I have a series of queries which depend on a where clause which looks like the following:

    where a = 
      and b = 
      and c = 
      and d = 
    

    The angular brackets represent conditions that are passed in as string parameters from a script containing my queries. I need to modify these queries so that in some instances (that the script decides) the results of my queries are independent of one of those conditions. I was wondering if there is some clever way to construct the parameter to accomplish that, so that my script can simply adjust the parameter when necessary and it flows through all of the queries, rather than modifying each query or making larger modifications to my script.



  • So this can definitely depend on the database system and version you're using, so you should include those as tags on your post, but typically I would write the predicate to have a way to short-circuit based on a certain value of the parameter. Generally I use NULL as the short-circuit value.

    An example of how to re-write your predicate to be able to be short-circuited is like so:

    where ( IS NULL OR a = )
      and ( IS NULL OR b = )
      and ( IS NULL OR c = )
      and ( IS NULL OR d = )
    

    Otherwise, no, I don't think it's possible with your original predicate to pass in some value that always results in true such that it doesn't affect the results (assuming a, b, c, and d are column names and not some construct holding scalar values).




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2