Home > Mobile >  SQL select statement to change two other column values based on a column that contains null
SQL select statement to change two other column values based on a column that contains null

Time:01-22

I would like to use a SQL select statement that has the condition 'where column A is NULL change column B values to be equal to column C values'. How would I be able to incorporate this logic into a SELECT statement (Not an UPDATE statement as I cant change the tables on the server but want to query them from the server).

SELECT final.*
FROM final

The actual table is in the image below, here I want to change column Old to match column DirectUse if the Change column is null.

Table example

CodePudding user response:

Use a CASE expression:

SELECT Name, NameSimple, DirectUse, Year, Month,
       CASE WHEN Change IS NULL THEN DirectUse ELSE Old END AS Old,
       CurrentCons, Change
FROM final;

CodePudding user response:

I think you basically you want:

SELECT 
    ColumnA
    , CASE WHEN ColumnA IS NULL THEN ColumnC ELSE ColumnB END AS ColumnB
    , ColumnC 
    , <any other columns>
FROM Final

CodePudding user response:

Try Case statement:

       SELECT 
       Name, NameSimple, DirectUse, Year, Month,
       CASE WHEN Change IS NULL THEN DirectUse ELSE Old END AS Old,
       CurrentCons, Change
       FROM final;

CASE: https://www.w3schools.com/sql/sql_case.asp

Can also be incorporated by UNION ALL:

SELECT Old 
FROM final where Change is not null
UNION ALL
SELECT DirectUse
FROM final where Change is null
  •  Tags:  
  • Related