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?
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.
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.
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 ...
INSERT INTO Movies (Title, Director, Cost, Profits) SELECT 'Star Wars', name, 50000, 1000000 FROM Directors WHERE name = 'Lucas'
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With