Set custom messages by working with MySQL IF Statements and SELECT in a user-defined variable


Let us first create a table −

mysql> create table DemoTable2008
(
   Value int
);
Query OK, 0 rows affected (10.59 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable2008 values(10);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable2008 values(20);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable2008 values(30);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable2008 values(-31);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable2008 values(-28);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable2008;

This will produce the following output −

+-------+
| Value |
+-------+
|    10 |
|    20 |
|    30 |
|   -31 |
|   -28 |
+-------+
5 rows in set (0.00 sec)

Here is the query to first work with a user-defined variable and taking input as a SELECT −

mysql> set @value:=(select sum(Value) from DemoTable2008);
Query OK, 0 rows affected (0.03 sec)
mysql> select if(@value > 0, 'Value is greater than 0','Not greater than') as Result;

This will produce the following output −

+-------------------------+
| Result                  |
+-------------------------+
| Value is greater than 0 |
+-------------------------+
1 row in set (0.00 sec)

Updated on: 02-Jan-2020

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements