Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create unique constraint for multiple columns?

Tags:

sql

go

go-gorm

I have following structure and would like to create unique index on (UserId and Contact). Is this possible in gorm?

type Contact struct {
    gorm.Model
    UserId    uint   `gorm:"index;not null"`
    Contact string `gorm:"type:text;not null"`
}

I would like to create table something like

CREATE TABLE contact (...column definitions ...) 
    CONSTRAINT constraint1
    UNIQUE (user_id, contact) 
like image 577
rkj Avatar asked Aug 14 '20 08:08

rkj


People also ask

How do I create a unique constraint on multiple columns in SQL Server?

SQL UNIQUE constraint for 2 columns example Notice that we named the UNIQUE constraints using CONSTRAINT keyword. We can use this name to remove the UNIQUE constraint later if we want. To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.

Can unique key created on multiple columns?

UNIQUE key does not allow duplicate values. UNIQUE key allows NULL values but does not allow NULL values multiple times. We can create multiple UNIQUE columns on one table however only one PRIMARY KEY for table. Defining primary key on a column has a UNIQUE constraint property by default.

How many columns can hold unique constraints?

Defining Composite Unique Keys Oracle creates an index on the columns of a unique key, so a composite unique key can contain a maximum of 16 columns.


1 Answers

The doc on models specifies the following for INDEX and UNIQUE_INDEX:

INDEX Create index with or without name, same name creates composite indexes

UNIQUE_INDEX Like INDEX, create unique index

This means that two fields with the same UNIQUE_INDEX name will create a composite unique index.

The full struct definition to use a composite index named compositeindex using your example becomes:

type Contact struct {
    gorm.Model
    UserId    uint   `gorm:"UNIQUE_INDEX:compositeindex;index;not null"`
    Contact   string `gorm:"UNIQUE_INDEX:compositeindex;type:text;not null"`
}
like image 64
Marc Avatar answered Sep 30 '22 07:09

Marc