Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an extra column value with INSERT ... SELECT in MySQL

Tags:

mysql

I have two tables and my goal is to move specific data from the first table into the second table along with a reason for why that data was moved. For instance:

raw_data_table

SELECT * FROM raw_data_table where id IS NULL;

I would want to move this into the second table, which is identical to the first table except for an extra column reason. I tried:

INSERT INTO bad_data_table 
(SELECT * FROM raw_data_table WHERE id IS NULL), "The ID is NULL";

But this returns a syntax error. How can I copy the entire row over and add the reason value?

like image 644
Anthony Avatar asked Apr 07 '11 16:04

Anthony


People also ask

Can we use insert and SELECT together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.

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

The basic syntax for adding a new column is as follows: ALTER TABLE table_name ADD column_name data_type constraints; The SQL ALTER TABLE add column statement we have written above takes four arguments.

How do I assign a value to a column in SELECT query?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.


1 Answers

INSERT INTO bad_data_table 
SELECT *, 'The ID is NULL' AS Reason
FROM raw_data_table
WHERE id IS NULL;
like image 144
Cade Roux Avatar answered Oct 27 '22 04:10

Cade Roux