Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional select query

I have a large SQL query with multiple statements and UNION ALL. I am doing something like this now:

DECLARE @condition BIT;
SET @condition = 0;

SELECT * FROM table1
WHERE @condition = 1;

UNION ALL

SELECT * FROM table2

In this case, table1 won't return any results. However, that query is complex with many joins (such as FullTextTable). The execution plan's estimate shows a high cost, but the actual number of rows and time to execute seems to show otherwise. Is this the most efficient way of filtering a whole query, or is there a better way? I don't want anything in the first select to run, if possible.

like image 749
Nelson Rothermel Avatar asked May 24 '26 11:05

Nelson Rothermel


1 Answers

I would imagine that your eventual SQL query with all of the unions and conditions that depend on pre-calculated values gets pretty complicated. If you're interested in reducing the complexity of the query (not to the machine but for maintenance purposes), I would go with a moving the individual queries into views or table valued functions to move that logic elsewhere. Then you can use the if @condition = 1 syntax that has been suggested elsewhere.

like image 102
Jeff Hornby Avatar answered May 26 '26 04:05

Jeff Hornby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!