Search code examples
sqlif-statementcase

How to use CASE statement in SQL to change an empty field in one column based on another column


I'm just starting with SQL with no training but the job suddenly requires it. So thank you in advance for any help.

Let's say I have a query that returns 3 columns. Some of the cells in column 3 are empty and I would like to fill them in with values based on column1.

example:

CASE column1 = 'Individual' then Column3 should show 'Individual' not empty, but if column1 = 'group' them column3 needs to show "group" else no change.  

SELECT column1, column2, column3,  
CASE  
    WHEN column1 = 'Individual' THEN Column3 = 'Individual'  
    WHEN column1 = "Group' THEN comlumn3 = 'Group'  
END  
FROM tablename

Solution

  • If you only want to select data and not change the table values you can use case as you tried:

    SELECT column1, column2,
    CASE  
        WHEN column3 IS NULL THEN Column1  
        ELSE column3
    END as column3
    FROM tablename