<p>I am trying to <code>INSERT INTO</code> a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the <code>SQL</code> engine of the day (<a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>, <a href="http://en.wikipedia.org/wiki/Oracle_Database" rel="noreferrer">Oracle</a>, <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a>, <a href="http://en.wikipedia.org/wiki/IBM_Informix" rel="noreferrer">Informix</a>, and <a href="http://en.wikipedia.org/wiki/IBM_DB2" rel="noreferrer">DB2</a>).</p>

<p>Is there a silver-bullet syntax coming from an SQL standard (for example, <a href="http://en.wikipedia.org/wiki/SQL-92" rel="noreferrer">SQL-92</a>) that would allow me to insert the values without worrying about the underlying database?</p>

[{'answer_id': 25971, 'author': 'Claude Houle', 'author_id': 244, 'author_profile': 'https://Stackoverflow.com/users/244', 'pm_score': 12, 'selected': True, 'text': '<p>Try:</p>\n<pre><code>INSERT INTO table1 ( column1 )\nSELECT  col1\nFROM    table2  \n</code></pre>\n<p>This is standard ANSI SQL and should work on any DBMS</p>\n<p>It definitely works for:</p>\n<ul>\n<li>Oracle</li>\n<li>MS SQL Server</li>\n<li>MySQL</li>\n<li>Postgres</li>\n<li>SQLite v3</li>\n<li>Teradata</li>\n<li>DB2</li>\n<li>Sybase</li>\n<li>Vertica</li>\n<li>HSQLDB</li>\n<li>H2</li>\n<li>AWS RedShift</li>\n<li>SAP HANA</li>\n<li>Google Spanner</li>\n</ul>\n'}, {'answer_id': 26080, 'author': 'travis', 'author_id': 1414, 'author_profile': 'https://Stackoverflow.com/users/1414', 'pm_score': 10, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/a/25971/282110">Claude Houle\'s answer</a>: should work fine, and you can also have multiple columns and other data as well:</p>\n\n<pre><code>INSERT INTO table1 ( column1, column2, someInt, someVarChar )\nSELECT  table2.column1, table2.column2, 8, \'some string etc.\'\nFROM    table2\nWHERE   table2.ID = 7;\n</code></pre>\n\n<p>I\'ve only used this syntax with Access, SQL 2000/2005/Express, MySQL, and PostgreSQL, so those should be covered. It should also work with SQLite3.</p>\n'}, {'answer_id': 145115, 'author': 'Jonathan Leffler', 'author_id': 15168, 'author_profile': 'https://Stackoverflow.com/users/15168', 'pm_score': 6, 'selected': False, 'text': '<p>Both the answers I see work fine in Informix specifically, and are basically standard SQL.  That is, the notation:</p>\n\n<pre><code>INSERT INTO target_table[(&lt;column-list&gt;)] SELECT ... FROM ...;\n</code></pre>\n\n<p>works fine with Informix and, I would expect, all the DBMS.  (Once upon 5 or more years ago, this is the sort of thing that MySQL did not always support; it now has decent support for this sort of standard SQL syntax and, AFAIK, it would work OK on this notation.)  The column list is optional but indicates the target columns in sequence, so the first column of the result of the SELECT will go into the first listed column, etc.  In the absence of the column list, the first column of the result of the SELECT goes into the first column of the target table.</p>\n\n<p>What can be different between systems is the notation used to identify tables in different databases - the standard has nothing to say about inter-database (let alone inter-DBMS) operations.  With Informix, you can use the following notation to identify a table:</p>\n\n<pre><code>[dbase[@server]:][owner.]table\n</code></pre>\n\n<p>That is, you may specify a database, optionally identifying the server that hosts that database if it is not in the current server, followed by an optional owner, dot, and finally the actual table name.  The SQL standard uses the term schema for what Informix calls the owner.  Thus, in Informix, any of the following notations could identify a table:</p>\n\n<pre><code>table\n"owner".table\ndbase:table\ndbase:owner.table\ndbase@server:table\ndbase@server:owner.table\n</code></pre>\n\n<p>The owner in general does not need to be quoted; however, if you do use quotes, you need to get the owner name spelled correctly - it becomes case-sensitive.  That is:</p>\n\n<pre><code>someone.table\n"someone".table\nSOMEONE.table\n</code></pre>\n\n<p>all identify the same table.  With Informix, there\'s a mild complication with MODE ANSI databases, where owner names are generally converted to upper-case (informix is the exception).  That is, in a MODE ANSI database (not commonly used), you could write:</p>\n\n<pre><code>CREATE TABLE someone.table ( ... )\n</code></pre>\n\n<p>and the owner name in the system catalog would be "SOMEONE", rather than \'someone\'.  If you enclose the owner name in double quotes, it acts like a delimited identifier.  With standard SQL, delimited identifiers can be used many places.  With Informix, you can use them only around owner names -- in other contexts, Informix treats both single-quoted and double-quoted strings as strings, rather than separating single-quoted strings as strings and double-quoted strings as delimited identifiers.  (Of course, just for completeness, there is an environment variable, DELIMIDENT, that can be set - to any value, but Y is safest - to indicate that double quotes always surround delimited identifiers and single quotes always surround strings.)</p>\n\n<p>Note that MS SQL Server manages to use [delimited identifiers] enclosed in square brackets.  It looks weird to me, and is certainly not part of the SQL standard.</p>\n'}, {'answer_id': 10914430, 'author': 'SWATI BISWAS', 'author_id': 1439766, 'author_profile': 'https://Stackoverflow.com/users/1439766', 'pm_score': 4, 'selected': False, 'text': "<p>Here is another example where source is taken using more than one table:</p>\n\n<pre><code>INSERT INTO cesc_pf_stmt_ext_wrk( \n  PF_EMP_CODE    ,\n  PF_DEPT_CODE   ,\n  PF_SEC_CODE    ,\n  PF_PROL_NO     ,\n  PF_FM_SEQ      ,\n  PF_SEQ_NO      ,\n  PF_SEP_TAG     ,\n  PF_SOURCE) \nSELECT\n  PFl_EMP_CODE    ,\n  PFl_DEPT_CODE   ,\n  PFl_SEC         ,\n  PFl_PROL_NO     ,\n  PF_FM_SEQ       ,\n  PF_SEQ_NO       ,\n  PFl_SEP_TAG     ,\n  PF_SOURCE\n FROM cesc_pf_stmt_ext,\n      cesc_pfl_emp_master\n WHERE pfl_sep_tag LIKE '0'\n   AND pfl_emp_code=pf_emp_code(+);\n\nCOMMIT;\n</code></pre>\n"}, {'answer_id': 12916793, 'author': 'northben', 'author_id': 1125584, 'author_profile': 'https://Stackoverflow.com/users/1125584', 'pm_score': 5, 'selected': False, 'text': "<p>This can be done without specifying the columns in the <code>INSERT INTO</code> part if you are supplying values for all columns in the <code>SELECT</code> part.</p>\n\n<p>Let's say table1 has two columns. This query should work:</p>\n\n<pre><code>INSERT INTO table1\nSELECT  col1, col2\nFROM    table2\n</code></pre>\n\n<p>This WOULD NOT work (value for <code>col2</code> is not specified):</p>\n\n<pre><code>INSERT INTO table1\nSELECT  col1\nFROM    table2\n</code></pre>\n\n<p>I'm using MS SQL Server. I don't know how other RDMS work.</p>\n"}, {'answer_id': 12939439, 'author': 'Faiz', 'author_id': 82961, 'author_profile': 'https://Stackoverflow.com/users/82961', 'pm_score': 4, 'selected': False, 'text': '<p>For Microsoft SQL Server, I will recommend learning to interpret the SYNTAX provided on MSDN. With Google it\'s easier than ever, to look for syntax.</p>\n\n<p>For this particular case, try </p>\n\n<blockquote>\n  <p>Google: insert site:microsoft.com</p>\n</blockquote>\n\n<p>The first result will be <a href="http://msdn.microsoft.com/en-us/library/ms174335.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms174335.aspx</a></p>\n\n<p>scroll down to the example ("Using the SELECT and EXECUTE options to insert data from other tables") if you find it difficult to interpret the syntax given at the top of the page.</p>\n\n<pre><code>[ WITH &lt;common_table_expression&gt; [ ,...n ] ]\nINSERT \n{\n        [ TOP ( expression ) [ PERCENT ] ] \n        [ INTO ] \n        { &lt;object&gt; | rowset_function_limited \n          [ WITH ( &lt;Table_Hint_Limited&gt; [ ...n ] ) ]\n        }\n    {\n        [ ( column_list ) ] \n        [ &lt;OUTPUT Clause&gt; ]\n        { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n     ] \n        | derived_table       &lt;&lt;&lt;&lt;------- Look here ------------------------\n        | execute_statement   &lt;&lt;&lt;&lt;------- Look here ------------------------\n        | &lt;dml_table_source&gt;  &lt;&lt;&lt;&lt;------- Look here ------------------------\n        | DEFAULT VALUES \n        }\n    }\n}\n[;]\n</code></pre>\n\n<p>This should be applicable for any other RDBMS available there. There is no point in remembering all the syntax for all products IMO.</p>\n'}, {'answer_id': 15573450, 'author': 'Grungondola', 'author_id': 1164019, 'author_profile': 'https://Stackoverflow.com/users/1164019', 'pm_score': 4, 'selected': False, 'text': "<p>I actually prefer the following in SQL Server 2008:</p>\n\n<pre><code>SELECT Table1.Column1, Table1.Column2, Table2.Column1, Table2.Column2, 'Some String' AS SomeString, 8 AS SomeInt\nINTO Table3\nFROM Table1 INNER JOIN Table2 ON Table1.Column1 = Table2.Column3\n</code></pre>\n\n<p>It eliminates the step of adding the Insert () set, and you just select which values go in the table.</p>\n"}, {'answer_id': 15741466, 'author': 'Santhosh', 'author_id': 1970734, 'author_profile': 'https://Stackoverflow.com/users/1970734', 'pm_score': 5, 'selected': False, 'text': '<p>Most of the databases follow the basic syntax,</p>\n\n<pre><code>INSERT INTO TABLE_NAME\nSELECT COL1, COL2 ...\nFROM TABLE_YOU_NEED_TO_TAKE_FROM\n;\n</code></pre>\n\n<p>Every database I have used follow this syntax namely, <code>DB2</code>, <code>SQL Server</code>, <code>MY SQL</code>, <code>PostgresQL</code></p>\n'}, {'answer_id': 20095817, 'author': 'elijah7', 'author_id': 3013029, 'author_profile': 'https://Stackoverflow.com/users/3013029', 'pm_score': 4, 'selected': False, 'text': "<p>This worked for me:</p>\n\n<pre><code>insert into table1 select * from table2\n</code></pre>\n\n<p>The sentence is a bit different from Oracle's.</p>\n"}, {'answer_id': 21056554, 'author': 'kylieCatt', 'author_id': 1318181, 'author_profile': 'https://Stackoverflow.com/users/1318181', 'pm_score': 8, 'selected': False, 'text': "<p>To get only one value in a multi value <code>INSERT</code> from another table I did the following in SQLite3:</p>\n\n<pre><code>INSERT INTO column_1 ( val_1, val_from_other_table ) \nVALUES('val_1', (SELECT  val_2 FROM table_2 WHERE val_2 = something))\n</code></pre>\n"}, {'answer_id': 21754160, 'author': 'RameezAli', 'author_id': 3098077, 'author_profile': 'https://Stackoverflow.com/users/3098077', 'pm_score': 4, 'selected': False, 'text': '<p>Simple insertion when table column sequence is known:</p>\n\n<pre><code>    Insert into Table1\n    values(1,2,...)\n</code></pre>\n\n<p>Simple insertion mentioning column:</p>\n\n<pre><code>    Insert into Table1(col2,col4)\n    values(1,2)\n</code></pre>\n\n<p>Bulk insertion when number of selected columns of a table(#table2) are equal to insertion table(Table1)</p>\n\n<pre><code>    Insert into Table1 {Column sequence}\n    Select * -- column sequence should be same.\n       from #table2\n</code></pre>\n\n<p>Bulk insertion when you want to insert only into desired column of a table(table1):</p>\n\n<pre><code>    Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  \n    Select Column1,Column2..desired column from #table2\n       from #table2\n</code></pre>\n'}, {'answer_id': 22528220, 'author': 'Sarvar N', 'author_id': 2490074, 'author_profile': 'https://Stackoverflow.com/users/2490074', 'pm_score': 5, 'selected': False, 'text': '<p>This is another example using values with select:</p>\n\n<pre><code>INSERT INTO table1(desc, id, email) \nSELECT "Hello World", 3, email FROM table2 WHERE ...\n</code></pre>\n'}, {'answer_id': 23715783, 'author': 'Pavel', 'author_id': 3115912, 'author_profile': 'https://Stackoverflow.com/users/3115912', 'pm_score': 3, 'selected': False, 'text': "<pre><code>select *\ninto tmp\nfrom orders\n</code></pre>\n\n<p>Looks nice, but works only if tmp doesn't exists (creates it and fills). (SQL sever)</p>\n\n<p>To insert into existing tmp table: </p>\n\n<pre><code>set identity_insert tmp on\n\ninsert tmp \n([OrderID]\n      ,[CustomerID]\n      ,[EmployeeID]\n      ,[OrderDate]\n      ,[RequiredDate]\n      ,[ShippedDate]\n      ,[ShipVia]\n      ,[Freight]\n      ,[ShipName]\n      ,[ShipAddress]\n      ,[ShipCity]\n      ,[ShipRegion]\n      ,[ShipPostalCode]\n      ,[ShipCountry] )\n      select * from orders\n\nset identity_insert tmp off\n</code></pre>\n"}, {'answer_id': 29544903, 'author': 'Weslor', 'author_id': 4140711, 'author_profile': 'https://Stackoverflow.com/users/4140711', 'pm_score': 6, 'selected': False, 'text': '<p>To add something in the first answer, when we want only few records from another table (in this example only one):</p>\n\n<pre><code>INSERT INTO TABLE1\n(COLUMN1, COLUMN2, COLUMN3, COLUMN4) \nVALUES (value1, value2, \n(SELECT COLUMN_TABLE2 \nFROM TABLE2\nWHERE COLUMN_TABLE2 like "blabla"),\nvalue4);\n</code></pre>\n'}, {'answer_id': 29769671, 'author': 'logan', 'author_id': 975199, 'author_profile': 'https://Stackoverflow.com/users/975199', 'pm_score': 5, 'selected': False, 'text': '<p>Instead of <code>VALUES</code> part of <code>INSERT</code> query, just use <code>SELECT</code> query as below.</p>\n\n<pre><code>INSERT INTO table1 ( column1 , 2, 3... )\nSELECT col1, 2, 3... FROM table2\n</code></pre>\n'}, {'answer_id': 30344570, 'author': 'Matt', 'author_id': 2641576, 'author_profile': 'https://Stackoverflow.com/users/2641576', 'pm_score': 4, 'selected': False, 'text': '<pre><code>INSERT INTO yourtable\nSELECT fielda, fieldb, fieldc\nFROM donortable;\n</code></pre>\n\n<p>This works on all DBMS</p>\n'}, {'answer_id': 36181014, 'author': 'Ciarán Bruen', 'author_id': 177347, 'author_profile': 'https://Stackoverflow.com/users/177347', 'pm_score': 4, 'selected': False, 'text': "<p>Here's how to insert from multiple tables. This particular example is where you have a mapping table in a many to many scenario:</p>\n\n<pre><code>insert into StudentCourseMap (StudentId, CourseId) \nSELECT  Student.Id, Course.Id FROM Student, Course \nWHERE Student.Name = 'Paddy Murphy' AND Course.Name = 'Basket weaving for beginners'\n</code></pre>\n\n<p>(I realise matching on the student name might return more than one value but you get the idea. Matching on something other than an Id is necessary when the Id is an Identity column and is unknown.)</p>\n"}, {'answer_id': 37879263, 'author': 'Bharath theorare', 'author_id': 2700841, 'author_profile': 'https://Stackoverflow.com/users/2700841', 'pm_score': 4, 'selected': False, 'text': '<p>You could try this if you want to insert all column using <code>SELECT * INTO</code> table.</p>\n\n<pre><code>SELECT  *\nINTO    Table2\nFROM    Table1;\n</code></pre>\n'}, {'answer_id': 44449020, 'author': 'Sebastian', 'author_id': 6248747, 'author_profile': 'https://Stackoverflow.com/users/6248747', 'pm_score': 2, 'selected': False, 'text': '<p>If you go the INSERT VALUES route to insert multiple rows, make sure to delimit the VALUES into sets using parentheses, so:    </p>\n\n<pre><code>INSERT INTO `receiving_table`\n  (id,\n  first_name,\n  last_name)\nVALUES \n  (1002,\'Charles\',\'Babbage\'),\n  (1003,\'George\', \'Boole\'),\n  (1001,\'Donald\',\'Chamberlin\'),\n  (1004,\'Alan\',\'Turing\'),\n  (1005,\'My\',\'Widenius\');\n</code></pre>\n\n<p>Otherwise MySQL objects that "Column count doesn\'t match value count at row 1", and you end up writing a trivial post when you finally figure out what to do about it. </p>\n'}, {'answer_id': 48771455, 'author': 'Gaurav', 'author_id': 8527035, 'author_profile': 'https://Stackoverflow.com/users/8527035', 'pm_score': 4, 'selected': False, 'text': '<pre><code>INSERT INTO FIRST_TABLE_NAME (COLUMN_NAME)\nSELECT  COLUMN_NAME\nFROM    ANOTHER_TABLE_NAME \nWHERE CONDITION;\n</code></pre>\n'}, {'answer_id': 50734798, 'author': 'Manish Vadher', 'author_id': 6313628, 'author_profile': 'https://Stackoverflow.com/users/6313628', 'pm_score': 3, 'selected': False, 'text': '<p>Best way to insert multiple records from any other tables.   </p>\n\n<pre><code>INSERT  INTO dbo.Users\n            ( UserID ,\n              Full_Name ,\n              Login_Name ,\n              Password\n            )\n            SELECT  UserID ,\n                    Full_Name ,\n                    Login_Name ,\n                    Password\n            FROM    Users_Table\n            (INNER JOIN / LEFT JOIN ...)\n            (WHERE CONDITION...)\n            (OTHER CLAUSE)\n</code></pre>\n'}, {'answer_id': 52476225, 'author': 'Dasikely', 'author_id': 5721196, 'author_profile': 'https://Stackoverflow.com/users/5721196', 'pm_score': 5, 'selected': False, 'text': "<p>Just use parenthesis for <strong>SELECT</strong> clause into INSERT. For example like this :</p>\n\n<pre><code>INSERT INTO Table1 (col1, col2, your_desired_value_from_select_clause, col3)\nVALUES (\n   'col1_value', \n   'col2_value',\n   (SELECT col_Table2 FROM Table2 WHERE IdTable2 = 'your_satisfied_value_for_col_Table2_selected'),\n   'col3_value'\n);\n</code></pre>\n"}, {'answer_id': 55507700, 'author': 'Mohammed Safeer', 'author_id': 2293686, 'author_profile': 'https://Stackoverflow.com/users/2293686', 'pm_score': 6, 'selected': False, 'text': "<p>Two approaches for insert into with select sub-query. </p>\n\n<ol>\n<li>With SELECT subquery returning results with <strong>One row</strong>.</li>\n<li>With SELECT subquery returning results with <strong>Multiple rows</strong>.</li>\n</ol>\n\n<p><strong>1. Approach for With SELECT subquery returning results with <em>one row</em>.</strong></p>\n\n<pre><code>INSERT INTO &lt;table_name&gt; (&lt;field1&gt;, &lt;field2&gt;, &lt;field3&gt;) \nVALUES ('DUMMY1', (SELECT &lt;field&gt; FROM &lt;table_name&gt; ),'DUMMY2');\n</code></pre>\n\n<p>In this case, it assumes SELECT Sub-query returns only one row of result based on WHERE condition or SQL aggregate functions like SUM, MAX, AVG etc. Otherwise it will throw error</p>\n\n<p><strong>2. Approach for With SELECT subquery returning results with <em>multiple rows</em>.</strong></p>\n\n<pre><code>INSERT INTO &lt;table_name&gt; (&lt;field1&gt;, &lt;field2&gt;, &lt;field3&gt;) \nSELECT 'DUMMY1', &lt;field&gt;, 'DUMMY2' FROM &lt;table_name&gt;;\n</code></pre>\n\n<p>The second approach will work for both the cases.</p>\n"}, {'answer_id': 59300010, 'author': 'Miroslav Savel', 'author_id': 10839776, 'author_profile': 'https://Stackoverflow.com/users/10839776', 'pm_score': 0, 'selected': False, 'text': '<p>In informix it works as Claude said:</p>\n\n<pre><code>INSERT INTO table (column1, column2) \nVALUES (value1, value2);    \n</code></pre>\n'}, {'answer_id': 60972386, 'author': 'Kazakov Vsevolod', 'author_id': 1063460, 'author_profile': 'https://Stackoverflow.com/users/1063460', 'pm_score': 0, 'selected': False, 'text': '<p>Postgres supports next:\ncreate table company.monitor2 as select * from company.monitor;</p>\n'}, {'answer_id': 62135236, 'author': 'S.M.Fazle Rabbi', 'author_id': 5803730, 'author_profile': 'https://Stackoverflow.com/users/5803730', 'pm_score': 3, 'selected': False, 'text': '<p>IF you want to insert some data into a table without want to write column name.</p>\n\n<pre><code>INSERT INTO CUSTOMER_INFO\n   (SELECT CUSTOMER_NAME,\n           MOBILE_NO,\n           ADDRESS\n      FROM OWNER_INFO cm)\n</code></pre>\n\n<p>Where the tables are:</p>\n\n<pre><code>            CUSTOMER_INFO               ||            OWNER_INFO\n----------------------------------------||-------------------------------------\nCUSTOMER_NAME | MOBILE_NO | ADDRESS     || CUSTOMER_NAME | MOBILE_NO | ADDRESS \n--------------|-----------|---------    || --------------|-----------|--------- \n      A       |     +1    |   DC        ||       B       |     +55   |   RR  \n</code></pre>\n\n<p><strong>Result:</strong></p>\n\n<pre><code>            CUSTOMER_INFO               ||            OWNER_INFO\n----------------------------------------||-------------------------------------\nCUSTOMER_NAME | MOBILE_NO | ADDRESS     || CUSTOMER_NAME | MOBILE_NO | ADDRESS \n--------------|-----------|---------    || --------------|-----------|--------- \n      A       |     +1    |   DC        ||       B       |     +55   |   RR\n      B       |     +55   |   RR        ||\n</code></pre>\n'}, {'answer_id': 68365315, 'author': 'Serdin Çelik', 'author_id': 7834559, 'author_profile': 'https://Stackoverflow.com/users/7834559', 'pm_score': 2, 'selected': False, 'text': '<p>If you create table firstly you can use like this;</p>\n<pre><code>  select * INTO TableYedek From Table\n</code></pre>\n<p>This metot insert values but differently with creating new copy table.</p>\n'}]
['https://Stackoverflow.com/questions/25969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244/']