Smart Systems for Home

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

PostgreSQL INSERT: How to Add Data to a Table

· 4 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 values into a PostgreSQL table, use the INSERT INTO statement: INSERT INTO table_name (column1, column2) VALUES (value1, value2);. This adds one or more rows to an existing table. You need a PostgreSQL database, a table, and a user with INSERT privilege. The steps below cover the syntax, variations, and common pitfalls.

What You'll Need

  • A PostgreSQL server (local or remote) and a database.
  • A table with defined columns and data types.
  • A user role with INSERT privilege on that table.
  • A client tool: psql, pgAdmin, or any PostgreSQL-compatible driver.

Step-by-Step

  1. Connect to your database. Using psql, run psql -U username -d dbname and enter your password. In pgAdmin, expand the server, right-click the database, and choose Query Tool. Labels may differ slightly by version or client.
  2. Confirm the table structure. Run \d table_name in psql or inspect the table in pgAdmin. Note column names, data types, and any NOT NULL or default constraints. This prevents type mismatches and missing required values.
  3. Write a basic INSERT with column names. Use the syntax INSERT INTO table_name (col1, col2) VALUES (val1, val2);. Listing columns explicitly is safer than relying on column order, which can change if the table is altered.
  4. Match values to data types. Enclose text and date values in single quotes (e.g., '2025-01-01'). Use unquoted numbers for numeric columns. For boolean, use TRUE or FALSE. For NULL, write NULL without quotes.
  5. Insert multiple rows in one statement. Add comma-separated value tuples: INSERT INTO table_name (col1, col2) VALUES (val1a, val2a), (val1b, val2b);. This is more efficient than separate statements.
  6. Use RETURNING to get generated values. Append RETURNING id; (or another column) to retrieve auto-generated keys or defaults. For example: INSERT INTO users (name) VALUES ('Alice') RETURNING id;.
  7. Handle defaults and omitted columns. If a column has a default or is nullable, you can omit it from the column list. To explicitly insert a default value, use the DEFAULT keyword in the VALUES list.
  8. Execute the statement. In psql, end with a semicolon and press Enter. In pgAdmin, click the Execute button. Check the output for INSERT 0 1 (one row inserted) or an error.
  9. Verify the inserted data. Run SELECT * FROM table_name WHERE ...; to confirm the row appears as expected. Use a WHERE clause to narrow results.

Common Mistakes

  • Omitting the column list. Relying on column order can break if the table schema changes. Always specify columns unless you are certain of the order and all columns are provided.
  • Mismatched quotes. Using double quotes for string literals causes errors; double quotes are for identifiers. Use single quotes for text values.
  • Forgetting the semicolon. In psql, a statement without a semicolon is not executed. The prompt changes to indicate continuation.
  • Violating constraints. Inserting NULL into a NOT NULL column, duplicate values into a UNIQUE column, or values that fail a CHECK constraint will raise errors. Review constraints with \d table_name.
  • Type mismatches. Inserting a string into an integer column or a date in the wrong format fails. Use explicit casts if needed, e.g., '123'::integer.
  • Ignoring permissions. If you get a permission denied error, your role lacks INSERT privilege. Ask an administrator to grant it.

Tips

  • Use parameterized queries in application code to prevent SQL injection and handle quoting automatically.
  • Wrap multiple INSERTs in a transaction (BEGIN; ... COMMIT;) to ensure all-or-nothing behavior.
  • For bulk loading, consider COPY or \copy in psql, which is faster than many INSERT statements.
  • Use ON CONFLICT to handle unique violations gracefully, e.g., INSERT ... ON CONFLICT (id) DO NOTHING;.
  • Test INSERT statements in a development database before running them in production.

Troubleshooting

If the INSERT fails, read the error message carefully. Common errors include:

  • Syntax error: Check for missing commas, parentheses, or semicolons. Ensure VALUES is spelled correctly.
  • Column does not exist: Verify column names with \d table_name. Names are case-sensitive if quoted; unquoted names are folded to lowercase.
  • Null value in column violates not-null constraint: Provide a value for that column or alter the table to allow NULLs if appropriate.
  • Duplicate key value violates unique constraint: The value already exists. Use ON CONFLICT or choose a different value.
  • Permission denied for table: Grant INSERT privilege: GRANT INSERT ON table_name TO username;.
  • Invalid input syntax for type: The value cannot be cast to the column type. Check formatting, especially for dates and numbers.

If you are unsure, run the statement with EXPLAIN (for SELECT) or check the PostgreSQL documentation for the exact syntax. For permission issues, contact your database administrator.

Frequently Asked Questions

How do I insert a row with only some columns filled?

List only the columns you want to populate; omitted columns receive their default values or NULL if no default and nullable.

Can I insert multiple rows at once?

Yes, use multiple parenthesized value tuples separated by commas after VALUES.

How do I get the ID of the inserted row?

Use the RETURNING clause, e.g., INSERT ... RETURNING id;.

What if I don't know the column order?

Always specify column names in the INSERT statement to avoid relying on order.

How do I insert a date or timestamp?

Use a string literal in ISO format, e.g., '2025-01-01' for date or '2025-01-01 12:00:00' for timestamp.

Can I insert data from another table?

Yes, use INSERT INTO table_name (columns) SELECT ... FROM other_table;.