Fastest check if row exists in PostgreSQL

前端 未结 8 1317
有刺的猬
有刺的猬 2020-11-28 19:20

I have a bunch of rows that I need to insert into table, but these inserts are always done in batches. So I want to check if a single row from the batch exists in the table

8条回答
  •  再見小時候
    2020-11-28 19:47

    How about simply:

    select 1 from tbl where userid = 123 limit 1;
    

    where 123 is the userid of the batch that you're about to insert.

    The above query will return either an empty set or a single row, depending on whether there are records with the given userid.

    If this turns out to be too slow, you could look into creating an index on tbl.userid.

    if even a single row from batch exists in table, in that case I don't have to insert my rows because I know for sure they all were inserted.

    For this to remain true even if your program gets interrupted mid-batch, I'd recommend that you make sure you manage database transactions appropriately (i.e. that the entire batch gets inserted within a single transaction).

提交回复
热议问题