Result Set of a SELECT Query

We've seen informally in previous examples how the results of a SELECT statement are returned to you. The results of a query come back as rows-in-a-table, held in an object called a result set.

Contents of a result set

The result set contains zero or more rows which are retrieved and examined individually using something called a cursor. Just as a GUI cursor marks your position on the screen, a database cursor indicates the row of the result set that you are currently looking at. A cursor is usually implemented as an unsigned integer that holds the offset into the file containing your result set. It has enough knowledge to move forward row by row through the result set.

The cursor

Database management systems typically provide a cursor to the SQL programmer automatically. The programmer can use it to iterate through the result set. JDBC 2 upgrades the features of a cursor available to Java. Now you can move the cursor backward as well as forward, providing the underlying database supports that. You can also move the cursor to an absolute position (e.g., the fifth row in the result set) or to a position relative to where it is now (e.g., go to the immediate previous record).

Getting a sorted result set

We can ask for our result set to come to us sorted by some column or columns. We achieve this by using the “ORDER BY” clause in the query. When you do that, it makes sense to use the cursor to ask for the record before the one we are currently looking at. For example, if you order by “billing price” you can go backward until you reach orders under $10. That way, you can process your most valuable orders first, and stop invoicing when the amount is smaller than the cost of processing.

SELECT pitfalls

Here are some common pitfalls encountered when using the SELECT statement. When you hit an error in your programs in the next chapter, check if it is one of these!

  • Not surrounding a literal string in single quotes.

  • Spelling the table name or the column name wrongly.

  • Only mentioning the tables that you are extracting from in the “from” clause. You need to mention all the tables that you will be looking at in the “where” clause.

  • Failing to specify “distinct” and thus getting duplicate values in certain columns.

  • Failing to leave a space between keywords when creating a Java String on several lines containing SQL.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.245.167