sqlpostgresqlsql-view

Add a new column to a view in SQL


I have a database and I've made a view with the data I want. The data looks something like this:

    n     |   value |
----------+---------+
 50404791 |     112 | 
  5034591 |     164 |
 50280287 |      31 |

I want to add a column of text like this:

    n     |   value | status |
----------+---------+--------+
 50404791 |     112 |default | 
  5034591 |     164 |biggest |
 50280287 |      31 |smallest|

I tried Alter Table Table1 Add Column status text ; but it seems like text is not a data type. Any suggestions what to do?


Solution

  • Tested on Rextester.com (remember, avoid anyway to use SELECT * in a view)

    CREATE TABLE TABLE1 (ID INTEGER);
    CREATE VIEW V1 AS SELECT * FROM TABLE1;
    INSERT INTO TABLE1 VALUES (0);
    
    ALTER TABLE TABLE1 ADD COLUMN STATUS TEXT;    
    INSERT INTO TABLE1 (ID, STATUS) VALUES (1, 'aaa');
    
    SELECT * FROM V1;
    DROP VIEW V1;
    
    CREATE VIEW V1 AS SELECT * FROM TABLE1;
    SELECT * FROM V1;
    

    Output:

        id
    1   0
    2   1
    
        id  status
    1   0   NULL
    2   1   aaa