0

I have the following table:

Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) UNIQUE NOT NULL
)

I'm trying to make it so that the bottom line makes it so that each entry in the "Gebruikersnaam" column is unique. Is what I did right? What do you call this type of feature?

1
  • You have added a Unique Constraint Commented Mar 30, 2017 at 10:49

2 Answers 2

4

each entry in the "Gebruikersnaam" column is unique

Yes it's right. Essentially what you did is nothing but adding a UNIQUE CONSTRAINT to your column Gebruikersnaam.

Per comment, yes it's better to name your constraint explicitly than let DB engine assign a default name implicitly like

Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) NOT NULL,
    CONSTRAINT idx_unique_Gebruikersnaam UNIQUE(Gebruikersnaam) --Here
)
Sign up to request clarification or add additional context in comments.

Comments

0

You have created an unique constraint, that is what it is called.
It is however always better to name your indexes and constraints, also the primary key you can give a name. Look at below examples.

You can create an unique index for an existing table like this

CREATE UNIQUE NONCLUSTERED INDEX idx_Gebruikersnaam
ON dbo.Medewerker(Gebruikersnaam)

in the table create it looks like this

Create table [dbo].[Medewerker]
(
    [Id] int IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) NOT NULL,

    constraint PK_MedewerkerId primary key (Id),
    constraint idx_Gebruikersnaam unique (Gebruikersnaam)        
)

Also I would use nvarchar in stead of varchar.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.