SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)
Ankit Dubey
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1
rohassanie
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
TharuniDiddekunta
 
Ch2 Liang
Ch2 LiangCh2 Liang
Ch2 Liang
Dorothea Chaffin
 
Structured analysis and structured design
Structured analysis  and structured designStructured analysis  and structured design
Structured analysis and structured design
Sudeep Singh
 
Core java
Core java Core java
Core java
Ravi varma
 
Google File System
Google File SystemGoogle File System
Google File System
guest2cb4689
 
GUI Testing
GUI TestingGUI Testing
GUI Testing
BugRaptors
 
Jvm Architecture
Jvm ArchitectureJvm Architecture
Jvm Architecture
ThirupathiReddy Vajjala
 
Calculator Program in C#.NET
Calculator Program in C#.NET Calculator Program in C#.NET
Calculator Program in C#.NET
Dhairya Joshi
 
Database testing
Database testingDatabase testing
Database testing
Hrushikesh Wakhle
 
decision table training session
decision table training sessiondecision table training session
decision table training session
Sabik T S
 
Task Scheduling Using Firefly algorithm with cloudsim
Task Scheduling Using Firefly algorithm with cloudsimTask Scheduling Using Firefly algorithm with cloudsim
Task Scheduling Using Firefly algorithm with cloudsim
AqilIzzuddin
 
Sql
SqlSql
Sql
Aman Lalpuria
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Arrays in JAVA.ppt
Arrays in JAVA.pptArrays in JAVA.ppt
Arrays in JAVA.ppt
SeethaDinesh
 
Software Testing Techniques: An Overview
Software Testing Techniques: An Overview Software Testing Techniques: An Overview
Software Testing Techniques: An Overview
QA InfoTech
 
Software Testing Fundamentals
Software Testing FundamentalsSoftware Testing Fundamentals
Software Testing Fundamentals
Chankey Pathak
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
Wings Interactive
 
White box ppt
White box pptWhite box ppt
White box ppt
Chintakunta Hariteja
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)
Ankit Dubey
 
Chapter 3 part 1
Chapter 3 part 1Chapter 3 part 1
Chapter 3 part 1
rohassanie
 
Structured analysis and structured design
Structured analysis  and structured designStructured analysis  and structured design
Structured analysis and structured design
Sudeep Singh
 
Google File System
Google File SystemGoogle File System
Google File System
guest2cb4689
 
Calculator Program in C#.NET
Calculator Program in C#.NET Calculator Program in C#.NET
Calculator Program in C#.NET
Dhairya Joshi
 
decision table training session
decision table training sessiondecision table training session
decision table training session
Sabik T S
 
Task Scheduling Using Firefly algorithm with cloudsim
Task Scheduling Using Firefly algorithm with cloudsimTask Scheduling Using Firefly algorithm with cloudsim
Task Scheduling Using Firefly algorithm with cloudsim
AqilIzzuddin
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 
Arrays in JAVA.ppt
Arrays in JAVA.pptArrays in JAVA.ppt
Arrays in JAVA.ppt
SeethaDinesh
 
Software Testing Techniques: An Overview
Software Testing Techniques: An Overview Software Testing Techniques: An Overview
Software Testing Techniques: An Overview
QA InfoTech
 
Software Testing Fundamentals
Software Testing FundamentalsSoftware Testing Fundamentals
Software Testing Fundamentals
Chankey Pathak
 

Similar to Sorting Alpha Numeric Data in MySQL (20)

DBMS.pptx
DBMS.pptxDBMS.pptx
DBMS.pptx
Geetha Kannan
 
Sql wksht-2
Sql wksht-2Sql wksht-2
Sql wksht-2
Mukesh Tekwani
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the Indices
Kellyn Pot'Vin-Gorman
 
SQL on Linux and its uses and application.pdf
SQL on Linux and its uses and application.pdfSQL on Linux and its uses and application.pdf
SQL on Linux and its uses and application.pdf
bhaveshsethi456
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
Swapnali Pawar
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
Stewart Rogers
 
Database
DatabaseDatabase
Database
marwa_ma
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
Vineeta Garg
 
Integrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdfIntegrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdf
Saikrishna492522
 
Sql
SqlSql
Sql
jyothislides
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
Alessandro Baratella
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
Saeid Zebardast
 
Select To Order By
Select  To  Order BySelect  To  Order By
Select To Order By
Krizia Capacio
 
Database
Database Database
Database
NoorullahZamindar
 
Data Warehouse and Business Intelligence - Recipe 3
Data Warehouse and Business Intelligence - Recipe 3Data Warehouse and Business Intelligence - Recipe 3
Data Warehouse and Business Intelligence - Recipe 3
Massimo Cenci
 
Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)  Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)
MuhammadWaheed44
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
webhostingguy
 
MAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptxMAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptx
Siva Krishna Prasad
 
mysqlHiep.ppt
mysqlHiep.pptmysqlHiep.ppt
mysqlHiep.ppt
webhostingguy
 
Oracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the IndicesOracle vs. SQL Server- War of the Indices
Oracle vs. SQL Server- War of the Indices
Kellyn Pot'Vin-Gorman
 
SQL on Linux and its uses and application.pdf
SQL on Linux and its uses and application.pdfSQL on Linux and its uses and application.pdf
SQL on Linux and its uses and application.pdf
bhaveshsethi456
 
Adbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queriesAdbms 21 sql 99 schema definition constraints and queries
Adbms 21 sql 99 schema definition constraints and queries
Vaibhav Khanna
 
Database Management System 1
Database Management System 1Database Management System 1
Database Management System 1
Swapnali Pawar
 
Structured query language functions
Structured query language functionsStructured query language functions
Structured query language functions
Vineeta Garg
 
Integrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdfIntegrity constraint fundamentals of dbms.pdf
Integrity constraint fundamentals of dbms.pdf
Saikrishna492522
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
Alessandro Baratella
 
Data Warehouse and Business Intelligence - Recipe 3
Data Warehouse and Business Intelligence - Recipe 3Data Warehouse and Business Intelligence - Recipe 3
Data Warehouse and Business Intelligence - Recipe 3
Massimo Cenci
 
Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)  Data Manipulation(DML) and Transaction Control (TCL)
Data Manipulation(DML) and Transaction Control (TCL)
MuhammadWaheed44
 
Ad

More from Abdul Rahman Sherzad (20)

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

Recently uploaded (20)

FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
Lionel Briand
 
Odoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education ProcessOdoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education Process
iVenture Team LLP
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
FlakyFix: Using Large Language Models for Predicting Flaky Test Fix Categorie...
Lionel Briand
 
Odoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education ProcessOdoo ERP for Education Management to Streamline Your Education Process
Odoo ERP for Education Management to Streamline Your Education Process
iVenture Team LLP
 
Implementing promises with typescripts, step by step
Implementing promises with typescripts, step by stepImplementing promises with typescripts, step by step
Implementing promises with typescripts, step by step
Ran Wahle
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Creating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdfCreating Automated Tests with AI - Cory House - Applitools.pdf
Creating Automated Tests with AI - Cory House - Applitools.pdf
Applitools
 
Foundation Models for Time Series : A Survey
Foundation Models for Time Series : A SurveyFoundation Models for Time Series : A Survey
Foundation Models for Time Series : A Survey
jayanthkalyanam1
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Innovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at allInnovative Approaches to Software Dev no good at all
Innovative Approaches to Software Dev no good at all
ayeshakanwal75
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 

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