
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
MySQL ORDER BY with CASE WHEN
For this, you can use the ORDER BY CASE statement. Let us first create a table −
mysql> create table DemoTable order by with vas Color varchar(100) ); Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Red'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Green'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Blue'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Yellow'); Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+ | Color | +--------+ | Red | | Green | | Blue | | Yellow | +--------+ 4 rows in set (0.00 sec)
Here is the query to order by with CASE WHEN −
mysql> select *from DemoTable order by case Color when 'Blue' then 10 when 'Green' then 20 when 'Yellow' then 30 else 100 end ;
This will produce the following output −
+--------+ | Color | +--------+ | Blue | | Green | | Yellow | | Red | +--------+ 4 rows in set (0.00 sec)
- Related Articles
- MySQL Order by with case?
- MySQL order by field using CASE Statement
- MySQL IF/WHEN/ELSE/OR with ORDER BY FIELD
- Implement MySQL CASE statement with WHEN clause
- MySQL Mass Update with CASE WHEN/ THEN/ ELSE?
- Perform count with CASE WHEN statement in MySQL?
- How can we sort a query using ORDER BY CASE WHEN REGEXP?
- MySQL ORDER BY CASE to display special character in the beginning
- MySQL ORDER BY strings with underscore?
- MySQL order by string with numbers?
- MySQL ORDER BY with EXPLAIN command
- Alternative to MySQL CASE WHEN in MySQL
- MySQL ORDER BY with custom field value
- How to sort by value with MySQL ORDER BY?
- MySQL CASE WHEN with SELECT to display odd and even ids?

Advertisements