SQL Select Into
In SQL, the SELECT INTO
statement is used to create a new table from an existing table by selecting a subset of rows and columns. This can be useful for creating summary tables or temporary tables for analysis.
Here is an example of how to use the SELECT INTO
statement:
SELECT customer_id, SUM(order_total) AS total_spent INTO customer_totals FROM orders GROUP BY customer_id;
In this example, we are selecting the customer_id
column and the sum of the order_total
column from the orders
table. We are grouping the results by customer_id
using the GROUP BY
clause. The INTO
keyword is used to specify the name of the new table to be created, which will contain the selected columns and grouped data.
After running this statement, a new table called customer_totals
will be created, containing two columns: customer_id
and total_spent
. Each row in the new table will represent a customer ID and their total order amount.
Note that the SELECT INTO
statement creates a new table, so you should ensure that the table name does not already exist in the database or you will get an error. Also, the data types of the new table's columns will be inferred from the selected columns, so be sure to select appropriate data types to avoid errors or unexpected results.