13

I want to add a column in a query that does not exist in a table and return it as a result. So lets say TABLE_TEST has column A, B and I want to return values for A, B and C. I am trying to do

SELECT A, B, C=3 FROM TABLE_TEST

or

SELECT *, C=3 FROM TABLE_TEST

Can this be done in MySQL, Postgresel or MSSQL?

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
Devin Dixon
  • 11,553
  • 24
  • 86
  • 167
  • Further to the answers below: If you need a string instead of an integer, you need single quotes around it. (That is, while `select 3 as c from table` works, `select dummy as c from table` or `select "dummy" as c from table` try to look for a column already named `dummy`, so you need `select 'dummy' as c from table`. Might vary with your SQL engine. Via http://stackoverflow.com/questions/2504163/include-in-select-a-column-that-isnt-actually-in-the-database and http://stackoverflow.com/questions/5185743/how-can-i-create-a-blank-hardcoded-column-in-a-sql-query – ShreevatsaR Oct 29 '16 at 23:53

3 Answers3

33

Yes, sure:

select a, b, 3 as c from table_test

That's it. It works on three db engines you've mentioned.

Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • 3
    You could also do _3 as "My Fake Column"_ if you want to incorporate spaces in the column name. – NKCSS Apr 09 '11 at 14:25
11

You should use:

SELECT A,B, 3 AS C FROM TABLE_TEST
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
Marco
  • 56,740
  • 14
  • 129
  • 152
3

you can use as

Select a,b, 3 as c from table

This is known as alias

anishMarokey
  • 11,279
  • 2
  • 34
  • 47