HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

SQL set allowed values for a column

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
allowedcolumnsqlforvaluesset

Problem

I want to make an ALTER TABLE expression which adds a new column and sets a default value and additionaly defines the allowed values for that column. It's a text column, and allowed should be only 'value1', 'value2' and 'value3'. Default should be 'value1'

According to following syntax diagrams:

I'm getting to this point

ALTER TABLE exampleTable ADD COLUMN new_column VarChar(20) DEFAULT 'value1'


but I'm absolutely not sure how to set the allowed values.

Is it possible to make somethin like

CONSTRAINT CHECK new_column IN ('value1', 'value2', 'value3)

? I must admit the search condition diagram is quite confusing me.

Solution

You should actually do this as two different statements:

ALTER TABLE test
    ADD new_column VARCHAR(20) DEFAULT 'value1'

ALTER TABLE test
    ADD CONSTRAINT CK_exampleTable_newColumn CHECK (new_column IN ('value1','value2','value3'))

Code Snippets

ALTER TABLE test
    ADD new_column VARCHAR(20) DEFAULT 'value1'

ALTER TABLE test
    ADD CONSTRAINT CK_exampleTable_newColumn CHECK (new_column IN ('value1','value2','value3'))

Context

StackExchange Database Administrators Q#29801, answer score: 8

Revisions (0)

No revisions yet.