Tutorialspoint

Comparing two columns in a single MySQL query to get one row?


1 Answer
Sharon Christine

For this, you can use ORDER BY clause. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Num1 int,
   -> Num2 int
   -> );
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(60,249);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(59,250);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+------+
| Num1 | Num2 |
+------+------+
| 60   | 249 |
| 59   | 250 |
+------+------+
2 rows in set (0.00 sec)

Here is the query to comparing with two maximum of columns get one row −

mysql> select *from DemoTable
   -> order by Num2 DESC,Num1 DESC limit 1;

Here is the query to comparing with two maximum of columns get one row −

mysql> select *from DemoTable
   -> order by Num2 DESC,Num1 DESC limit 1;

This will produce the following output −

+------+------+
| Num1 | Num2 |
+------+------+
| 59   | 250  |
+------+------+
1 row in set (0.00 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.