I have a table in Redshift named 'table_1', with columns named 'column_name_1','column_name_2','column_name_3'.......'column_m' etc.
table_1
column_name_1 column_name_2 column_name_3 column_name_4 .... column_name_m
I want to make a temporary table named 'temp_table' based on the following conditions:
- Select the 3 columns named
'column_name_1','column_name_2','column_name_3'
which I am sure already exist in 'table_1'.
- Select column named 'column_n' which I am not sure exists in 'table_1'. If 'column_n' exists in 'table_1', select it as it is, if it does not exist, then make a column in 'temp_table' named 'column_n' and assign it a character value 'val_n' all the rows.
So my final 'temp_table' will look like this:
- If 'column_n' exists in 'table_1'
temp_table
column_name_1 column_name_2 column_name_3 column_n
col_1_val_1 col_2_val_1 col_3_val_1 col_n_val_1
col_1_val_2 col_2_val_2 col_3_val_2 col_n_val_2
col_1_val_3 col_2_val_3 col_3_val_3 col_n_val_3
.... .... .... ....
- If 'column_n' does not exist in 'table_1'
temp_table
column_name_1 column_name_2 column_name_3 column_n
col_1_val_1 col_2_val_1 col_3_val_1 val_n
col_1_val_2 col_2_val_2 col_3_val_2 val_n
col_1_val_3 col_2_val_3 col_3_val_3 val_n
.... .... .... ....
I tried to take some hints from this link : How can I test if a column exists in a table using an SQL statement, but somehow I have not been successful in testing for a condition inside creation of a temporary table.