In SQL Server, is TOP deterministic by default when used on a table with a clustered index? -


so trying explain people why query bad idea:

select z.reportdate, z.zipcode, sum(z.sales) sales, coalesce(   (select top (1) groupname   dbo.zipgroups   (zipcode = z.zipcode)), 'unknown') groupname, coalesce(   (select top (1) groupcode   dbo.zipgroups   (zipcode = z.zipcode)), 0) groupnumber dbo.report_byzipcode z group z.reportdate, z.zipcode 

and suggesting better way write it, when boss ended discussion with, "well, it's been returning right data last year , haven't had problems it, it's fine."

at point thought myself, how in world possible?

after digging, discovered these facts:

  1. this query supposed group sales zipcode , date, , link largest group (by population size) zipcode assigned way of zipgroups table.
  2. each zipcode can assigned 0 many groups, , if zipcode assigned 0 groups, it's not in zipgroups table.
  3. a group geographical area, , groupnumbers ranked largest smallest population (for example, group covering ny-nj-ct tri-state area groupnumber 1, , north platte, nebraska groupnumber 209).
  4. the zipgroups table has not changed in @ least 2 years.
  5. the zipgroups table has clustered index zipcode, groupnumber (ascending) keys.
  6. the combination of zipcode, groupnumber unique in zipgroups.

so question has 2 parts.

a) though there no order clauses in select top queries, deterministic because clustered index providing default order by?

b1) if true, query, however precariously, doing it's supposed do?

b2) if not true, can me prove it?

note: i've re-written use joins, don't need sql fix it, need production stop worrying breaking.

sql server makes no guarantees ordering of records in absence of order by. might yield correct results 999,999 times , fail on millionth try. don't it.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -