Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I update a cte?

Using CTE I try doing

WITH cte as ( 
     SELECT myFieldName, 
            row_number() over (order by gps_device_id) as rn
     FROM tracker.gps_devices
) 
UPDATE cte
SET cte.myFieldName = CASE WHEN cte.rn % 3  = 0  THEN '0'
                           WHEN cte.rn % 3  = 1  THEN '1'
                           WHEN cte.rn % 3  = 2  THEN '2'
                       END

But got the following error.

ERROR: relation "cte" does not exist

Looks like I can do INSERT and DELETE after WITH but UPDATE only inside the cte, is that correct? Im sure I did something like this, but maybe was in a different db.

https://www.postgresql.org/docs/9.6/static/queries-with.html

So I end with this, even when work is very confusing, any suggestion?.

UPDATE tracker.gps_devices g
SET g.myFieldName = CASE WHEN t.rn % 3  = 0  THEN '0'
                         WHEN t.rn % 3  = 1  THEN '1'
                         WHEN t.rn % 3  = 2  THEN '2'
                    END
FROM (SELECT gps_device_id,
             myFieldName,
             row_number() over (order by gps_device_id) as rn
      FROM tracker.gps_devices) as t
WHERE g.gps_device_id = t.gps_device_id
like image 858
Juan Carlos Oropeza Avatar asked Nov 02 '16 03:11

Juan Carlos Oropeza


People also ask

Can you do an update with a CTE?

Updatable CTEIf your CTE is based on a single table then you can update using CTE, which in turn updates the underlying table.

Can I insert into a CTE?

You can also use CTE to insert data into the SQL table. The CTE query definition includes the required data that you can fetch from existing tables using joins. Later, query CTE for inserting data into the target table.

Can I use a CTE twice?

Unlike a derived table, a CTE behaves more like an in-line view and can be referenced multiple times in the same query. Using a CTE makes complex queries easier to read and maintain. Because a CTE can be referred to multiple times in a query, syntax can be simpler.

Can we perform DML on CTE?

CTE can be used for both selects and DML (Insert, Update, and Delete) statements.


1 Answers

You can use cte for update, e.g. (assuming that id is a primary key):

with cte as ( 
    select 
        id, 
        my_field_name, 
        row_number() over (order by gps_device_id) as rn
    from gps_devices
) 
update gps_devices
set my_field_name = (rn % 3)::text
from cte
where gps_devices.id = cte.id;

You can insert, update or delete rows of a table (view) rather than a resultset of a query.

like image 198
klin Avatar answered Sep 29 '22 05:09

klin