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
Updatable CTEIf your CTE is based on a single table then you can update using CTE, which in turn updates the underlying table.
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.
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.
CTE can be used for both selects and DML (Insert, Update, and Delete) statements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With