
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use CAST Function in MySQL SELECT Statement
The CAST() function in MySQL converts a value of any type into a value that has a specified type. Let us first create a table −
mysql> create table castFunctionDemo -> ( -> ShippingDate date -> ); Query OK, 0 rows affected (0.74 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into castFunctionDemo values('2019-01-31'); Query OK, 1 row affected (0.20 sec) mysql> insert into castFunctionDemo values('2018-07-12'); Query OK, 1 row affected (0.16 sec) mysql> insert into castFunctionDemo values('2016-12-06'); Query OK, 1 row affected (0.16 sec) mysql> insert into castFunctionDemo values('2017-08-25'); Query OK, 1 row affected (0.19 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from castFunctionDemo;
This will produce the following output −
+--------------+ | ShippingDate | +--------------+ | 2019-01-31 | | 2018-07-12 | | 2016-12-06 | | 2017-08-25 | +--------------+ 4 rows in set (0.00 sec)
Here is the query to use the cast() function correctly in a MySQL select statement −
mysql> select CAST(ShippingDate AS CHAR(12)) as Conversion FROM castFunctionDemo;
This will produce the following output −
+------------+ | Conversion | +------------+ | 2019-01-31 | | 2018-07-12 | | 2016-12-06 | | 2017-08-25 | +------------+ 4 rows in set (0.00 sec)
Advertisements