Lesson 46 +10 XP

INSERT INTO SELECT

INSERT INTO SELECT copies rows from one table into another.

Copy all columns


sql

### INSERT INTO Customers (CustomerName, Country)

### SELECT SupplierName, Country

### FROM Suppliers;

Copy with a WHERE


sql

### INSERT INTO Customers (CustomerName, Country)

### SELECT SupplierName, Country

### FROM Suppliers

### WHERE Country = 'Germany';

The rules

  • The number of columns in both lists must match.
  • The data types should be compatible.
  • The source and target tables can be the same database or different ones.

Example: copy with an expression


sql

### INSERT INTO newProducts (Name, DoublePrice)

### SELECT ProductName, Price * 2

### FROM Products;

TL;DR

  • INSERT INTO SELECT copies rows between tables.
  • Column counts must match.
  • Add WHERE to copy a subset.
  • Works across databases when both exist.