sql server - SQL slow subquery -
i trying retrieve data large audits table (millions of rows). need make query run efficiently possible. first playing subquery return objecttypeid , use limit query on audit table
this query taking 4 minutes run:
select distinct audits.objecttypeid, count(*) count audits audits audits.objecttypeid = (select distinct objecttype.objecttypeid objecttype objectname = 'data') group audits.objecttypeid
if default in objecttypeid query runs in 42 seconds
select distinct(audits.objecttypeid), count(*) count audits audits.objecttypeid = 1 group audits.objecttypeid
but subquery when run in isolation takes second run. why should first query take long?
i can see 3 things might help:
- pull
objecttypeid
variable: since there should 1 value it - take out
distinct
on both queries since should unnecessary (the subquery should have 1 value , grouping value in outer query - take out group since querying 1
objecttypeid
so final query be:
declare @objecttypeid int select @objecttypeid = (select objecttype.objecttypeid objecttype objectname = 'data') select audits.objecttypeid, count(*) count audits audits audits.objecttypeid = @objecttypeid
if executing single statement , not batch or stored procedure (meaning can't use variables) thne can keep subquery:
select audits.objecttypeid, count(*) count audits audits audits.objecttypeid = (select objecttype.objecttypeid objecttype objectname = 'data')
Comments
Post a Comment