- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get MySQL maximum value from 3 different columns?
To get the maximum value from three different columns, use the GREATEST() function.
The syntax is as follows
SELECT GREATEST(yourColumnName1,yourColumnName2,yourColumnName3) AS anyAliasName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table MaxOfThreeColumnsDemo -> ( -> First int, -> Second int, -> Third int -> ); Query OK, 0 rows affected (0.73 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into MaxOfThreeColumnsDemo values(30,90,60); Query OK, 1 row affected (0.16 sec) mysql> insert into MaxOfThreeColumnsDemo values(100,40,50); Query OK, 1 row affected (0.20 sec) mysql> insert into MaxOfThreeColumnsDemo values(101,290,150); Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from MaxOfThreeColumnsDemo;
The following is the output
+-------+--------+-------+ | First | Second | Third | +-------+--------+-------+ | 30 | 90 | 60 | | 100 | 40 | 50 | | 101 | 290 | 150 | +-------+--------+-------+ 3 rows in set (0.00 sec)
Here is the query to find the greatest of three columns
mysql> select greatest(First,Second,Third) AS MAXValueOfThreeColumns from MaxOfThreeColumnsDemo;
The following is the output
+------------------------+ | MAXValueOfThreeColumns | +------------------------+ | 90 | | 100 | | 290 | +------------------------+ 3 rows in set (0.00 sec)
Advertisements