Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WITH clause with INSERT statement in POSTGRESQL

I have a requirement in which I need to get one column from another table and insert that column data with some other data into another table.

Example:

If the cust_id='11' then I need to get the cust_code from cust table (let's say it returns cust_code='ABCD') and then use that cust_code with some other data to insert into table_1 like so:

WITH get_cust_code_for_cust_id AS (
    SELECT cust_code FROM cust WHERE cust_id=11
)

INSERT INTO public.table_1(
    cust_code, issue, status, created_on)
    VALUES (SELECT cust_code FROM get_cust_code_for_cust_id, 'New Issue', 'Open', current_timestamp)

But this query does not work as we haven't called the get_cust_code_for_cust_id query.

My preference is some query with WITH clause but any other answer will also be appreciated.

like image 693
Neeraj Wadhwa Avatar asked May 16 '18 07:05

Neeraj Wadhwa


People also ask

Can I use with clause in PostgreSQL?

You can use data-modifying statements (INSERT, UPDATE or DELETE) in WITH.

How do I run multiple inserts in PostgreSQL?

PostgreSQL INSERT Multiple Rows First, specify the name of the table that you want to insert data after the INSERT INTO keywords. Second, list the required columns or all columns of the table in parentheses that follow the table name. Third, supply a comma-separated list of rows after the VALUES keyword.

What does INSERT query return in PostgreSQL?

In an INSERT , the data available to RETURNING is the row as it was inserted. This is not so useful in trivial inserts, since it would just repeat the data provided by the client. But it can be very handy when relying on computed default values.

What's the fastest way to do a bulk INSERT into Postgres?

We recommend using the PostgreSQL COPY command to load data from one or more files. COPY is optimized for bulk data loads. It's more efficient than running a large number of INSERT statements or even multi-valued INSERTS.


1 Answers

If the source of an insert statement is a select do not use the VALUES keyword.

WITH get_cust_code_for_cust_id AS (
    SELECT cust_code 
    FROM cust 
    WHERE cust_id=11
)
INSERT INTO public.table_1 (cust_code, issue, status, created_on)
SELECT cust_code, 'New Issue', 'Open', current_timestamp 
FROM get_cust_code_for_cust_id;

You don't really need the CTE for this though:

INSERT INTO public.table_1 (cust_code, issue, status, created_on)
SELECT cust_code, 'New Issue', 'Open', current_timestamp  
FROM cust 
WHERE cust_id=11
like image 171
a_horse_with_no_name Avatar answered Oct 22 '22 14:10

a_horse_with_no_name