MySQL select distinct dates from datetime column in a table?

MySQLMySQLi Database

You need to use DISTINCT keyword to select distinct dates from datetime column in a table.

For an example, let us create a table

mysql> create table PostMesssageDemo
   - > (
   - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > UserMessage varchar(100),
   - > UserPost datetime
   - > );
Query OK, 0 rows affected (0.60 sec)

Now you can insert some records in the table using insert command.

The query is as follows

mysql> insert into PostMesssageDemo(UserMessage,UserPost) values('Software Developer',now());
Query OK, 1 row affected (0.17 sec)
mysql> insert into PostMesssageDemo(UserMessage,UserPost) values('Software Developer',date_add(now(),interval 3 month));
Query OK, 1 row affected (0.16 sec)
mysql> insert into PostMesssageDemo(UserMessage,UserPost) values('Software Developer',now());
Query OK, 1 row affected (0.12 sec)
mysql> insert into PostMesssageDemo(UserMessage,UserPost) values('Software Developer','2019-03-31 17:30:34');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from PostMesssageDemo;

The following is the output

+--------+--------------------+---------------------+
| UserId | UserMessage        | UserPost            |
+--------+--------------------+---------------------+
|      1 | Software Developer | 2019-02-15 18:07:27 |
|      2 | Software Developer | 2019-05-15 18:09:18 |
|      3 | Software Developer | 2019-02-15 18:09:31 |
|      4 | Software Developer | 2019-03-31 17:30:34 |
+--------+--------------------+---------------------+
4 rows in set (0.00 sec)

The following is the query to get distinct dates

mysql> select distinct year(UserPost),month(UserPost) from PostMesssageDemo;

Here is the output

+----------------+-----------------+
| year(UserPost) | month(UserPost) |
+----------------+-----------------+
|           2019 |               2 |
|           2019 |               5 |
|           2019 |               3 |
+----------------+-----------------+
3 rows in set (0.00 sec)
raja
Published on 19-Mar-2019 10:39:21
Advertisements