Cursor or application code?
I have a select query which gives me a huge output (number of records). I have to iterate through each record to do a certain action. Is it efficient to do it by manipulating the result set or should I define a cursor? I am using JDBC API and JAVA programs against an UDB database. Is there a rule of thumb for when to use cursors or when to manipulate result sets?

    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

You may have overlooked a third option: do the manipulation directly in SQL.

Predicting which of several methods will be most efficient is always a crapshoot. So much depends on how the database system has been configured, whether proper indexes have been defined, and so on. To be absolutely certain, you would need to test each method, obtain CPU and elapsed time totals for several runs of large magnitude, and compare timings.

That said, here's my rule of thumb:

  1. SQL
  2. cursor
  3. application code

Please use discretion, because it's not an absolute rule. For example, if by "manipulate the result set" you intend simply to sort it, then obviously option 1 is best (use an ORDER BY clause). On the other hand, if complex statistical calculations are required, sometimes option 3 is best (extract the data and dump it into a statistical analysis application). Unless you are forced, by the nature of the desired manipulation, to use application code, then the choice between option 1 and option 2 is almost always to look for an SQL solution, because cursors are by nature slower.


This was first published in October 2004

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.