Skip to content

Instantly share code, notes, and snippets.

@tetafro
Created March 23, 2017 12:13
Show Gist options
  • Save tetafro/a10ecca2172a7483e2f9c2c4463907a8 to your computer and use it in GitHub Desktop.
Save tetafro/a10ecca2172a7483e2f9c2c4463907a8 to your computer and use it in GitHub Desktop.
Iterate over table rows to find corrupted one

Taken from here.

Query iterates over rows of table my_table. The last printed ctid - is the last before corrupted row. After getting this value ('(78498,1)' for example) you should check the next one ('(78498,2)' for example):

SELECT * FROM my_table WHERE ctid = '(78498,2)';

And then delete it.

$$ DO
DECLARE
result tid;
curs refcursor;
ctids record;
tmp_row record;
count bigint;
BEGIN
OPEN curs FOR EXECUTE 'SELECT ctid FROM tbl_las_tin';
count = 1;
FETCH curs INTO ctids;
WHILE ctids.ctid IS NOT NULL LOOP
count = count + 1;
result = ctids.ctid;
FETCH curs INTO ctids;
EXECUTE 'SELECT (each(hstore(my_table))).* FROM my_table WHERE ctid = $1'
INTO tmp_row
USING ctids.ctid;
IF count % 100 = 0 THEN
RAISE NOTICE 'rows processed: %', count;
END IF;
END LOOP;
CLOSE curs;
RAISE NOTICE 'No errors found';
EXCEPTION
WHEN OTHERS THEN
RAISE NOTICE 'LAST CTID: %', result;
RAISE NOTICE '%: %', SQLSTATE, SQLERRM;
END
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment