The `INSERT` statement in PostgreSQL is used to add new rows of data into a specified table. It is a fundamental operation for populating and updating databases with new information.
Usage
The basic syntax of the `INSERT` statement is used when you need to add new records to a table. It specifies the table name, the columns to insert data into, and the corresponding values.
In this syntax, `table_name` is the target table, `column1, column2, ...` are the columns to receive the data, and `value1, value2, ...` are the actual data values to be inserted.
Here, two rows are inserted into the `products` table in one statement, each with a `product_name` and `price`.
3. Insert with Subquery
sql
INSERTINTOsales(product_id, quantity)SELECT product_id,5FROM products
WHERE product_name ='Product C';提供:
This example inserts data into the `sales` table by selecting `product_id` from the `products` table where the `product_name` is 'Product C', setting the `quantity` to 5.
The `RETURNING` clause is used to return the `order_id` of the newly inserted row, which is especially useful with auto-increment fields.
Tips and Best Practices
Specify columns explicitly. Always list the columns in an `INSERT` statement to ensure clarity and maintain compatibility if the table structure changes.
Validate data types. Ensure that the values being inserted match the data types of the columns.
Use transactions for bulk inserts. Wrap multiple `INSERT` operations in a transaction to ensure atomicity and improve performance. For example:
The `INSERT` statement in PostgreSQL is used to add new rows of data into a specified table. It is a fundamental operation for populating and updating databases with new information.
Usage
The basic syntax of the `INSERT` statement is used when you need to add new records to a table. It specifies the table name, the columns to insert data into, and the corresponding values.
In this syntax, `table_name` is the target table, `column1, column2, ...` are the columns to receive the data, and `value1, value2, ...` are the actual data values to be inserted.
Examples
1. Basic Insert
This example inserts a single row into the `employees` table with values for `first_name`, `last_name`, and `email`.
2. Insert Multiple Rows
Here, two rows are inserted into the `products` table in one statement, each with a `product_name` and `price`.
3. Insert with Subquery
This example inserts data into the `sales` table by selecting `product_id` from the `products` table where the `product_name` is 'Product C', setting the `quantity` to 5.
4. Handling Duplicates with ON CONFLICT
This example demonstrates handling potential duplicates by updating the `email` if the `username` already exists in the `users` table.
5. Using RETURNING Clause
The `RETURNING` clause is used to return the `order_id` of the newly inserted row, which is especially useful with auto-increment fields.
Tips and Best Practices