SQL INSERT INTO SELECT



  SQL > Table Manipulation > Insert Into Select Statement

In the previous section, we learned about how to insert individual values into a table, one row at a time. What if we want to insert multiple rows into a table? In addition to INSERT INTO, we will combine it with the SELECT statement to achieve this goal. If you are thinking whether this means that you are using information from another table, you are correct. The syntax is as follows:

INSERT INTO "table1" ("column1", "column2", ...)
SELECT "column3", "column4", ...
FROM "table2"

Note that this is the simplest form. The entire statement can easily contain WHERE, GROUP BY, and HAVING clauses, as well as table joins and aliases.

Assuming that we have a table that has the following structure,

Table Store_Information
Column NameData Type
store_namechar(50)
Salesfloat
Datedatetime

Table Sales_Data
Column NameData Type
store_namechar(50)
Product_IDinteger
Salesfloat
Datedatetime

Table Sales_Data has detailed sales information, while table Store_Information keeps summarized data on sales by store by day. To move data from Sales_Data to Store_Information, we would type in:

INSERT INTO Store_Information (store_name, Sales, Date)
SELECT store_name, sum(Sales), Date
FROM Sales_Information
GROUP BY store_name, date;

Please note that we specified the order of the columns to insert data into in the example above (the first column is store_name, the second column is Sales, and the third column is Date). While this is not absolutely necessary, it is a good practice to follow, as this can ensure that we are always inserting data into the correct column.

Next: SQL UPDATE




Copyright © 2013 1keydata.com   All Rights Reserved.     Privacy Policy


SQL SELECT
SQL DISTINCT
SQL WHERE
SQL AND OR
SQL IN
SQL BETWEEN
SQL Wildcard
SQL LIKE
SQL ORDER BY
SQL Functions
SQL Average
SQL COUNT
SQL MAX
SQL MIN
SQL SUM
SQL GROUP BY
SQL HAVING
SQL ALIAS
SQL AS
SQL JOIN
SQL INNER JOIN
SQL OUTER JOIN
SQL LEFT OUTER JOIN
SQL CROSS JOIN
SQL SELECT UNIQUE
SQL ROUND
SQL CAST
SQL CONVERT
SQL CONCATENATE
SQL SUBSTRING
SQL INSTR
SQL TRIM
SQL LENGTH
SQL REPLACE
SQL DATEADD
SQL DATEDIFF
SQL DATEPART
SQL GETDATE
SQL SYSDATE

SQL CREATE TABLE
SQL Data Types
SQL CONSTRAINT
SQL NOT NULL
SQL DEFAULT
SQL UNIQUE
SQL CHECK
PRIMARY KEY
FOREIGN KEY
SQL View
SQL CREATE VIEW
SQL Index
SQL CREATE INDEX
SQL ALTER TABLE
SQL DROP TABLE
SQL TRUNCATE TABLE
SQL USE
SQL CREATE DATABASE
SQL DROP DATABASE
SQL INSERT INTO
SQL INSERT INTO SELECT
SQL UPDATE
SQL DELETE FROM

SQL Video Tutorial
SQL Jobs

Site Map
Resources