Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update table with limit and offset in postgres

hi is it possible to update a table with values form an other table with limit and offset?

for example the table t_device has 600 rows and t_object has 100 rows

i want to update a column but only the first 100 rows with an offset from a subquery like

update t_device set id_object = 
(select id_object from t_object limit 100) limit 100 offset 0;

update t_device set id_object = 
(select id_object from t_object limit 100) limit 100 offset 100;

is it possible? i cant find a solution to modive the value in t_device from t_object

im using postgres 8.4

like image 516
Ser Yoga Avatar asked Jul 09 '13 15:07

Ser Yoga


People also ask

How does limit and offset work in Postgres?

If a limit count is given, no more than that many rows will be returned (but possibly fewer, if the query itself yields fewer rows). LIMIT ALL is the same as omitting the LIMIT clause, as is LIMIT with a NULL argument. OFFSET says to skip that many rows before beginning to return rows.

How do I limit data in PostgreSQL?

The LIMIT clause can be used with the OFFSET clause to skip a specific number of rows before returning the query for the LIMIT clause. Syntax:SELECT * FROM table LIMIT n OFFSET m; Let's analyze the syntax above. The LIMIT clause returns a subset of “n” rows from the query result.

How do you use limit and offset?

To limit the number of rows returned by a select statement, you use the LIMIT and OFFSET clauses. In this syntax: The LIMIT row_count determines the number of rows ( row_count ) returned by the query. The OFFSET offset clause skips the offset rows before beginning to return the rows.

What is difference between limit and offset?

The limit option allows you to limit the number of rows returned from a query, while offset allows you to omit a specified number of rows before the beginning of the result set. Using both limit and offset skips both rows as well as limit the rows returned.


1 Answers

  • That UPDATE statement doesn't look like it is going to be much use if you are just setting id_object to id_object, albeit in a semi-random order.
  • If there is no unique WHERE predicate in the t_device table UPDATE statement, there is no guarantee that only 100 rows will be updated, which is what I assume the intent of the outer LIMIT is.
  • You should have an ORDER BY in the subquery to ensure you are not getting overlaps in rows.

Something like the following might work for you.

UPDATE t_device set id_object = t.id_object
FROM (select id_object from t_object order by id_object limit 100) t
WHERE t.id_object = t_device.id_object;
like image 136
bma Avatar answered Oct 15 '22 13:10

bma