Advertisement
❮ Previous: SQL Null Values Next: SQL Update ❯

SQL Insert Into

The SQL INSERT INTO statement is a Data Manipulation Language (DML) command used to add new records (rows) to a table within a relational database. Depending on your requirements, you can insert data into specific columns, populate an entire row, insert multiple records at once, or copy data directly from another table.

In simple words INSERT INTO statement is a core Data Manipulation Language (DML) command used to add new rows of data into an existing database table.


Insert into Specific Columns (Recommended)

This method explicitly maps your values to specific columns. It is the safest approach because it prevents your queries from breaking if the database schema changes later (such as adding new optional or auto-incremented columns).

INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);

Example:

INSERT INTO Customers (first_name, last_name, age, country)
VALUES ('Harry', 'Potter', 31, 'USA');

Why it's safe: If you add new columns to your database table down the road, this code structure will not break. It also allows you to skip columns that generate values automatically (like auto-incrementing primary IDs or default timestamps).


Advertisement

Insert into All Columns (Shorthand)

If you are adding values for every single column in the table, you can omit the column names. However, your values must strictly match the exact order of the columns as defined in the database schema.

INSERT INTO table_nameVALUES (value1, value2, value3, ...);

Example:

-- Assumes the table structure is exactly: ID, FirstName, LastName, Age, Country
INSERT INTO CustomersVALUES (5, 'Harry', 'Potter', 31, 'USA');

Warning: If the underlying table structure changes later (e.g., a column is added or rearranged), this query will throw an immediate syntax error.


Advertisement

Insert Multiple Rows at Once

Instead of executing a separate query for every row, you can bundle multiple rows into a single INSERT INTO statement by separating each VALUES group with a comma. This reduces database operations and runs much faster.

INSERT INTO Customers (first_name, last_name, country)VALUES 
    ('Ron', 'Weasley', 'UK'),
    ('Hermione', 'Granger', 'UK'),
    ('Luna', 'Lovegood', 'Ireland');

Advertisement

Insert Data From Another Table (INSERT INTO SELECT)

You can populate a table dynamically by copying data from a source table using a SELECT statement. The data types of the source and destination columns must match.

INSERT INTO Archive_Customers (customer_id, first_name, last_name)
SELECT customer_id, first_name, last_name
FROM Customers
WHERE country = 'UK';

Advertisement

💡 Crucial Rules to Remember


Key Syntax Rules to Keep in Mind

❮ Previous: SQL Null Values Next: SQL Update ❯
Advertisement