How to add a conditional unique index on PostgreSQL

前端 未结 2 601
梦毁少年i
梦毁少年i 2020-12-05 08:54

I have a line_items table with following columns:

product_id
variant_id

variant_id is nullable.

Here is t

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 09:23

    Another option is to use expressions in your key fields. This may not have been around when you asked the question, but could be helpful for others that come across this now.

    CREATE UNIQUE INDEX line_items_prod_id_var_id_idx
    ON line_items ( product_id, (coalesce(variant_id, 0)) );
    

    Granted, this assumes that your variant_id is an auto-incrementing integer that started at 1. Also note the parentheses around the expression. Per the docs, they are required.

    http://www.postgresql.org/docs/9.3/static/sql-createindex.html

提交回复
热议问题