0

Consider the following tables

CREATE TABLE Main (
    id INT PRIMARY KEY,
    state VARCHAR(255) DEFAULT NULL 
)

CREATE TABLE ColorTable (
    color VARCHAR(255),
    state  VARCHAR(255)
)


INSERT INTO Main (id, state) VALUES 
    (1, 'A'),
    (2, 'B'),
    (3, 'C'),
    (4, 'B'),
    (5, 'C'),
    (6, 'A'),
    (7, NULL)

INSERT INTO ColorTable (color, state) VALUES 
    ('Yellow', 'A'),
    ('Red', 'B'),
    ('Green', 'C'),
    ('Black', NULL)

I would like to add a new column 'color' into the table 'Main'. I want this such that the color for each id is based on the state in 'Main', and the corresponding color in 'ColorTable'.

I can achieve this through the following:

ALTER TABLE main  
ADD color VARCHAR(255)

UPDATE main 
SET main.color = ColorTable.color 
FROM main 
LEFT JOIN ColorTable ON main.state = ColorTable.state 

UPDATE main 
SET color = 'Red'
WHERE state IS NULL 

I am curious as to alternative methods of doing this–can I achieve the same result using a SELECT INTO or something else?

1 Answer 1

1

No, you cannot alter the table structure and insert the data into new column in one statement.

But you can combine last 2 updates:

UPDATE main 
SET main.color = CASE WHEN main.state IS NULL
                      THEN 'Red'
                      ELSE ColorTable.color 
                      END
FROM main 
LEFT JOIN ColorTable ON main.state = ColorTable.state 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.