A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgresql-insert-into.php below:

Website Navigation


Guide to Using INSERT INTO in PostgreSQL

Guide to Using INSERT INTO in PostgreSQLLast update on December 23 2024 07:39:12 (UTC/GMT +8 hours)

PostgreSQL: INSERT INTO Statement

The INSERT INTO statement in PostgreSQL is used to add new rows of data into a specified table. It’s one of the most commonly used commands in SQL, allowing you to insert a single row, multiple rows, or even data from another table using a subquery.

Syntax:

To insert a single row of data:

INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);

Here:

Insert Multiple Rows:

To insert multiple rows of data in one statement:

INSERT INTO table_name (column1, column2, ...)
VALUES 
    (value1a, value2a, ...),
    (value1b, value2b, ...),
    (value1c, value2c, ...);

Insert Using a Subquery

You can also insert data from another table using a SELECT query:

INSERT INTO table_name (column1, column2, ...)
SELECT other_column1, other_column2, ...
FROM other_table
WHERE condition;

Example 1: Basic Single Row insert

Code:

-- Insert a new product into the "products" table
INSERT INTO products (product_id, product_name, price)
VALUES (1, 'Laptop', 1000);

Explanation:

Example 2: Multiple Rows insert

Code:

-- Insert multiple rows into the "customers" table
INSERT INTO customers (customer_id, customer_name, country)
VALUES 
    (1, 'Alice', 'USA'),
    (2, 'Bob', 'Canada'),
    (3, 'Charlie', 'UK');

Explanation:

Example 3: Insert Data Using a Subquery

Code:

-- Insert data from one table into another using a SELECT query
INSERT INTO high_value_orders (order_id, customer_id, total)
SELECT order_id, customer_id, total
FROM orders
WHERE total > 10000;

Explanation:

Important Notes:

1. Auto-Increment Columns:

2. Default Values:

Code:

INSERT INTO employees (employee_id, employee_name, salary) 
VALUES (DEFAULT, ' Encarni Ovide’, 50000);

3. Error Handling with ON CONFLICT:

Code:

INSERT INTO products (product_id, product_name, price)
VALUES (1, 'Tablet', 500)
ON CONFLICT (product_id) DO UPDATE SET price = 500;

Summary:

The INSERT INTO statement in PostgreSQL is essential for adding data to tables, whether inserting a single row, multiple rows, or even data from other tables. Understanding how to use INSERT INTO effectively helps streamline database operations and manage data insertion workflows.

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4