Published on

October 14, 2012

Understanding Alphanumeric Sorting in SQL Server

When working with alphanumeric data in SQL Server, sorting the data based on the numeric part can be a challenge. In this blog post, we will explore a solution to this problem using the PATINDEX function.

Let’s start by considering a scenario where we have a table with a column containing alphanumeric data. The data always begins with an integer followed by a string. The business requirement is to order the data based on the numeric part of the alphanumeric data.

However, when we use the ORDER BY clause, the result is not produced as expected. Let’s take a look at an example:

USE tempdb
GO
CREATE TABLE MyTable (ID INT, Col1 VARCHAR(100))
GO
INSERT INTO MyTable (ID, Col1)
SELECT 1, '1one'
UNION ALL
SELECT 2, '11eleven'
UNION ALL
SELECT 3, '2two'
UNION ALL
SELECT 4, '22twentytwo'
UNION ALL
SELECT 5, '111oneeleven'
GO

-- Select Data
SELECT *
FROM MyTable
GO

-- Select Data
SELECT *
FROM MyTable
ORDER BY Col1
GO

The result of the table is not as expected. We need the result to be ordered based on the numeric part of the alphanumeric data.

To solve this problem, we can use the PATINDEX function. PATINDEX allows us to identify the length of the numeric part in the alphanumeric string. We can then use the LEFT function to extract the numeric portion from the string and order the data accordingly.

Here is an example of how we can use PATINDEX:

-- Use of PATINDEX
SELECT ID,
LEFT(Col1, PATINDEX('%[^0-9]%', Col1)-1) AS 'Numeric Character',
Col1 AS 'Original Character'
FROM MyTable
ORDER BY LEFT(Col1, PATINDEX('%[^0-9]%', Col1)-1)
GO

By using PATINDEX and LEFT functions, we are able to extract the numeric part of the alphanumeric data and order the result set accordingly.

Once we have achieved the desired result, we can easily clean up the script by dropping the temporary table:

DROP TABLE MyTable
GO

In conclusion, sorting alphanumeric data based on the numeric part can be achieved using the PATINDEX and LEFT functions in SQL Server. This solution provides a way to order the data as per the business requirement.

Do you have any suggestions for a better solution? Additionally, any suggestions for changing the title of this blog post?

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.