I am using PostgreSQL and I would like to update a table which would include an auto number column id. I know it might something very simple but I have done something like this;
CREATE SEQUENCE SEQ_ID
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
update trk2
set (id, track_id, track_point) =
(select nextval('seq_id'), trk1.track_fid, trk1.wkb_geometry
from track_points_1 as trk1
where track_fid = 0)
The thing is that it is giving me the following error (code reformatted):
ERROR: syntax error at or near "select"
LINE 3: set (id, track_id, track_point)=(select nextval('seq_id'), t...
Can anybody help please?
Your query is broken in several places. It could look something like this:
Or simpler (preferable syntax):
Major points:
An
UPDATEwithout aWHEREclause only makes sense if you really need to change each and every row in the table. Else it is wrong or at least sub-optimal.When you retrieve values from another table, you get a
CROSS JOINbetween target and source if you don’t add aWHEREclause connecting target with source – meaning that every row of the target table will be updated with every row in the source table. This can take a very long time and lead to arbitrary results. The lastUPDATEwins. In short: this is almost always complete nonsense and extremely expensive at that.In my example I link target and source by the
idcolumn. You have to replace that with whatever fits in your case.You can assign multiple values in one
SETclause in anUPDATE, but you can only return a single value from a correlated subselect expression. Therefore, it is strictly not possible to have a subselect in aSETclause with multiple values.Your initial syntax error comes from a missing pair of parenthesis around your subselect. But adding that only reveals the error mentioned above.
Depending on what you are after, you would include
nextval('seq_id')in the subquery or in theSETclause directly. This can lead to very different results, especially when you have rows in the subquery that are not used in theUPDATE.I placed it in the
SETclause because I suspect, that’s what you want. The sequence of rows is still arbitrary. If you want more control over which numbers are assigned, you need to define what you want and then take a different route.