Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL insert with select and hard-coded values

Tags:

For illustration purposes, let's say I have a database Movies(Title, Director, Cost, Profits).

Now I would like to insert a new row into the Movies table based on a director found in another table and then hard coded values.

INSERT INTO Movies  SELECT name    FROM Directors   WHERE name = 'Lucas'; 

Is how I understand select inserts work but what if I want to use the select as well as pass in hard coded values. So something theoretically like this:

INSERT INTO Movies  VALUES(Star Wars,(SELECT name                      FROM Directors                     WHERE name='Lucas'), 50000, 1000000); 

Is this possible?

like image 504
Msencenb Avatar asked Nov 10 '10 04:11

Msencenb


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 static value to a select query?

Static values can be inserted into a resultset returned from a SELECT query as another column. Simply use the static value as a column to select, and the query will return a column where the name of the column is the static value, and every row in that column will return that same static value.

What is hard coded in SQL?

Hard coding (also, hard-coding or hardcoding) refers to the software development practice of embedding what may, perhaps only in retrospect, be regarded as input or configuration data directly into the source code of a program or other executable object, or fixed formatting of the data, instead of obtaining that data ...


2 Answers

INSERT INTO Movies (Title, Director, Cost, Profits) SELECT 'Star Wars', name, 50000, 1000000 FROM Directors WHERE name = 'Lucas' 
like image 152
Phil Avatar answered Oct 16 '22 01:10

Phil


Because you can specify hardcoded values in the select statement, it's probably cleaner to use:

insert into movies (title, director, cost, profits)    select 'Star Wars', name, 50000, 1000000 from directors where name = 'Lucas'; 
like image 35
paxdiablo Avatar answered Oct 16 '22 01:10

paxdiablo