Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a temporary column with a value

Tags:

sql

mysql

I have a select statement like this

select field1, field2  
  from table1

What I want is to have a newfield with only value "example".

newfield does not exist in the table, but when I run this query it kinda makes a virtual column with the values of example field.

like image 855
Asim Zaidi Avatar asked Jun 22 '10 21:06

Asim Zaidi


People also ask

How do you add a value to a temp table?

INSERT INTO SELECT statement reads data from one table and inserts it into an existing table. Such as, if we want to copy the Location table data into a temp table using the INSERT INTO SELECT statement, we have to specify the temporary table explicitly and then insert the data.

How do I add a value to an existing column?

INSERT INTO Syntax 1. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...)

How do I add a column to a select query in SQL?

Manually add it when you build the query: SELECT 'Site1' AS SiteName, t1. column, t1. column2 FROM t1 UNION ALL SELECT 'Site2' AS SiteName, t2.


4 Answers

select field1, field2, 'example' as TempField
from table1

This should work across different SQL implementations.

like image 123
Steve Homer Avatar answered Oct 17 '22 01:10

Steve Homer


You mean staticly define a value, like this:

SELECT field1, 
       field2,
       'example' AS newfield
  FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

like image 29
OMG Ponies Avatar answered Oct 17 '22 03:10

OMG Ponies


I'm rusty on SQL but I think you could use select as to make your own temporary query columns.

select field1, field2, 'example' as newfield from table1

That would only exist in your query results, of course. You're not actually modifying the table.

like image 7
DA. Avatar answered Oct 17 '22 02:10

DA.


In this example, the TABLE registrofaena doesn't have the column called minutos. The query returns a column "minutos" with demora/60 as the content (the values represent the delay in minutes). The table is not modified in the process.

This is the query:

SELECT idfaena,fechahora,demora, demora/60 as minutos,comentario 
FROM registrofaena  
WHERE fecha>='2018-10-17' AND comentario <> '' 
ORDER BY idfaena ASC;

This is the view:

This is the result

like image 4
Dlorko Avatar answered Oct 17 '22 01:10

Dlorko