SQL tricky Question - How to sort alphanumeric data?

 Here are the SQLs related to this tutorial.

Video tutorial -

SQL-alphanumeric sorting


Create SQL

CREATE TABLE [dbo].[ID_Key]

(

[ID] [nvarchar](100) NULL


Insert SQL


INSERT INTO [dbo].[ID_Key] ([ID]) VALUES ('1');

INSERT INTO [dbo].[ID_Key] ([ID]) VALUES ('2');

INSERT INTO [dbo].[ID_Key] ([ID]) VALUES ('21');

INSERT INTO [dbo].[ID_Key] ([ID]) VALUES ('10');

INSERT INTO [dbo].[ID_Key] ([ID]) VALUES ('Alpha11');

INSERT INTO [dbo].[ID_Key] ([ID]) VALUES ('Alpha2');

INSERT INTO [dbo].[ID_Key] ([ID]) VALUES ('210');

INSERT INTO [dbo].[ID_Key] ([ID]) VALUES ('Alpha1');


SQL Query

Select ID from ID_Key 

Order by LEFT(ID, Patindex('%[0-9]%', ID) -1),

Convert(Int,Substring(ID, Patindex('%[0-9]%', ID) , Len(ID)))


Post a Comment

Previous Post Next Post

Contact Form