DEV Community

Hong duc
Hong duc

Posted on

When query db should I check if data exists first then select it ?

I always just select data then check if returned data is null or not, but I wonder if that is a good way.
But if I check for data exists then that will make 2 call to db, 1 for check and 1 for select, is this good ?
Or maybe I just overthinking it :).
What are your though about this ?

Thank you

Top comments (2)

Collapse
 
molly profile image
Molly Struve (she/her)

I actually wrote a post that talks about tradeoffs of making lots of database hits even if they are simple. You might find it helpful!

In your scenario it really depends.

  • How many of these selects are you making?
    • If you are making millions then it might not be worth it to double up the hits.
  • How big is the expected data set you are going to get back?
    • If you have a large dataset coming back then it might be worth it to do the exists. If the dataset is small then it is probably not worth it.
Collapse
 
bgadrian profile image
Adrian B.G.

Depending on the storage and the query, most likely you will end up doing the same expensive operation, twice (network call + disk access). This optimization is done at the database level (with caching, indexing), the user (who makes the query) should not deal with it, exceptions occurs of course.