Question

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?

Was it helpful?

Solution

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top