Syntax error How to split the datetime column into date and time and compare individually in MySQL?

How to split the datetime column into date and time and compare individually in MySQL?



Let us first create a table −

mysql> create table DemoTable805(LoginDate datetime);
Query OK, 0 rows affected (0.63 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable805 values('2019-01-31 12:45:20');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable805 values('2017-11-01 10:20:30');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable805 values('2016-03-12 04:10:00');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable805 values('2018-12-24 05:01:00');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable805;

This will produce the following output −

+---------------------+
| LoginDate           |
+---------------------+
| 2019-01-31 12:45:20 |
| 2017-11-01 10:20:30 |
| 2016-03-12 04:10:00 |
| 2018-12-24 05:01:00 |
+---------------------+
4 rows in set (0.00 sec)

Here is the query to split the DateTime column into date and time and compare individually −

mysql> select cast(LoginDate AS date),cast(LoginDate AS Time) from DemoTable805;

This will produce the following output −

+-------------------------+-------------------------+
| cast(LoginDate AS date) | cast(LoginDate AS Time) |
+-------------------------+-------------------------+
| 2019-01-31              | 12:45:20                |
| 2017-11-01              | 10:20:30                |
| 2016-03-12              | 04:10:00                |
| 2018-12-24              | 05:01:00                |
+-------------------------+-------------------------+
4 rows in set (0.03 sec)
Updated on: 2019-09-03T10:39:11+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements