SQL INSERT

Basic INSERT INTO

INSERT INTO customers (name, city)
VALUES ('Alice', 'New York');

Inserts a new customer named Alice in New York.

Specifying Columns

INSERT INTO products (product_name, price)
VALUES ('Laptop', 999.99);

Only the specified columns are filled; others must allow NULL or have defaults.

Inserting Multiple Rows

INSERT INTO employees (name, department)
VALUES 
  ('Tom', 'Sales'),
  ('Jerry', 'Marketing'),
  ('Sam', 'Support');

This adds three rows at once.

Inserting NULLs and Defaults

INSERT INTO users (username, email)
VALUES ('admin', NULL);

You can use NULL explicitly, or omit columns that use DEFAULT values.

INSERT from SELECT

INSERT INTO archived_orders (id, customer_id, total)
SELECT id, customer_id, total
FROM orders
WHERE status = 'completed';

Copies completed orders into the archive.

Best Practices

  • Always specify column names to avoid mismatch errors
  • Use parameterized queries in production code
  • Wrap batch inserts in transactions when necessary

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic