Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL INSERT INTO: Add New Rows to a Table

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To insert new values into a SQL table, use the INSERT INTO statement. The shortest working form is INSERT INTO table_name (column1, column2) VALUES (value1, value2);. You list the table, the columns you are filling, and the matching values in the same order. If you omit the column list, you must supply a value for every column in the table's defined order, which is fragile and easy to break when the schema changes.

What You'll Need

  • A database connection with permission to write to the target table (INSERT privilege).
  • The exact table name and column names, including spelling and case where the database is case-sensitive.
  • Knowledge of each column's data type and any constraints (NOT NULL, UNIQUE, foreign keys, defaults, auto-increment).
  • A SQL client or command-line tool such as psql, mysql, sqlite3, SQL Server Management Studio, or a web admin panel.
  • A backup or a test copy of the table if you are inserting in bulk or into production.

Step-by-Step

  1. Inspect the table structure first. Run a describe command for your database, for example DESCRIBE table_name; in MySQL, \d table_name in psql, or query the information schema. Note which columns are required, which have defaults, and which auto-generate values. This prevents most insert errors before you write a single row.
  2. Write the INSERT with an explicit column list. Name only the columns you are supplying. For example: INSERT INTO customers (first_name, last_name, email) VALUES ('Ana', 'Lopez', 'ana@example.com'); Columns you leave out must either allow NULL or have a default value; otherwise the statement fails.
  3. Match values to columns in order. The first value goes to the first named column, the second to the second, and so on. Text and date values go in single quotes; numbers do not. Use the database's standard date format, commonly 'YYYY-MM-DD', and avoid regional formats that can be misread.
  4. Handle special characters and quotes. Escape a single quote inside a string by doubling it ('O''Brien') or by using your client's parameter binding. Never build SQL by concatenating raw user input; use prepared statements or parameterized queries to prevent SQL injection and quoting bugs.
  5. Run the statement and check the result. Most clients report the number of rows affected. If it says 1 row inserted, verify with a SELECT filtered on the new values. If it says 0, the statement was likely rolled back or hit a constraint.
  6. Insert multiple rows in one statement where supported. The standard multi-row form is INSERT INTO table_name (col1, col2) VALUES (v1, v2), (v3, v4), (v5, v6); This is faster than many single-row statements and is atomic in most databases. Check your database's limit on statement size for very large batches.
  7. Use INSERT ... SELECT for copying data. When the values come from another table or a query, write INSERT INTO target (col1, col2) SELECT col1, col2 FROM source WHERE ...; Confirm the SELECT returns the rows you expect before running the insert.
  8. Commit or roll back deliberately. If your client is in manual-commit mode, run COMMIT; to save the change or ROLLBACK; to undo it. In autocommit mode the change is saved immediately, so test on a copy first when in doubt.
  9. Confirm constraints and generated keys. If the table has an auto-increment or identity column, retrieve the new key using your database's return mechanism (for example RETURNING id in PostgreSQL or SCOPE_IDENTITY() in SQL Server) rather than guessing the next number.

Common Mistakes

  • Omitting the column list and then adding a column to the table later, which shifts every value into the wrong field.
  • Mismatching value count and column count; the database rejects the statement, but the error message can be vague.
  • Forgetting quotes around text or dates, or using double quotes for string literals in databases where double quotes mean identifiers.
  • Inserting NULL into a NOT NULL column, or a duplicate into a UNIQUE column, which fails the whole statement.
  • Assuming an insert succeeded without checking the affected-row count or running a verification SELECT.
  • Building SQL by string concatenation with user input, which invites injection and breaks on apostrophes.

Tips

  • Always name columns explicitly. It makes statements self-documenting and resilient to schema changes.
  • Use parameterized queries in application code; they handle quoting and types for you.
  • Test bulk inserts inside a transaction on a staging copy, then commit only after a row count and spot-check SELECT.
  • Keep a short script of your verification queries so you can confirm inserts quickly after deployment.
  • Let the database generate IDs and timestamps with defaults rather than supplying them manually.

Troubleshooting

If the insert fails, read the error text closely: it usually names the column, constraint, or value type at fault.

  • Column count doesn't match value count: recount both lists; a missing comma is a common cause.
  • Cannot insert NULL: supply a value for that column or add a default to the table if appropriate.
  • Duplicate key: the value already exists in a UNIQUE or primary key column. Check with a SELECT, then update instead of insert, or use your database's upsert form (for example INSERT ... ON CONFLICT DO NOTHING in PostgreSQL or ON DUPLICATE KEY UPDATE in MySQL).
  • Foreign key violation: the referenced row does not exist yet; insert the parent row first.
  • Data too long or invalid type: check the column's defined length and type, and trim or convert the value.
  • Permission denied: your database user lacks INSERT on the table; ask an administrator to grant it.
  • Statement seems to do nothing: you may be in a transaction that was rolled back, or connected to a different database or schema than you think. Check the active connection and run a SELECT.

Frequently Asked Questions

Can I insert a row without listing every column?

Yes, if the omitted columns allow NULL or have defaults. Name the columns you are filling explicitly so the database knows where each value belongs.

How do I insert the current date and time?

Use the database's function, such as CURRENT_TIMESTAMP or NOW(), or define a default on the column and omit it from the insert. Exact function names vary by database.

What is the difference between INSERT and INSERT ... SELECT?

INSERT ... VALUES adds literal values you supply. INSERT ... SELECT copies rows returned by a query, which is useful for moving or duplicating data between tables.

How do I get the ID of the row I just inserted?

Use your database's return mechanism, such as RETURNING id in PostgreSQL or SCOPE_IDENTITY() in SQL Server. Do not assume the ID is the previous maximum plus one.

Can I undo an insert?

Only before you commit, by running ROLLBACK;. After a commit, you must delete the row or restore from backup. Test bulk inserts on a copy first.

Why does my insert fail with a duplicate key error?

A UNIQUE or primary key column already holds that value. Query the table to confirm, then update the existing row or use an upsert form supported by your database.