
- 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 field using CASE Statement
To order by field, use CASE statement. Let us first create a table −
mysql> create table DemoTable(StudentId varchar(100)); Query OK, 0 rows affected (1.69 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('STU-980'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values('STU-1029'); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable values('STU-189'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('STU-890'); Query OK, 1 row affected (0.38 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+ | StudentId | +-----------+ | STU-980 | | STU-1029 | | STU-189 | | STU-890 | +-----------+ 4 rows in set (0.00 sec)
Following is the query to MySQL order by field −
mysql> select *from DemoTable order by case WHEN StudentId = 'STU-890' THEN 1 WHEN StudentId = 'STU-1029' THEN 2 WHEN StudentId = 'STU-980' THEN 3 WHEN StudentId = 'STU-189' THEN 4 end;
This will produce the following output −
+-----------+ | StudentId | +-----------+ | STU-890 | | STU-1029 | | STU-980 | | STU-189 | +-----------+ 4 rows in set (0.08 sec)
- Related Articles
- MySQL Order by with case?
- MySQL ORDER BY with CASE WHEN
- MySQL ORDER BY with custom field value
- ORDER BY specific field value first in MySQL
- MySQL case statement inside a select statement?
- Simulating MySQL's ORDER BY FIELD() in PostgreSQL?
- MySQL ORDER BY Date field not in date format?
- MySQL IF/WHEN/ELSE/OR with ORDER BY FIELD
- How to use ORDER BY field and sort by id in a single MySQL field?
- How to use MySQL CASE statement while using UPDATE Query?
- MySQL ORDER BY CASE to display special character in the beginning
- How to ORDER BY FIELD with GROUP BY in a single MySQL query?
- Why should we use MySQL CASE Statement?
- Implement MySQL CASE statement with WHEN clause
- Change value from 1 to Y in MySQL Select Statement using CASE?

Advertisements