INSERT
What it means
Section titled βWhat it meansβINSERT adds one or more new rows to a table. You can specify column names explicitly (recommended β resilient to future schema changes) or rely on column order (fragile), insert a single row or multiple rows in one statement, or insert the results of a SELECT query directly.
Examples
Section titled βExamplesβINSERT INTO Customers (Name, Email)VALUES ('Alice', 'alice@example.com');
-- Multiple rows in one statementINSERT INTO Customers (Name, Email)VALUES ('Alice', 'alice@example.com'), ('Bob', 'bob@example.com');
-- Insert from a query result (copy filtered data into another table)INSERT INTO ArchivedOrders (Id, CustomerId, Amount)SELECT Id, CustomerId, Amount FROM Orders WHERE OrderDate < '2020-01-01';
-- Capture the generated identity valueINSERT INTO Customers (Name, Email) VALUES ('Carol', 'carol@example.com');SELECT SCOPE_IDENTITY(); -- the auto-generated Id for the row just insertedCommon mistake
Section titled βCommon mistakeβOmitting the column list and relying on positional order β this compiles fine today, but silently breaks (or worse, inserts data into the wrong columns without error) the moment someone adds, removes, or reorders a column.
-- Fragile: relies on the table's exact current column orderINSERT INTO Customers VALUES ('Alice', 'alice@example.com');
-- Robust: explicit column names, resilient to future schema changesINSERT INTO Customers (Name, Email) VALUES ('Alice', 'alice@example.com');Quick practice
Section titled βQuick practiceβ-
Why is specifying an explicit column list generally safer than relying on positional
VALUES?Answer
It's resilient to schema changes β if a column is added, removed, or reordered later, an explicit column list still inserts values into the correct places, while positional inserts can silently break or insert wrong data. -
What does
SCOPE_IDENTITY()return after anINSERTinto a table with anIDENTITYcolumn?Answer
The auto-generated identity value of the row just inserted, in the current session/scope. -
Can you insert the results of a
SELECTquery directly into another table?Answer
Yes βINSERT INTO TargetTable (columns) SELECT columns FROM SourceTable WHERE ...