Q
Problem solve Get help with specific problems with your technologies, process and projects.

# Sorting substrings of different lengths numerically

I have a table which contains IP addresses, such as 192.192.192.50. I want to display the table sorted by IP address (which is the primary key, a string), but unfortunately 192.192.192.19 will appear before 192.192.192.2!

The general solution to sorting strings of numbers of different lengths is to concatenate each of them onto the right end of a string of enough zeroes, and then take a substring of the desired length from the right.

For example, if we concatenate '123', '45', and '6' onto '00', we get '00123', '0045', and '006'. If we then take the rightmost 3 characters, we get '123', '045', and '006'. This is the strategy we shall apply to the IP numbers.

IP numbers contain four groups of digits, each of which can be between 1 and 3 digits long. We need a way to search a string or substring looking for the first occurrence of a specific character, in this case a period. We also need to pull substrings out, pad them with zeroes where necessary, and take the rightmost three characters to sort on. Each of the four groups can vary in size, so this will get tricky.

Standard SQL provides the SUBSTRING and POSITION functions, but these aren't supported by every database. For the following examples, I'll use Microsoft Access syntax, and the MID, INSTR, and RIGHT functions -- MID and RIGHT are special versions of SUBSTRING, and INSTR performs the POSITION function.

Let's get the first group of digits. We need a substring, starting at the very first character on the left, and going up to the last character before the first period --

```MID( IPno
, 1
, INSTR(IPno,'.')-1
)```

INSTR(IPno,'.') returns the position of the first period, which will be 2, 3, or 4, depending on whether the first group of digits is 1, 2, or 3 digits long. The MID function starts at the first character of IPno, and goes for a length equal to the position of the first period minus 1, i.e. up to the last character before the period.

Once we have pulled out the digits of the first group, we need to pad them on the left with zeroes and take the rightmost 3 characters --

```RIGHT( '00'
& MID( IPno
, 1
, INSTR(IPno,'.')-1
)
, 3
)```

From here on it gets messier. To pull out the second group of digits, we have to start one character to the right of the first period, search for the next period in that substring, and then pull out the second group like this --

```MID(IPno
,INSTR(IPno,'.')+1
,INSTR(MID(IPno
,INSTR(IPno,'.')+1)
,'.')-1)```

Notice that the length parameter, which determines how long a substring we're getting, is based on the position of the second period.

This response is continued.

#### Have a question for an expert?

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

#### Start the conversation

Send me notifications when other members comment.

## SearchDataManagement

• ### Databricks contributes Delta Lake to the Linux Foundation

Databricks has found a new home at the Linux Foundation for its open source Delta Lake data lake project, in a bid to help grow a...

• ### Apache Rya matures open source triple store database

Open source triple store database technology used by the U.S. Navy moves forward as a stable, mature project at the Apache ...

• ### PostgreSQL 12 boosts open source database performance

Widely used open source PostgreSQL database platform gets a major update providing users with new SQL query capabilities for JSON...

• ### SAS analytics platform aided by \$1 billion AI investment

The SAS suite of business intelligence products is quickly seeing results from the vendor's \$1 billion commitment to AI seven ...

• ### ThoughtSpot BI platform an early adopter of AI

Due to AI, ThoughtSpot's analytics tools have been accessible to citizen data scientists from the start, Andrew Yeung, the ...

• ### ThoughtSpot 6 advances AI power of BI platform

New augmented intelligence and machine learning tools, along with a new mobile app, highlight the release of the new update to ...

## SearchSAP

• ### How to improve the manufacturing process: 6 keys to tech success

AI, analytics, IoT and modern apps can serve important roles in today's manufacturing companies. Learn six steps that put these ...

New SAP co-CEOs Jennifer Morgan and Christian Klein must clarify SAP's products strategy, explain the experience economy and help...

• ### CEO of SAP Bill McDermott abruptly resigns

Bill McDermott, CEO of longtime ERP, CRM and BI software vendor SAP, resigned Thursday triggering a succession plan that promotes...

## SearchSQLServer

• ### SQL Server database design best practices and tips for DBAs

Good database design is a must to meet processing needs in SQL Server systems. In a webinar, consultant Koen Verbeeck offered ...

• ### SQL Server in Azure database choices and what they offer users

SQL Server databases can be moved to the Azure cloud in several different ways. Here's what you'll get from each of the options ...

• ### Using a LEFT OUTER JOIN vs. RIGHT OUTER JOIN in SQL

In this book excerpt, you'll learn LEFT OUTER JOIN vs. RIGHT OUTER JOIN techniques and find various examples for creating SQL ...

## TheServerSide.com

• ### Is Java slow? Compared to C++, it's faster than you think

If you find that Java is slower than other languages, such as C++, here's how to better compare the two and the major differences...

• ### Java video games, like Minecraft, keep the language popular

The next generation of Java developers can learn the ins and outs of the language through an unlikely source: video games such as...

• ### Pivotal, Microsoft team up to deliver Azure Spring Cloud

Azure Spring Cloud, jointly developed by Microsoft and Pivotal, lets Spring developers bring apps to the cloud without concern ...

## SearchDataCenter

• ### Improve server rack physical security with ISO standards

Safeguarding information access is essential to data center operations. With ISO Standard 27001 and the right locking mechanisms,...

• ### Essential private cloud migration steps

Executive buy-in, application evaluation and tool configuration are all important parts of cloud selection. With these steps, ...

• ### IBM quantum computers' usefulness in sight -- using binoculars

IBM's Bob Sutor discusses Big Blue's new quantum systems and computation center, the realities of quantum computing today and how...

## SearchContentManagement

• ### WebPurify launches profanity filter for memes and images

WebPurify has launched a beta of its Optical Character Recognition Profanity Filter Service to identify and block profane images ...

• ### Digital asset management benefits the future of work

Digital asset management promises to transform digital work, making it easier to tag documents, analyze video and provide image ...

• ### Box cloud content management adds PDF tools, boosts security

Box partners with Adobe in releasing a new set of PDF tools that can be used within Box's content management cloud to enable ...

## SearchHRSoftware

• ### A backlash emerges over automated interviewing

Illinois may have adopted the nation's first automated hiring law, which will take effect Jan 1. The law is likely to become a ...

• ### Get smarter about HR data security

HR deals with mountains of sensitive employee data and must do a better job of protecting that information. Here's a look at how ...

• ### Walmart, FedEx make case for VR training

The payback from virtual training may be improved retention and shorter training times. An hour-long training period can be ...

Close