0

I want to add a new column with SQL in my data table as below,

CREATE TABLE brands ( Brand varchar(255), Contact varchar(150), Address varchar(255), Location varchar(50), ) 

:

I wish to add a new column called country, and the value only can be selected from the following values: "Japan", "New Zealand", "US", "France" enter image description here

I can add the new column but I don't know how to set the limited optional values for the column. Please help if you have ideas. Many thanks

1

2 Answers 2

4

You could use a check constraint, or a foreign key.

Check constraint:

alter table brands add country_name varchar(64) not null; alter table brands add constraint ck_country_list check (country_name in ('Japan', 'New Zealand', 'US', 'France')); 

With a check constraint, the values that are allowed never change (unless you change the constraint code). With a foreign key, the allowed values are stored in another table. As long as the value exists in the other table, they are allowed in this table.

create table countries(country_name varchar(64) not null primary key); insert countries (country_name) values ('France'), ('New Zealand') -- etc alter table brands add country_name varchar(64) not null; alter table brands add constraint fk_brands_countries foreign key (country_name) references countries (country_name); 

But we can actually do even better that! Countries already have a well defined "thing" which uniquely identifies them: ISO3166 country codes. You can use the 2 char, 3 char, or int versions. Using well defined standards where you can is always a good idea for primary keys.

This is the next level up beyond what you are currently trying to learn. But here's what it might look like:

create table countries ( country_code char(2) not null primary key clustered, country_name varchar(64) not null ); insert countries (country_code, country_name) values ('FR', 'France'), ('NZ', 'New Zealand') -- etc etc; alter table brands add country_code char(2) not null; alter table brands add constraint fk_brands_countries foreign key (country_code) references countries (country_code); 

When you want to get the country name, you join the brands table to the countries table using the country_code column.

Sign up to request clarification or add additional context in comments.

Comments

2

After you added the column you could add a check constraint

ALTER TABLE brands ADD CONSTRAINT chk_country check (Country IN ('Japan', 'New Zealand', 'US', 'France')); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.