SQL INSERT INTO: How to Add Rows to a Table
In this article
To add a row to a table, use the INSERT INTO statement: name the table, list the columns you are filling in parentheses, then supply the matching values in the same order. For example, INSERT INTO customers (first_name, last_name, email) VALUES ('Ana', 'Lopez', 'ana@example.com'); adds one row to the customers table. The column list is optional only when you are providing a value for every column in the table in the table's physical order, which is fragile and rarely worth doing. Everything below assumes you have a working database connection and the right to write to the table.
What You'll Need
- A database you can connect to (MySQL, PostgreSQL, SQL Server, SQLite, Oracle or similar) and a client such as the command-line tool, a GUI like DBeaver or pgAdmin, or your application's query console.
- The table name, spelled exactly, including its schema if the database uses schemas (for example
sales.orders). - The column names and their data types. Run a quick
DESCRIBE table_name;in MySQL or\d table_namein PostgreSQL to see them. - Values that match those types: numbers without quotes, text and dates in single quotes, and NULL written as the keyword NULL with no quotes.
- INSERT permission on the table. If you get a permission error, that is a grant issue, not a syntax issue.
Step-by-Step
- Confirm the table and its columns. Run a describe command or open the table's structure view. Note which columns are NOT NULL and which have defaults. Columns with defaults can be left out of the insert; NOT NULL columns without defaults must be supplied or the statement fails.
- Write the INSERT INTO clause. Start with
INSERT INTO table_name. Add the schema prefix if your client is not already pointed at the right database. - List the target columns in parentheses. Write them in the order you will supply values, for example
(first_name, last_name, email, signup_date). Always list columns explicitly: it protects you when someone adds a column to the table later, and it makes the statement readable. - Add the VALUES keyword and one set of parentheses per row. A single row looks like
VALUES ('Ana', 'Lopez', 'ana@example.com', '2024-05-01');. Multiple rows are separated by commas:VALUES ('Ana', ...), ('Ben', ...), ('Cara', ...);. Multi-row inserts are faster than one statement per row and are atomic in most engines. - Quote values correctly. Single quotes around strings and dates, no quotes around numbers, and NULL as a bare keyword. Escape an apostrophe inside a string by doubling it (
'O''Brien') or by using your client's parameter binding. - Match the count and order. The number of values must equal the number of listed columns, in the same order. This is the single most common cause of errors.
- Run the statement and check the result. The client reports something like "1 row affected" or "INSERT 0 1". Then verify with
SELECT * FROM table_name WHERE ...;using a unique value from the row you just added. - Commit if you are in a transaction. Many clients run in autocommit mode, but if you opened a transaction with BEGIN, the row is not visible to other sessions until you run COMMIT. Roll back with ROLLBACK if you made a mistake.
- Use parameterized inserts in application code. Instead of building the SQL string by concatenation, use placeholders:
INSERT INTO customers (first_name, email) VALUES (?, ?);in MySQL or SQLite,$1, $2in PostgreSQL. Bind the values in your language's driver. This prevents SQL injection and handles quoting for you. - Retrieve generated keys when needed. If the table has an auto-increment or identity primary key, ask the driver for the generated value after the insert rather than guessing it. In MySQL that is
LAST_INSERT_ID(); in PostgreSQL useINSERT ... RETURNING id;; in SQL Server useOUTPUT INSERTED.id.
Common Mistakes
- Column and value counts differ. Adding a column to the list but not a value, or vice versa, produces an error such as "Column count doesn't match value count".
- Forgetting quotes around text or dates. An unquoted word is read as a column name, and a date without quotes may be misparsed.
- Quoting numbers. Some engines will silently convert, others will reject the value. Match the column type.
- Omitting the column list. It works only until someone alters the table, then every insert without a column list breaks.
- Duplicate primary keys. Inserting an id that already exists fails with a unique constraint error. Let the database generate the key, or check first.
- Not-null violations. Leaving out a required column without a default fails the statement.
- String concatenation in code. Building SQL from user input is the classic injection hole; use parameters.
- Forgetting to commit. The row appears in your session but not to anyone else, and disappears if the connection drops.
Tips
- Test the statement inside a transaction on a development copy before running it against production.
- Insert in batches of a few hundred to a few thousand rows rather than one row per round trip, but keep batches small enough to fit in memory and to keep locks short.
- Use
INSERT ... SELECTto copy rows from another table in one statement instead of reading them into your application and sending them back. - If duplicates are expected, learn your engine's conflict handling:
INSERT ... ON CONFLICT DO NOTHINGin PostgreSQL and SQLite,INSERT IGNOREorON DUPLICATE KEY UPDATEin MySQL. These are not portable between engines. - Keep a unique key or a natural identifier in the row so you can verify the insert with a targeted SELECT afterwards.
- Store dates in ISO format (YYYY-MM-DD) to avoid regional ambiguity.
Troubleshooting
- Syntax error near a word. Usually a missing comma, a missing parenthesis, or a reserved word used as a column name without quoting. Check the exact position the error message points to.
- Column count doesn't match value count. Recount both lists. A trailing comma in the column list is a frequent culprit.
- Unknown column. The name is misspelled, the case differs (some engines are case-sensitive for quoted identifiers), or you are connected to the wrong database or schema.
- Duplicate entry for key. A unique or primary key already holds that value. Check the existing row, then either update it or insert with a new key.
- Cannot insert NULL. A required column was omitted or explicitly set to NULL. Supply a value or add a default to the column.
- Data too long or out of range. The value exceeds the column's length or numeric limits. Shorten it or change the column type deliberately.
- Permission denied. Your database user lacks INSERT on the table. Ask an administrator for the grant; do not try to work around it.
- Foreign key constraint fails. The referenced parent row does not exist yet. Insert the parent first, or check that the id you are referencing is correct.
- Row missing after insert. You are probably in an uncommitted transaction, or you are querying a different schema or connection.
Frequently Asked Questions
Can I insert multiple rows in one statement?
Yes. Put each row's values in its own parentheses and separate them with commas after a single VALUES keyword. This is supported by MySQL, PostgreSQL, SQL Server and SQLite.
Do I have to list the column names?
No, but you should. Without the list, the database expects a value for every column in the table's physical order, and the statement breaks as soon as the table structure changes.
How do I insert the current date and time?
Use the engine's function in place of a literal: NOW() in MySQL, CURRENT_TIMESTAMP in PostgreSQL and SQL Server, datetime('now') in SQLite. Alternatively, give the column a default and leave it out of the insert.
What is the difference between INSERT INTO and INSERT INTO ... SELECT?
The first supplies literal values; the second copies rows produced by a query. Use the SELECT form for moving or duplicating data between tables without pulling it through your application.
Why did my insert succeed but the row is not there?
Most often the transaction was never committed, or the row was written to a different schema, database or connection than the one you queried.
Is it safe to build INSERT statements with string concatenation?
No. Use parameterized queries or prepared statements so user input is bound as data, not parsed as SQL. This is the standard defense against SQL injection.