Unique Key column in the database table used to avoid the duplication of data in the same column.
Using a unique column key, Table gives guarantees to unique value for the column from the set of records in a table.
First, we create a simple db_schema.xml file to create a table,
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="customer_records" resource="default" engine="innodb" comment="Catalogrule Label">
<column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true"
comment="Id"/>
<column xsi:type="varchar" name="coupon_code" nullable="false" length="255" comment="Coupon code"/>
<column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false"
comment="Store Id"/>
<constraint xsi:type="unique" referenceId="CUSTOMER_RECORDS_COUPON_CODE_STORE_ID">
<column name="coupon_code"/>
<column name="store_id"/>
</constraint>
</table>
</schema>
You can add a unique key for the column using constraint xsi:type=“unique” in an XML file.
In Customer_records table, We have defined two columns as unique,
1. coupon_code
2. store_id
You need to pass the below syntax,
<constraint xsi:type="unique" referenceId="CUSTOMER_RECORDS_COUPONCODE_STORE_ID">
<column name="coupon_code"/>
<column name="store_id"/>
</constraint>
Add your unique column under <column /> node to create unique column.
You can add one or multiple unique key columns inside the table.
