Creating Unique Key in MySQL table referring to date?

MySQLMySQLi Database

To create a unique key in MySQL table referring to date, you can use the following syntax −

CREATE TABLE yourTableName
(
   yourIdColumnName dataType,
   yourDateColumnName dataType,
   .
   .
   .
   N
   UNIQUE KEY(yourIdColumnName, yourDateColumnName )
);

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table keyReferringToDateDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Client_Id int,
   -> ClientProjectDeadline date,
   -> ClientName varchar(100),
   -> ClientAge int,
   -> ClientCountryName varchar(20) ,
   -> UNIQUE KEY(Client_Id,ClientProjectDeadline)
   -> );
Query OK, 0 rows affected (0.63 sec)

Let us check all the details of table using SHOW CREATE command. The query is as follows −

mysql> show create table keyReferringToDateDemo;

Here is the output −

+------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------+
| Table                  | Create Table                        |
+------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| keyReferringToDateDemo | CREATE TABLE `keyreferringtodatedemo` (`Id` int(11) NOT NULL AUTO_INCREMENT,`Client_Id` int(11) DEFAULT NULL,`ClientProjectDeadline` date DEFAULT NULL,`ClientName` varchar(100) DEFAULT NULL,`ClientAge` int(11) DEFAULT NULL,`ClientCountryName` varchar(20) DEFAULT NULL,PRIMARY KEY (`Id`),UNIQUE KEY `Client_Id` (`Client_Id`,`ClientProjectDeadline`)
) ENGINE =InnoDB DEFAULT CHARSET =utf8 |
+------------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
raja
Published on 01-Apr-2019 12:00:31
Advertisements