SQL DML

SQL INSERT

Add new records to database tables using INSERT INTO statements.

The SQL INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table.

INSERT Syntax

You can write the INSERT INTO statement in two ways:

  1. Specify both the column names and the values to be inserted:

INSERT INTO table (col1, col2) VALUES (val1, val2);

  1. If you are adding values for all columns of the table, you do not need to specify the column names:

INSERT INTO table VALUES (val1, val2, ...);

Inserting Multiple Rows

You can insert multiple rows in a single INSERT statement, which is much more efficient than multiple separate INSERT statements.

INSERT ... SELECT

You can insert data from another table using INSERT ... SELECT.

Example

sql
-- Insert a single row
INSERT INTO users (name, email, role, created_at)
VALUES ('Alice Smith', 'alice@example.com', 'user', NOW());

-- Insert with defaults
INSERT INTO posts (title, content, author_id)
VALUES ('My First Post', 'Hello world!', 1);

-- Insert multiple rows
INSERT INTO tags (name, slug) VALUES
  ('Python', 'python'),
  ('JavaScript', 'javascript'),
  ('AI', 'artificial-intelligence'),
  ('Web Dev', 'web-development');

-- Insert and return the new ID
INSERT INTO orders (user_id, total, status)
VALUES (42, 99.99, 'pending')
RETURNING id, created_at;

-- Insert from another table
INSERT INTO archived_users (id, name, email)
SELECT id, name, email
FROM users
WHERE last_login < NOW() - INTERVAL '2 years';

-- Insert or ignore if exists (upsert)
INSERT INTO user_preferences (user_id, theme, lang)
VALUES (1, 'dark', 'en')
ON CONFLICT (user_id) DO NOTHING;

Want to run this code interactively?

Try in Compiler