SlideShare a Scribd company logo
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.
Most read
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.
Most read
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
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

Similar to Sorting Alpha Numeric Data in MySQL (20)

Distributed databases systems-3-2015.ppt
Distributed databases systems-3-2015.pptDistributed databases systems-3-2015.ppt
Distributed databases systems-3-2015.ppt
NaglaaAbdelhady
 
Databases Main Lesson 1
Databases Main Lesson 1Databases Main Lesson 1
Databases Main Lesson 1
high300
 
Ben Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptxBen Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptx
StephenEfange3
 
session_2 on database mysql databaseds from file to
session_2 on database mysql databaseds from file tosession_2 on database mysql databaseds from file to
session_2 on database mysql databaseds from file to
zmulani8
 
MySQL Cookbook 1st ed Edition Paul Dubois
MySQL Cookbook 1st ed Edition Paul DuboisMySQL Cookbook 1st ed Edition Paul Dubois
MySQL Cookbook 1st ed Edition Paul Dubois
uzielklael28
 
Sql1
Sql1Sql1
Sql1
5h4m4n
 
Session 2 - "MySQL Basics & Schema Design"
Session 2 - "MySQL Basics & Schema Design"Session 2 - "MySQL Basics & Schema Design"
Session 2 - "MySQL Basics & Schema Design"
LogaRajeshwaranKarth
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10
Syed Asrarali
 
Introduction to MySQL in PHP
Introduction to MySQL in PHPIntroduction to MySQL in PHP
Introduction to MySQL in PHP
hamsa nandhini
 
SQL python for beginners easy explanation with concepts and output .pptx
SQL python for beginners easy explanation with concepts and output .pptxSQL python for beginners easy explanation with concepts and output .pptx
SQL python for beginners easy explanation with concepts and output .pptx
harshitagrawal2608
 
2018 02 20_biological_databases_part2_v_upload
2018 02 20_biological_databases_part2_v_upload2018 02 20_biological_databases_part2_v_upload
2018 02 20_biological_databases_part2_v_upload
Prof. Wim Van Criekinge
 
MySQL Data types
MySQL Data typesMySQL Data types
MySQL Data types
Kaveen Prathibha Kumarasinghe
 
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
 
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
Lukas Eder
 
2017 biological databasespart2
2017 biological databasespart22017 biological databasespart2
2017 biological databasespart2
Prof. Wim Van Criekinge
 
012. SQL.pdf
012. SQL.pdf012. SQL.pdf
012. SQL.pdf
recosi2217
 
Introduction to Databases, SQL and querying.pptx
Introduction to Databases, SQL and querying.pptxIntroduction to Databases, SQL and querying.pptx
Introduction to Databases, SQL and querying.pptx
darthvidre
 
Distributed database
Distributed databaseDistributed database
Distributed database
NasIr Irshad
 
Databases Foundation General
Databases Foundation GeneralDatabases Foundation General
Databases Foundation General
mrcarty
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
jyothimuppasani1
 
Distributed databases systems-3-2015.ppt
Distributed databases systems-3-2015.pptDistributed databases systems-3-2015.ppt
Distributed databases systems-3-2015.ppt
NaglaaAbdelhady
 
Databases Main Lesson 1
Databases Main Lesson 1Databases Main Lesson 1
Databases Main Lesson 1
high300
 
Ben Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptxBen Finkel- Using the order by clause.pptx
Ben Finkel- Using the order by clause.pptx
StephenEfange3
 
session_2 on database mysql databaseds from file to
session_2 on database mysql databaseds from file tosession_2 on database mysql databaseds from file to
session_2 on database mysql databaseds from file to
zmulani8
 
MySQL Cookbook 1st ed Edition Paul Dubois
MySQL Cookbook 1st ed Edition Paul DuboisMySQL Cookbook 1st ed Edition Paul Dubois
MySQL Cookbook 1st ed Edition Paul Dubois
uzielklael28
 
Session 2 - "MySQL Basics & Schema Design"
Session 2 - "MySQL Basics & Schema Design"Session 2 - "MySQL Basics & Schema Design"
Session 2 - "MySQL Basics & Schema Design"
LogaRajeshwaranKarth
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10
Syed Asrarali
 
Introduction to MySQL in PHP
Introduction to MySQL in PHPIntroduction to MySQL in PHP
Introduction to MySQL in PHP
hamsa nandhini
 
SQL python for beginners easy explanation with concepts and output .pptx
SQL python for beginners easy explanation with concepts and output .pptxSQL python for beginners easy explanation with concepts and output .pptx
SQL python for beginners easy explanation with concepts and output .pptx
harshitagrawal2608
 
2018 02 20_biological_databases_part2_v_upload
2018 02 20_biological_databases_part2_v_upload2018 02 20_biological_databases_part2_v_upload
2018 02 20_biological_databases_part2_v_upload
Prof. Wim Van Criekinge
 
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
 
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
How Modern SQL Databases Come up with Algorithms that You Would Have Never Dr...
Lukas Eder
 
Introduction to Databases, SQL and querying.pptx
Introduction to Databases, SQL and querying.pptxIntroduction to Databases, SQL and querying.pptx
Introduction to Databases, SQL and querying.pptx
darthvidre
 
Distributed database
Distributed databaseDistributed database
Distributed database
NasIr Irshad
 
Databases Foundation General
Databases Foundation GeneralDatabases Foundation General
Databases Foundation General
mrcarty
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
jyothimuppasani1
 

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)

FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
FME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable InsightsFME for Climate Data: Turning Big Data into Actionable Insights
FME for Climate Data: Turning Big Data into Actionable Insights
Safe Software
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdfdp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadWondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Ad

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