Conditional queries
Sometimes you might to add where conditions dynamically (base on the user input). This can be achieved in different ways with TypeSQL.
Conditional filters in SQL
This can be done using the IS NULL
condition.
Here is an example of a query with optional age
and name
filters:
Then you can run the query passing only the filters you want: For example, code below will only filter by name:
Or filter only by age:
Conditional filters in SQL for list
It also works with the IN
operator, but you can’t use :param is NOT NULL
when :param
is a list.
Instead you can do as following:
And you can run the query like this:
Or if you don’t want to filter by category:
More complicated dynamic queries can be done similarly. But If you need something more dynamic (choose columns to be SELECTed or need conditional JOINs or CTE) you can use the dynamic queries feature.