- 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
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)
Advertisements