Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order by sort wrong records

I have a table with `Subscription' , when I sort recordes with order by I getting wrong result . My Result Does not sort , by MyColumn

my query is :

Select Subscriptioncode from Subscription order by Subscriptioncode desc

my Result like as :

90
80
8
700
73
634
100

Why getting this Result ?

In SubscriptionCode some Row is Null.

100

like image 773
Psar Tak Avatar asked May 11 '15 05:05

Psar Tak


People also ask

Does order matter in ORDER BY SQL?

The order of columns/expressions showing up does matter. It orders by the first one as specified, then orders that set by the next one, then by the next. The result is different than if you were to reverse the order in which the columns are ordered.

Can ORDER BY sort based on multiple columns in SQL?

To sort the records in descending order, use the DESC keyword. Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first.

What is ORDER BY 2 in SQL?

customers ORDER BY 1, 2; In this example, 1 means the first_name column and 2 means the last_name column. Using the ordinal positions of columns in the ORDER BY clause is considered as bad programming practice for a couple of reasons.

Which clause is used to arrange data sorted order?

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.


2 Answers

Your column SubscriptionCode is currently not a numeric type, and it is likely a text type instead. However, you can CAST this column to an INT type and then the ordering should work with no problem:

Select Subscriptioncode from Subscription
order by CAST(Subscriptioncode AS INT) desc
like image 149
Tim Biegeleisen Avatar answered Sep 30 '22 16:09

Tim Biegeleisen


You should declare Subscriptioncode column Datatype As INT

Example

create table Subscription(
Subscriptioncode  int)

insert into Subscription  values('90')
insert into Subscription  values('80')
insert into Subscription  values('8')
insert into Subscription  values('700')
insert into Subscription  values('73')
insert into Subscription  values('634')
insert into Subscription  values('100')


Select Subscriptioncode from Subscription order by Subscriptioncode desc

OUTPUT:

Subscriptioncode
700
634
100
90
80
73
8

Note:

As you are declaring datatype other than INT Ex:Varchar

-->It will sort values as like Sorting Alphabetical order i.e)abc

that's y you are getting wrong results.so choose correct Datatype.

like image 31
Hell Boy Avatar answered Sep 30 '22 17:09

Hell Boy