Skip to content

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

twitter logo github logo ・1 min read  

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

twitter logo DISCUSS (2)
markdown guide

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.

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.

Classic DEV Post from Jun 14 '19

How do you organize your projects?

Where do you keep your side projects and portfolio?

Hong duc profile image
Job: Developer Languages: java,javascript,clojure

Sore eyes? now has dark mode.

Go to the "misc" section of your settings and select night theme ❀️