Search code examples
sqlpostgresql

How to use PostgreSQL alias without SELECT query


I want to know command like:

ALTER TABLE table_name ALTER COLUMN column_name ADD ALIAS new_name

and after then I execute query like

SELECT column_name FROM table_name 

or

SELECT * FROM table_name

I want to get column name like new_name

I didn't find any resolve solution without SELECT column_name AS new_name, so I want it


Solution

  • That is not possible the way you asked for. Not sure what would be the reason for such an action. Maybe you could consider creating a view with altered (aliased) column names and then do the select from the view instead from the table.
    You will still have to use col_name as alias syntax when creating the view, though.

    Create Table tbl ( col_1 Int, col_2 Varchar(12) );
    
    Insert Into tbl
    Values( 1, 'A' ),
          ( 2, 'B' ),
          ( 3, 'C' );
    
    Select * From tbl;
    
    col_1 col_2
    1 A
    2 B
    3 C
    Create View tbl_v As 
      Select col_1 as c1_alias, col_2 as c2_alias
      From tbl;
    
    Select * From tbl_v;
    
    c1_alias c2_alias
    1 A
    2 B
    3 C

    fiddle