SlideShare a Scribd company logo
5
Most read
12
Most read
17
Most read
Methods to Sort Alpha-
numeric Data in MySQL
Abdul Rahman Sherzad
Lecturer at Computer Science faculty
Herat University, Afghanistan
ORDER BY Keyword
• In SQL, the ORDER BY keyword is used to sort the result-set in
ascending (ASC) or descending (DESC) order by some specified
column/columns.
• It works great for most of the cases.
• However, for alphanumeric data, it may not return the result-set
that you will be expecting.
• This presentation explains how this can be addressed using
different techniques.
2
Scenario I: Table Structure and Test Data
Table Structure
CREATE TABLE warnings
(
id INT NOT NULL
PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
due VARCHAR(20)
);
Test Data
INSERT INTO warnings
(name, due) VALUES
('Aaaaa', '10 days'),
('Baaaa', '1 days'),
('Ccccc', '2 days'),
('Ddddd', '12 days'),
('Eeeee', '20 days'),
('Fffff', '2 days'),
('Ggggg', '5 days'),
('Hhhhh', '3 days');
3
Scenario I: The Problem
• Assume there is a table named 'warnings' with the following
'due' and 'name' columns.
• The data for 'due' column is alphanumeric.
• A report is needed to display the data sorted by the 'due'
column. But, the result of the following query is not as it
is expected:
SELECT due, name FROM warnings
ORDER BY due ASC;
4
Solution #1: Identity Elements
5
• The number '0' in addition, and '1' in multiplication are
identity elements. An identity element is a number that
combines with other elements in a mathematical equation
but does not change them.
SELECT due, name FROM warnings
ORDER BY due + 0 ASC;
OR the following
SELECT due, name FROM warnings
ORDER BY due * 1 ASC;
Solution #2: CAST() function
6
• The CAST() function converts a value from
one datatype to another datatype.
• Using cast() function is another method to
address the mentioned problem as follow:
SELECT due, name
FROM warnings
ORDER BY CAST(due AS SIGNED) ASC;
Solution #3: Natural Sorting
7
• It is simple enough to accomplish natural
sorting in MySQL:
• First sort by length of the column,
• Then sort by the original column value.
SELECT due, name
FROM warnings
ORDER BY LENGTH(due) ASC, due ASC;
• NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
This is not end of the story!
• The above Solution #1 and Solution #2 works only with alpha-numeric data
starts with numbers.
• The Solution #1 and Solution #2 do not work with alpha-numeric data ends
with numbers!
8
Scenario II: Table Structure and Test Data
Table Structure
CREATE TABLE tests
(
id INT NOT NULL
PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
score INT
);
Test Data
INSERT INTO tests
(name, score) VALUES
('Test 1', 10),
('Test 10', 5),
('Test 3', 10),
('Test 2', 4),
('Test 15', 5),
('Test 18', 10),
('Test 20', 5),
('Test 9', 10);
9
Scenario II: The Problem
10
• Assume there is a table named 'tests' with the
following two columns 'name' and 'score'.
• The data in the column 'name' are alpha-numeric
• but the numbers are at the end of the string.
• With such a structure, the above-mentioned
Solution #1 and Solution #2 do not work as
illustrated on next slide 
Solution #1 and Solution #2: Issue
11
• The following queries do not sort the result-sets
as it is expected:
• Solution #1:
SELECT name, score FROM tests
ORDER BY name + 0 ASC;
• Solution #2:
SELECT name, score
FROM tests
ORDER BY CAST(name AS UNSIGNED);
Solution #3: Natural Sorting
12
• The natural sorting works properly with
alpha-numeric data whether the numbers
are at the beginning, or at the end of the
string, as illustrated on this slide.
SELECT name, score
FROM tests
ORDER BY LENGTH(name) ASC, name ASC;
What about the following Scenario?
• What about mixture of data (a very rare case)
• alpha-numeric data with numbers at the beginning of the
string
• alpha-numeric data with numbers at the end of the string
• Only numeric data
• Only alphabetic data
13
Scenario III: Table Structure and Test Data
Table Structure
CREATE TABLE tests (
test VARCHAR(20) NOT NULL
);
Test Data
INSERT INTO tests
(test) VALUES
('A1'), ('A10'), ('A2’),
('1 day'), ('10 day'), ('2 day’),
('10'), ('1'), ('2’),
('Sherzad’),
('Abdul Rahman');
14
Scenario III: ORDER BY Keyword
15
SELECT test
FROM tests
ORDER BY test ASC;
NOTE: The ASC keyword can be omitted, as
it is the DEFAULT.
Scenario III: Identity Elements and
CAST() function
16
• Casting using Identity Elements
SELECT test FROM tests
ORDER BY test + 0 ASC;
• CAST() function
SELECT test FROM tests
ORDER BY CAST(test AS UNSIGNED) ASC;
NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
Scenario III: Identity Elements and
CAST() function
17
• To sort the data based on the numeric
values, simply use the following queries:
SELECT test FROM tests
ORDER BY test + 0 ASC, test ASC;
• OR
SELECT test FROM tests
ORDER BY CAST(test AS UNSIGNED) ASC,
test ASC;
NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
Scenario III: Natural Sorting
18
SELECT test
FROM tests
ORDER BY LENGTH(test) ASC,
test ASC;
NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
Summary
In most cases including alpha-numeric data
with numbers either at the beginning or at the
end of the string Natural Sorting method
works pretty well.
•First sort by length of the column,
•Then sort by the original column value.
In case there are different variations of data
in same column (which is very rare), different
methods can be picked e.g.
• The data can be sorted based on their numeric values as
illustrated on slide 17,
• The data can be sorted using Natural Sorting method,
• Or combination of other methods
19
1
2
20

More Related Content

PPT
My8clst
PDF
Java Serialization
PPTX
Kruskal's algorithm
PPTX
Mdx 2nddraft
PPTX
Data Analysis with Python Pandas
PPTX
Regular Expression (Regex) Fundamentals
PPTX
Regular expressions
PPT
Regular Expressions
My8clst
Java Serialization
Kruskal's algorithm
Mdx 2nddraft
Data Analysis with Python Pandas
Regular Expression (Regex) Fundamentals
Regular expressions
Regular Expressions

What's hot (20)

PDF
PDF
Data Analytics with Pandas and Numpy - Python
PPTX
Chapter 1 swings
PPTX
Introduction to JUnit
PDF
Java Programming Question paper Aurangabad MMS
PDF
موقع ملزمتي - مراجعة ليلة الامتحان جبر للشهادة الإعدادية الترم الثانى
PPSX
Collections - Lists, Sets
PPTX
Graph Algorithms: Breadth-First Search (BFS)
PDF
Streaming Operational Data with MariaDB MaxScale
PDF
Deploying Machine Learning Models to Production
PPTX
Python Scipy Numpy
PDF
Java Fundamentals
PPTX
Static keyword ppt
PDF
MySQL partitions tutorial
PDF
Uncertainty Estimation in Deep Learning
PPTX
Regular Expression
PPTX
11. java methods
PDF
Pandas,scipy,numpy cheatsheet
PDF
04 curso poo Herencia
PPT
Types of exceptions
Data Analytics with Pandas and Numpy - Python
Chapter 1 swings
Introduction to JUnit
Java Programming Question paper Aurangabad MMS
موقع ملزمتي - مراجعة ليلة الامتحان جبر للشهادة الإعدادية الترم الثانى
Collections - Lists, Sets
Graph Algorithms: Breadth-First Search (BFS)
Streaming Operational Data with MariaDB MaxScale
Deploying Machine Learning Models to Production
Python Scipy Numpy
Java Fundamentals
Static keyword ppt
MySQL partitions tutorial
Uncertainty Estimation in Deep Learning
Regular Expression
11. java methods
Pandas,scipy,numpy cheatsheet
04 curso poo Herencia
Types of exceptions
Ad

Similar to Sorting Alpha Numeric Data in MySQL (20)

PPTX
DBMS.pptx
PDF
Sql wksht-2
POTX
Oracle vs. SQL Server- War of the Indices
PDF
SQL on Linux and its uses and application.pdf
PPTX
Adbms 21 sql 99 schema definition constraints and queries
PDF
Database Management System 1
PPTX
Arrays with the help of Computer Programming
PDF
SQL Overview
PPTX
Presentation on SQL Basics to Advance in DBMS
PPTX
Database
PPTX
Structured query language functions
PDF
Integrity constraint fundamentals of dbms.pdf
PPT
PDF
Database development coding standards
PDF
MySQL for beginners
PPT
Select To Order By
PPTX
PPTX
Data Warehouse and Business Intelligence - Recipe 3
PDF
Data Manipulation(DML) and Transaction Control (TCL)
PPT
MySql slides (ppt)
DBMS.pptx
Sql wksht-2
Oracle vs. SQL Server- War of the Indices
SQL on Linux and its uses and application.pdf
Adbms 21 sql 99 schema definition constraints and queries
Database Management System 1
Arrays with the help of Computer Programming
SQL Overview
Presentation on SQL Basics to Advance in DBMS
Database
Structured query language functions
Integrity constraint fundamentals of dbms.pdf
Database development coding standards
MySQL for beginners
Select To Order By
Data Warehouse and Business Intelligence - Recipe 3
Data Manipulation(DML) and Transaction Control (TCL)
MySql slides (ppt)
Ad

More from Abdul Rahman Sherzad (20)

PDF
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
PDF
PHP Unicode Input Validation Snippets
PDF
Iterations and Recursions
PDF
PHP Variable variables Examples
PDF
Cross Join Example and Applications
PDF
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
PDF
Web Application Security and Awareness
PDF
Database Automation with MySQL Triggers and Event Schedulers
PDF
Mobile Score Notification System
PDF
Herat Innovation Lab 2015
PDF
Evaluation of Existing Web Structure of Afghan Universities
PDF
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PDF
Java Applet and Graphics
PDF
Fundamentals of Database Systems Questions and Answers
PDF
Everything about Database JOINS and Relationships
PDF
Create Splash Screen with Java Step by Step
PDF
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
PDF
Web Design and Development Life Cycle and Technologies
PDF
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
PDF
Java Unicode with Live GUI Examples
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
PHP Unicode Input Validation Snippets
Iterations and Recursions
PHP Variable variables Examples
Cross Join Example and Applications
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Web Application Security and Awareness
Database Automation with MySQL Triggers and Event Schedulers
Mobile Score Notification System
Herat Innovation Lab 2015
Evaluation of Existing Web Structure of Afghan Universities
PHP Basic and Fundamental Questions and Answers with Detail Explanation
Java Applet and Graphics
Fundamentals of Database Systems Questions and Answers
Everything about Database JOINS and Relationships
Create Splash Screen with Java Step by Step
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Web Design and Development Life Cycle and Technologies
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Unicode with Live GUI Examples

Recently uploaded (20)

PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Online Work Permit System for Fast Permit Processing
PDF
System and Network Administration Chapter 2
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Digital Strategies for Manufacturing Companies
PPTX
history of c programming in notes for students .pptx
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
top salesforce developer skills in 2025.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Online Work Permit System for Fast Permit Processing
System and Network Administration Chapter 2
Understanding Forklifts - TECH EHS Solution
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
How to Migrate SBCGlobal Email to Yahoo Easily
How Creative Agencies Leverage Project Management Software.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Operating system designcfffgfgggggggvggggggggg
2025 Textile ERP Trends: SAP, Odoo & Oracle
Digital Strategies for Manufacturing Companies
history of c programming in notes for students .pptx
How to Choose the Right IT Partner for Your Business in Malaysia
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
ManageIQ - Sprint 268 Review - Slide Deck
top salesforce developer skills in 2025.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Upgrade and Innovation Strategies for SAP ERP Customers
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus

Sorting Alpha Numeric Data in MySQL

  • 1. Methods to Sort Alpha- numeric Data in MySQL Abdul Rahman Sherzad Lecturer at Computer Science faculty Herat University, Afghanistan
  • 2. ORDER BY Keyword • In SQL, the ORDER BY keyword is used to sort the result-set in ascending (ASC) or descending (DESC) order by some specified column/columns. • It works great for most of the cases. • However, for alphanumeric data, it may not return the result-set that you will be expecting. • This presentation explains how this can be addressed using different techniques. 2
  • 3. Scenario I: Table Structure and Test Data Table Structure CREATE TABLE warnings ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, due VARCHAR(20) ); Test Data INSERT INTO warnings (name, due) VALUES ('Aaaaa', '10 days'), ('Baaaa', '1 days'), ('Ccccc', '2 days'), ('Ddddd', '12 days'), ('Eeeee', '20 days'), ('Fffff', '2 days'), ('Ggggg', '5 days'), ('Hhhhh', '3 days'); 3
  • 4. Scenario I: The Problem • Assume there is a table named 'warnings' with the following 'due' and 'name' columns. • The data for 'due' column is alphanumeric. • A report is needed to display the data sorted by the 'due' column. But, the result of the following query is not as it is expected: SELECT due, name FROM warnings ORDER BY due ASC; 4
  • 5. Solution #1: Identity Elements 5 • The number '0' in addition, and '1' in multiplication are identity elements. An identity element is a number that combines with other elements in a mathematical equation but does not change them. SELECT due, name FROM warnings ORDER BY due + 0 ASC; OR the following SELECT due, name FROM warnings ORDER BY due * 1 ASC;
  • 6. Solution #2: CAST() function 6 • The CAST() function converts a value from one datatype to another datatype. • Using cast() function is another method to address the mentioned problem as follow: SELECT due, name FROM warnings ORDER BY CAST(due AS SIGNED) ASC;
  • 7. Solution #3: Natural Sorting 7 • It is simple enough to accomplish natural sorting in MySQL: • First sort by length of the column, • Then sort by the original column value. SELECT due, name FROM warnings ORDER BY LENGTH(due) ASC, due ASC; • NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
  • 8. This is not end of the story! • The above Solution #1 and Solution #2 works only with alpha-numeric data starts with numbers. • The Solution #1 and Solution #2 do not work with alpha-numeric data ends with numbers! 8
  • 9. Scenario II: Table Structure and Test Data Table Structure CREATE TABLE tests ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) NOT NULL, score INT ); Test Data INSERT INTO tests (name, score) VALUES ('Test 1', 10), ('Test 10', 5), ('Test 3', 10), ('Test 2', 4), ('Test 15', 5), ('Test 18', 10), ('Test 20', 5), ('Test 9', 10); 9
  • 10. Scenario II: The Problem 10 • Assume there is a table named 'tests' with the following two columns 'name' and 'score'. • The data in the column 'name' are alpha-numeric • but the numbers are at the end of the string. • With such a structure, the above-mentioned Solution #1 and Solution #2 do not work as illustrated on next slide 
  • 11. Solution #1 and Solution #2: Issue 11 • The following queries do not sort the result-sets as it is expected: • Solution #1: SELECT name, score FROM tests ORDER BY name + 0 ASC; • Solution #2: SELECT name, score FROM tests ORDER BY CAST(name AS UNSIGNED);
  • 12. Solution #3: Natural Sorting 12 • The natural sorting works properly with alpha-numeric data whether the numbers are at the beginning, or at the end of the string, as illustrated on this slide. SELECT name, score FROM tests ORDER BY LENGTH(name) ASC, name ASC;
  • 13. What about the following Scenario? • What about mixture of data (a very rare case) • alpha-numeric data with numbers at the beginning of the string • alpha-numeric data with numbers at the end of the string • Only numeric data • Only alphabetic data 13
  • 14. Scenario III: Table Structure and Test Data Table Structure CREATE TABLE tests ( test VARCHAR(20) NOT NULL ); Test Data INSERT INTO tests (test) VALUES ('A1'), ('A10'), ('A2’), ('1 day'), ('10 day'), ('2 day’), ('10'), ('1'), ('2’), ('Sherzad’), ('Abdul Rahman'); 14
  • 15. Scenario III: ORDER BY Keyword 15 SELECT test FROM tests ORDER BY test ASC; NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
  • 16. Scenario III: Identity Elements and CAST() function 16 • Casting using Identity Elements SELECT test FROM tests ORDER BY test + 0 ASC; • CAST() function SELECT test FROM tests ORDER BY CAST(test AS UNSIGNED) ASC; NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
  • 17. Scenario III: Identity Elements and CAST() function 17 • To sort the data based on the numeric values, simply use the following queries: SELECT test FROM tests ORDER BY test + 0 ASC, test ASC; • OR SELECT test FROM tests ORDER BY CAST(test AS UNSIGNED) ASC, test ASC; NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
  • 18. Scenario III: Natural Sorting 18 SELECT test FROM tests ORDER BY LENGTH(test) ASC, test ASC; NOTE: The ASC keyword can be omitted, as it is the DEFAULT.
  • 19. Summary In most cases including alpha-numeric data with numbers either at the beginning or at the end of the string Natural Sorting method works pretty well. •First sort by length of the column, •Then sort by the original column value. In case there are different variations of data in same column (which is very rare), different methods can be picked e.g. • The data can be sorted based on their numeric values as illustrated on slide 17, • The data can be sorted using Natural Sorting method, • Or combination of other methods 19 1 2
  • 20. 20