Update the records in a table with a specific year fetched from date format like '10/12/2010'?


To update records with a specific year, use the YEAR() method as in the below syntax:

update yourTableName set yourColumnName1=yourValue1 where YEAR(str_to_date(yourColumnName2,'%d/%m/%Y'))=yourValue2;

Let us first create a table −

mysql> create table DemoTable1924
   (
   UserName varchar(20),
   UserJoiningDate varchar(40)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1924 values('Chris','10/12/2010');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1924 values('David','20/01/2011');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1924 values('Mike','20/01/2010');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1924 values('Carol','26/04/2013');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1924;

This will produce the following output −

+----------+-----------------+
| UserName | UserJoiningDate |
+----------+-----------------+
| Chris    | 10/12/2010      |
| David    | 20/01/2011      |
| Mike     | 20/01/2010      |
| Carol    | 26/04/2013      |
+----------+-----------------+
4 rows in set (0.00 sec)

Here is the query to update records on the basis of a specific year −

mysql> update DemoTable1924 set UserName='Robert' where YEAR(str_to_date(UserJoiningDate,'%d/%m/%Y'))=2010;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1924;

This will produce the following output −

+----------+-----------------+
| UserName | UserJoiningDate |
+----------+-----------------+
| Robert   | 10/12/2010      |
| David    | 20/01/2011      |
| Robert   | 20/01/2010      |
| Carol    | 26/04/2013      |
+----------+-----------------+
4 rows in set (0.00 sec)

Updated on: 30-Dec-2019

57 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements