Postgresql – How to create unique index for both cases

indexpostgresqlunique-constraint

I have table in PostgreSQL with sender_id and receiver_id and a unique index:

add_index :my_table, [:sender_id, :recipient_id], unique: true

Table will created, if sender_id: 1, and recipient_id: 2.

I can create another table, with sender_id: 2, and recipient_id: 1. But table with this ids, (but in different order) already exists.

How can I make unique for both cases?

  • sender_id: 1, recipient_id: 2
  • sender_id: 2, recipient_id: 1

Best Answer

For Postgres and Oracle:

create unique index unique_combinations 
    on my_table (least(sender_id, recipient_id), greatest(sender_id, recipient_id));