Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequential Scan and Index Scan for primary key return different rows

Tags:

sql

postgresql

I have problem with the data in my table users. This table has a primary key defined as:

"primary_c26a3d1a9d1c7aa4bb0a8d6b752c01a7" PRIMARY KEY, btree (id)

When I use a WITH clause to force a sequential scan on the table, I find duplicate IDs:

=> WITH temp_table AS (select * from "users") SELECT id from temp_table group by id having count(id) > 1;
-[ RECORD 1 ]
id | 8225700
-[ RECORD 2 ]
id | 8225682
...

How does this happen? If I search for these duplicates by index, I don't have the same problem:

=> select count(*) from users where id = 8225700;
-[ RECORD 1 ]
count | 1

I am using PostgreSQL 9.1.

VACUUM did not help me. I tried to delete duplicates by ctid:

// good and bad rows
> with usrs as (select ctid, * from users) select ctid, id from usrs where id = 8225700;
ctid     |   id    
-------------+---------
(195669,33) | 8225700
(195708,34) | 8225700

// good row
select id, ctid from users where id = 8225700;
-[ RECORD 1 ]-----
id   | 8225700
ctid | (195708,34)

// deleting bad row
DELETE FROM users WHERE ctid = '(195669,33)';
ERROR:  update or delete on table "users" violates foreign key constraint   "foreign_1589fcbc580d08caf03e0fbaaca7d6dd" on table "account"

In detail: Key (id)=(8225700) is still referenced from the account table.

But the real row has references and I can't delete it.

How can I delete these broken rows?

like image 384
Yegor Lukash Avatar asked Jun 04 '14 09:06

Yegor Lukash


1 Answers

// deleting bad row DELETE FROM users WHERE ctid = '(195669,33)';
ERROR:  update or delete on table "users" violates foreign key
constraint   "foreign_1589fcbc580d08caf03e0fbaaca7d6dd" on table
"account"

In detail: Key (id)=(8225700) is still referenced from table
"account".

It says quite clearly: The row is referenced by account table.

You need to locate the reference and fix it.

UPDATE account SET fkey_field = ??? WHERE ... ;

Details depend on structure and contents of account table.

If you want more help, please paste full output of \d account and \d users from psql.

like image 130
filiprem Avatar answered Oct 03 '22 13:10

filiprem