Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL INSERT INTO with subquery and value

Tags:

sql

sql-insert

Is there a way I can use a combination of hard values and a subquery to insert into a table with one command?

For example:

INSERT INTO suppliers (supplier_id, supplier_name, supplier_type)
SELECT account_no, name
FROM customers
WHERE city = 'San Diego';

I need supplier_type to be 3. So can I do the following for the second line?

SELECT account_no, name, supplier_type = 3

supplier_type is not in the customers table

like image 418
Jaiesh_bhai Avatar asked Sep 12 '13 19:09

Jaiesh_bhai


2 Answers

Just add it with your SELECT fields.

INSERT INTO suppliers (supplier_id, supplier_name, supplier_type)
SELECT account_no, name, 3 AS supplier_type
FROM customers
WHERE city = 'San Diego';
like image 73
Kermit Avatar answered Nov 05 '22 01:11

Kermit


Even simpler, just fill in the field with the value, dont even need an AS:

INSERT INTO suppliers (supplier_id, supplier_name, supplier_type)
SELECT account_no, name, 3
FROM customers
WHERE city = 'San Diego';
like image 4
shkherad Avatar answered Nov 05 '22 02:11

shkherad