3

Guys i have that table in DB

-------------------------------------------------------------
ID | COMPANY_ID | NAME | DESCRIPTION | BARCODE 
-------------------------------------------------------------

i want to make a constraints that unique barcodes should be enetered with same companyID .... so how to do that in mysql ??

NB: i cam enter multiple company_id in the table

frederj
  • 1,483
  • 9
  • 20

1 Answers1

7

You need to add a Composite UNIQUE constraint on COMPANY_ID and BARCODE, to your table. This basically means that it will not allow rows having duplicate combination of values, for the said two fields. It can still allow duplicate values individually for either of them.

Eg: (1, 'abc') combination will not be able to exist in more than one row. However, (1, 'abc'), (1, 'def') can exist. So it allows duplicate values individually (Company_id in this example)

Do the following (change table and column name(s) accordingly):

ALTER TABLE your_table_name 
ADD CONSTRAINT unique_barcode_company UNIQUE (COMPANY_ID, BARCODE)
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57