Understanding the INSERT Statement
When constructing an INSERT statement, you must specify the target table and the columns that need to be populated. In our example, the “products” table requires values for the “name” and “price” columns. Optional columns such as “is_sale” and “inventory” automatically default to false and zero, respectively, if not provided.Viewing Existing Data
Before inserting new data, it can be helpful to review the current entries in your table. You can do this using:Basic Syntax
The basic syntax for inserting a new row is:Ensure that the order of the columns in the INSERT statement exactly matches the order of the corresponding values provided.
Inserting a Single Row
Below is an example that inserts values into the “name”, “price”, and “inventory” columns. By omitting the “is_sale” column, PostgreSQL will use its default value (false):The “0” in the message represents the OID by default. The key takeaway is that one row was successfully inserted.To verify your insertion, run:
Matching Column and Value Order
It is crucial to accurately match the order of the columns with the corresponding values. Consider the following example where the order is rearranged:Using the RETURNING Clause
When developing APIs, you might want to immediately return the newly created row, including fields such as the creation timestamp and any auto-assigned default values. PostgreSQL’s RETURNING clause facilitates this:Inserting Multiple Rows
To insert multiple rows at once, separate each row’s values with commas. For example:Summary
This lesson has demonstrated how to create new entries in a PostgreSQL database using SQL INSERT statements. The key points include:- Using proper syntax and ensuring the order of columns matches the values.
- Leveraging default values for optional columns.
- Utilizing the RETURNING clause for immediate feedback.
- Inserting multiple rows in a single statement for efficiency.