Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update with result from cte (postgresql)

I want to update job date if any records is an earlier date. Trying to use CTE to achieve this:

CREATE TABLE job     (jobid int4, jobdate date);  INSERT INTO job     (jobid, jobdate) VALUES     (1, '2016-02-01'),     (2, '2016-02-01'),     (3, '2016-02-01'),     (4, '2016-02-01') ;  CREATE TABLE rec     (recid int4, recjob int4, recdate date);  INSERT INTO rec     (recid, recjob, recdate) VALUES     (1,1,'2016-02-01'),     (2,2,'2016-01-01'),     (3,3,'2016-02-01'),     (4,4,'2016-02-01') ; 

Job number 2 have a record dated earlier than the job date. So I want to update this job with the record date.

WITH      cte AS           (SELECT jobid,least(min(recdate),jobdate) FROM      job LEFT JOIN rec ON recjob=jobid GROUP BY  jobid,jobdate HAVING    least(min(recdate),jobdate)<jobdate) 

Selecting the cte shows correct that job 2 should be updated

SELECT * FROM cte 

But updating gives an error: missing FROM-clause entry for table "cte"

UPDATE job  SET    jobdate=cte.date  WHERE  jobid IN (SELECT jobid FROM cte) 

SQLFiddle: http://sqlfiddle.com/#!15/e9ae6/8

I have never used cte with update, so I need some help to understand this.

TIA,

like image 780
sibert Avatar asked Apr 28 '16 07:04

sibert


People also ask

Can CTE be used for update statement?

Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE or MERGE statement. This clause can also be used in a CREATE VIEW statement as part of its defining SELECT statement.

Does CTE work in PostgreSQL?

In PostgreSQL, the CTE(Common Table Expression) is used as a temporary result set that the user can reference within another SQL statement like SELECT, INSERT, UPDATE or DELETE. CTEs are temporary in the sense that they only exist during the execution of the query.

Can we use with clause in PostgreSQL?

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


2 Answers

Try your UPDATE with the following syntax;

UPDATE job SET jobdate = cte.date FROM cte WHERE job.jobid = cte.jobid 
like image 173
William Avatar answered Sep 25 '22 03:09

William


The syntax is as follows:

WITH cte AS (     SELECT * FROM ... ) UPDATE table_to_update SET column_from_table_to_update = cte.some_column FROM cte WHERE table_to_update.id = cte.id 
like image 32
simPod Avatar answered Sep 22 '22 03:09

simPod