PostgreSQL INSERT INTO
The INSERT INTO
statement is used to add new rows of data into an existing PostgreSQL table. You can insert one row at a time or multiple rows in a single query.
Key Topics
1. Basic Syntax
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Always ensure that the values match the order and data types of the columns.
2. Inserting Multiple Rows
INSERT INTO table_name (column1, column2)
VALUES
(value1a, value2a),
(value1b, value2b),
(value1c, value2c);
Separate each set of values with a comma to insert multiple rows at once.
3. Using the RETURNING Clause
When you need to retrieve the inserted data (for example, auto-generated IDs), use the RETURNING
clause:
INSERT INTO employees (first_name, last_name)
VALUES ('John', 'Doe')
RETURNING emp_id;
Code Explanation: This query inserts a new employee and returns the auto-generated emp_id
value in one operation.
Best Practices
- Use explicit column lists to avoid mistakes when the table schema changes.
- Validate data before insertion to maintain data quality and integrity.
- Leverage the
RETURNING
clause to obtain inserted row data without extra queries.
Key Takeaways
- The
INSERT INTO
statement is fundamental for adding data to PostgreSQL tables. - You can insert multiple rows in a single statement for efficiency.
- Use
RETURNING
to capture auto-generated column values.