DEV Community

Hong duc
Hong duc

Posted on

2 1

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.

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging β†’

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay