Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL update every nth row

To do some testing on a new table field, I'd like to fake-up some values on existing records in my test database. I want to assign a value to every 8th record in a table. I can easily select every 8th record using this syntax:

select *
from 
  (select rownum rn
    , jeffs_field_to_update
  from jeff)
where mod(rn, 8) = 0;

However, I'm fairly new to SQL, and I can't seem to be able to convert this to an update statement. I see a lot of answers here about selecting nth records, but I've already got that. Any assistance would be appreciated.

like image 479
Travis Avatar asked Jun 21 '13 13:06

Travis


2 Answers

You need to join this to UPDATE statement on any key in the table. For example, if you have an unique id column, update statement will look like this:

update jeff
set jeffs_field_to_update = value
where id in
(select id
from 
  (select rownum rn
    , jeff.id
  from jeff)
where mod(rn, 8) = 0)
like image 100
Mikhail Avatar answered Nov 04 '22 00:11

Mikhail


A shorter answer:

UPDATE jeff 
SET jeffs_field_to_update = value 
WHERE mod(DBMS_ROWID.ROWID_ROW_NUMBER(ROWID), 8)=0;
like image 4
Aleksander Blomskøld Avatar answered Nov 03 '22 23:11

Aleksander Blomskøld