Ordinal position in a table refers to the position of the column in a table. It can also point to the column number in a SELECT statement
Consider the following set of data
create table testing(id int, names varchar(100))
insert into testing(id,names)
select 18,'Charles' union all
select 20,'Ashok' union all
select 19,'Birla' ;
The select statement
select * from testing order by 1
returns the following result
The number 1 in Order by clause refers to the first column listed in the SELECT statement so the result is ordered by column ID
The select statement
select * from testing order by 2
returns the following result
As you see the resultset is ordered by second column NAMES
But if you use a CASE expression and a number, it will behave differently. Suppose you want to keep the name Birla in first row and sort other rows by alphabetical order of remaining names, you can use the following statement
select * from testing order by case when names='Birla' then 1 else 2 end,names
The result is
In the above statement, number 1 and 2 are literal values and do not refer any columns. If the name is Birla, a value 1 is assigned otherwise 2 is assigned and ordered by these values first, then ordered by names.
No comments:
Post a Comment