[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

MS SQL order by with "over" statement and row_number()

Posted on 2016-10-07
11
Medium Priority
?
96 Views
Last Modified: 2016-10-11
I have a query I use frequently that someone helped me write several years ago, which I often create variations on. I thought I understood exactly what it does, but I am finding a discrepancy with the "order by" that I don't understand.

This query does what I want, which is simply an alphabetical sort on the "description" column:

select distinct
	description
from
	(select row_number() over (order by description) as rownum, description
		from tbl_product
		where (itemid='LUGS & H-TAPS : YAV2CLTC10FX' or itemid='LUGS & H-TAPS : YAV2CL2TC14E2FX')) as qryresults

Open in new window


RESULT:

description
"LUG COMPRESSION # 2 AWG FLEX 1 HOLE #10 STUD STANDARD BARREL 0.68"" TONGUE WIDTH BROWN W/ INSP WNDW BURNDY"
"LUG COMPRESSION # 2 AWG FLEX 2 HOLE 1/4"" STUD 3/4"" CENTER STANDARD BARREL 0.68"" TONGUE WIDTH BROWN W/ INSP WNDW BURNDY"

Open in new window


This query returns the same two results, but the "order by" is backwards:

select distinct
	itemid, description
from
	(select row_number() over (order by description) as rownum, itemid, description
		from tbl_product
		where (itemid='LUGS & H-TAPS : YAV2CLTC10FX' or itemid='LUGS & H-TAPS : YAV2CL2TC14E2FX')) as qryresults

Open in new window


RESULT:

itemid 	description
LUGS & H-TAPS : YAV2CL2TC14E2FX	"LUG COMPRESSION # 2 AWG FLEX 2 HOLE 1/4"" STUD 3/4"" CENTER STANDARD BARREL 0.68"" TONGUE WIDTH BROWN W/ INSP WNDW BURNDY"
LUGS & H-TAPS : YAV2CLTC10FX	"LUG COMPRESSION # 2 AWG FLEX 1 HOLE #10 STUD STANDARD BARREL 0.68"" TONGUE WIDTH BROWN W/ INSP WNDW BURNDY"

Open in new window


The only difference between the two is the "itemid" column present in the "select" clause (twice). I'm not understanding why selecting that column should cause the sorting to be backwards.

Thank you!
0
Comment
Question by:bbdesign
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
11 Comments
 
LVL 32

Expert Comment

by:Pawan Kumar
ID: 41834072
In one query you are sorting on itemid, description and in another you are doing only on description.

Thats why.
, DISTINCT will give you distinct records, order will be decided on the columns selected.

Innner row_number() -- does not matter.
0
 

Author Comment

by:bbdesign
ID: 41834085
I thought "order by description" would determine the order. I don't have "order by itemid,  description". How can I modify the second query so that it will return both itemid and description, but be sorted on description?
0
 
LVL 70

Expert Comment

by:Scott Pletcher
ID: 41834088
The ORDER BY in a ROW_NUMBER clause is used to assign values, it does not necessarily control the order in which rows are returned from the query.

An inner query order is never a guarantee of the order of rows for an outer query.

In short, if you want a specific order of rows returned by a query, you must ORDER BY in the outer query, such as:

select distinct
      itemid, description
from
      (select row_number() over (order by description) as rownum, itemid, description
            from tbl_product
            where (itemid='LUGS & H-TAPS : YAV2CLTC10FX' or itemid='LUGS & H-TAPS : YAV2CL2TC14E2FX')) as qryresults
order by description, itemid

Or even:

select distinct
      description
from
      (select row_number() over (order by description) as rownum, description
            from tbl_product
            where (itemid='LUGS & H-TAPS : YAV2CLTC10FX' or itemid='LUGS & H-TAPS : YAV2CL2TC14E2FX')) as qryresults
order by description

The distinct caused SQL to do a sort, which is why the rows were in order, but that was incidental/accidental, since an order by clause was not used.
0
Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

 
LVL 32

Accepted Solution

by:
Pawan Kumar earned 2000 total points
ID: 41834089
Here it is , You are not using row_num , why you have added it.

Sample example

select distinct
      itemid, description
from
      (select row_number() over (order by description) as rownum, itemid, description
            from tbl_product
            where (itemid='LUGS & H-TAPS : YAV2CLTC10FX' or itemid='LUGS & H-TAPS : YAV2CL2TC14E2FX')) as qryresults
ORDER BY description

select distinct
      description
from
      (select row_number() over (order by description) as rownum, description
            from tbl_product
            where (itemid='LUGS & H-TAPS : YAV2CLTC10FX' or itemid='LUGS & H-TAPS : YAV2CL2TC14E2FX')) as qryresults
ORDER BY description
0
 

Author Comment

by:bbdesign
ID: 41834110
I guess I didn't understand that before. It always seemed to work in the past, maybe I just got lucky. Anyway, thanks for your help!
0
 

Author Comment

by:bbdesign
ID: 41834112
I am using row_num in my final query, I was just trying to give you a stripped down version of my more complicated working query.
0
 
LVL 32

Expert Comment

by:Pawan Kumar
ID: 41834115
Great that you got it !! Excellent.
0
 

Author Comment

by:bbdesign
ID: 41838836
Sorry, I thought I had already assigned points.
0
 
LVL 70

Expert Comment

by:Scott Pletcher
ID: 41838897
Interesting points assignment.  Good luck with future qs.
0
 

Author Comment

by:bbdesign
ID: 41838926
Oh geez, I apologize! I did not realize there was more than one respondent. Somehow missed that.
0
 
LVL 70

Expert Comment

by:Scott Pletcher
ID: 41838943
Oh, ok, that makes sense.  Now maybe it's just me, but I thought my comments were more useful and on point (of course, maybe that's just me favoring my own answer :-) ).

[To be clear, I am not suggesting he just copied my answer, as the times are extremely close, and cross-posting is unavoidable on a site like this.]
0

Featured Post

Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

656 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question