bhylu.com

Advertisements

SQL Select Into

Creating a table from a query is useful for a temporary investigation or a deliberate snapshot. The syntax is database-specific. SQLite uses CREATE TABLE AS SELECT; SQL Server commonly uses SELECT columns INTO new_table FROM source.

Understand the idea

The example copies available products into a new table in the disposable playground. It copies the selected values at that moment, not a live link. Later source changes do not flow into the new table. Constraints and indexes are not automatically reproduced as a full schema clone. In MySQL, SELECT INTO has other uses, so use CREATE TABLE AS SELECT for this task.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

CREATE TABLE available_products AS
SELECT product_id, name, stock
FROM products WHERE stock > 0;

SELECT * FROM available_products ORDER BY product_id;

Read the result

The new table contains products 1, 2, and 4. Canvas bag is missing because its stock was zero when the snapshot query ran.

Try one change

Update one source stock value after creating the snapshot. Compare the source and copied table to see that the copy does not refresh itself.