
- 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
How to order by the highest value from two columns in MySQL?
Let us first create a table −
mysql> create table DemoTable834( Value1 int, Value2 int ); Query OK, 0 rows affected (1.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable834 values(10,20); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable834 values(40,50); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable834 values(20,24); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable834 values(30,10); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable834;
This will produce the following output −
+--------+--------+ | Value1 | Value2 | +--------+--------+ | 10 | 20 | | 40 | 50 | | 20 | 24 | | 30 | 10 | +--------+--------+ 4 rows in set (0.00 sec)
Following is the query to order by the highest value from two columns using GREATEST() −
mysql> select *from DemoTable834 order by greatest(Value1,Value2) DESC;
This will produce the following output −
+--------+--------+ | Value1 | Value2 | +--------+--------+ | 40 | 50 | | 30 | 10 | | 20 | 24 | | 10 | 20 | +--------+--------+ 4 rows in set (0.00 sec)
- Related Articles
- MySQL order by from highest to lowest value?
- Get the highest score value from a single column and the greatest from two columns in MySQL
- Order a MySQL table by two columns?
- How to order MySQL rows by multiple columns?
- Display two different columns from two different tables with ORDER BY?
- How to sort by value with MySQL ORDER BY?
- Order by a function of two columns in a single MySQL query
- How to calculate value from multiple columns in MySQL?
- MySQL query to merge rows if Id is the same and display the highest corresponding value from other columns
- How to get the fourth highest value using MySQL query?
- MySQL query to select the nth highest value in a column by skipping values
- Order by multiple columns not working as expected in MySQL?
- How to display highest value from a string with numbers set as varchar in MySQL?
- Select nth highest value in MySQL
- ORDER BY specific field value first in MySQL

Advertisements