Rob's Blog

Postings from the world of Rob Ferrer
  • rss
  • Home
  • About
  • Gallery

MySQL Optimisation Trick using EXISTS

January 20, 2009 | 5:57 pm

One for the geeks I’m afraid.

I’m developing a site with quite a complicated menu system getting details using equally complicated database queries. In various places in the menu, I needed to find out whether to display a particular sub-menu. To do this I had some SQL to check whether any products existed at that particular point.

The SQL to do this took quite a while to execute (in one case over 30 seconds), which is obviously too long to wait to load a page.

I realised that my SQL statements were selected all appropriate products, where as they in fact only had to check whether any existed.

I could have just added a LIMIT to just return the first row, but if my statement had any ordering etc this wouldn’t help. I don’t want the first row (I don’t care about the data), just to know whether there is one. I knew there must be a better way.

I discovered EXISTS, which although isn’t documented very much, seems to do exactly what I want very simply. The solution is to surround my existing SELECT statement as follows:

SELECT 1 FROM DUAL WHERE EXISTS ( [SELECT statement here] )

That’s it. I can plug any SELECT statement I like in, and it tells me (very quickly) whether any results would be returned. A very useful trick I’m sure I’ll use in future.

Share This:
  • Digg
  • Facebook
  • del.icio.us
  • Google Bookmarks
  • email
  • MySpace
  • Reddit
  • StumbleUpon
  • Technorati
  • FriendFeed
  • Twitter

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Categories
Uncategorized
Tags
MySQL, SQL, web, Web Development
Comments rss
Comments rss
Trackback
Trackback

« Touchscreen Proof of Delivery – Why Bother? Dell offers huge 20 foot monitor! »

Leave a comment

You can use these tags : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CAPTCHA Image CAPTCHA Audio
Refresh Image

Links

  • Dell Special Offers
  • Ferrer Consulting Ltd
  • My LinkedIn Profile
  • Yuwie – social networking
  • Zopa

Tags

Android baby led weaning blogging cashback eBay email funny gadgets GDI GDI Goldrush Get Rich Quick google Google Wave Homepages Friends HTC Hero HTC Sense Isabel junk mail kayaking mobile MySearchFunds Norton Antivirus openid outdoors show Paternity phone photography post Post a Day rant review rodeo search security spam Symantec t-mobile the mobile outlet web Web Development welcome woopra wordpress WordPress 2.5 Yahoo

Recent Photos

DSC_0169.JPG
DSC_0158.JPG
DSC_0103.JPG
DSC_0098.JPG

Meta

  • Register
  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox