Create a UNIQUE multi- (product_id, variant_id) INDEX in (product_id, variant_id) :
CREATE UNIQUE INDEX line_items_prod_id_var_id_idx ON line_items (product_id, variant_id);
However, this will allow the use of multiple elements (1, NULL) for (product_id, variant_id) , because NULL values ββare not considered identical.
To compensate for this, additionally create a partial UNIQUE INDEX on product_id :
CREATE UNIQUE INDEX line_items_prod_id_var_null_idx ON line_items (product_id) WHERE variant_id IS NULL;
So you can enter (1,2) , (1,3) and (1, NULL) , but not one of them can be a second time. Also speeds up queries with conditions on one or both columns.
This answer to dba.SE I recently wrote is very similar and almost directly applicable to your problem.
source share