📜  sql into - SQL (1)

📅  最后修改于: 2023-12-03 15:35:04.476000             🧑  作者: Mango

SQL INTO

Introduction

SQL INTO is a statement used in SQL to specify the destination of output from a SELECT query. This statement is commonly used to create a new table or temporary table to store the results of a query. INTO clause is also used with other SQL statements such as INSERT INTO and SELECT INTO OUTFILE.

Syntax and Usage
Syntax

The basic syntax of SQL INTO statement is as follows:

SELECT column1, column2, ...
INTO new_table_name [IN external_database]
FROM source_table_name [WHERE condition];

INSERT INTO new_table_name [IN external_database]
SELECT column1, column2, ...
FROM source_table_name [WHERE condition];

SELECT column1, column2, ...
INTO OUTFILE 'file_path'
FROM source_table_name [WHERE condition];
Usage
  • INTO new_table_name [IN external_database]: The INTO clause can be used with a SELECT statement to create a new table and store the results of the SELECT query. The new table will have the same structure as the SELECT query. If IN external_database is specified, the new table will be created in an external database instead of the current database.

  • INSERT INTO new_table_name [IN external_database]: The INTO clause can also be used with an INSERT statement to insert data into a new table. If IN external_database is specified, the new table will be created in an external database instead of the current database.

  • INTO OUTFILE 'file_path': The INTO clause can be used with a SELECT statement to write the output to a file. The file_path specifies the name and location of the file.

Examples
Example 1
SELECT customer_id, order_date, order_amount 
INTO new_orders
FROM orders;

In this example, a new table named new_orders is created with the columns customer_id, order_date, and order_amount. The data is extracted from the orders table.

Example 2
INSERT INTO new_customers
SELECT customer_name, customer_email, customer_phone 
FROM customers
WHERE customer_country = 'USA';

In this example, a new table named new_customers is created and the data from customers table where customer_country equals to 'USA' is inserted.

Example 3
SELECT product_name, product_price
INTO OUTFILE 'C:/data/products.csv'
FROM products
WHERE product_id < 100;

In this example, the SELECT query results are written to a file named products.csv located at C:/data/ directory. Only the data where product_id is less than 100 is extracted.

Conclusion

SQL INTO is a powerful statement for manipulating data in SQL. It is used to create a new table or temporary table to store the results of a query, insert data into a new table, and write query output to a file. Understanding and mastering SQL INTO is essential for any programmer working with SQL databases.