SQL Server (2014) Query Optimization when using filter variable passed to procedure -
i looking optimization techniques or hint me move ahead problem have. using temp table in clause makes query run more 5 seconds, changing static value returns data under second. trying understand way optimize this.
-- details number of rows in table dept_activity table - total rows - 17,319,666 - rows (dept_id = 10) - 36054 -- temp table create table #tbl_depts ( id int identity(1, 1) primary key ,dept_id integer ); -- example inserted 1 row based on conditions multiple department numbers inserted in temp table insert #tbl_depts(dept_id) values(10); -- query takes more 5 seconds select activity_type,count(1) rc dept_activity da ( @filter_by_dept null or da.depart_id in ( select td.dept_id #tbl_depts td ) ) group activity_type; -- query takes less 500 milli seconds select activity_type,count(1) rc dept_activity da ( @filter_by_dept null or da.depart_id in ( 10 -- changed static value ) ) group activity_type; what ways can optimize return data first query under second.
you're testing 1 value, isn't real case different?
the problem optimizer has here can't know how many rows temp. table in -clause find, it'll have make guess, , why result different. looking @ estimated row counts (+vs actual) might give insight on this.
if clause contains 1 criteria:
@filter_by_dept null or da.depart_id in it might test happens if separate logic if blocks, 1 fetches all, , other filters data.
if that's not real case, might want test both option (recompile), result better plan, use (little bit) more cpu since plan re-generated every time. or constructing clause dynamic sql (either temp table optimizing away or statements, or doing full in clause if there isn't ridiculous amount of values), might ugly.
Comments
Post a Comment