How do I force the column alias to be of specific data type in MySQL?


For this, you can use CASE statement. Let us first create a table −

mysql> create table DemoTable1505
   -> (
   -> Value integer unsigned,
   -> Status tinyint(1)
   -> );
Query OK, 0 rows affected (0.47 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1505 values(20,0);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1505 values(45,1);
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1505;

This will produce the following output −

+-------+--------+
| Value | Status |
+-------+--------+
|    20 |      0 |
|    45 |      1 |
+-------+--------+
2 rows in set (0.00 sec)

Here is the query to force the column alias to be of specific data type −

mysql> select case status
   -> when 0 then cast(Value as signed)*1
   -> when 1 then cast(Value as signed)*-1
   -> end as AllValues from DemoTable1505;

This will produce the following output −

+-----------+
| AllValues |
+-----------+
|        20 |
|       -45 |
+-----------+
2 rows in set (0.00 sec)

Updated on: 11-Dec-2019

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements