Friday, February 04, 2005

Encapsulation is not information hiding

Excellent article describing the difference between Encapsulation and Information hiding with real life example. Read it.

Saturday, January 15, 2005

ROWNUM Pseudocolumn with ORDER BY

In Oracle to limit the number of rows return we use ROWNUM in the WHERE clause. Suppose if we want first 10 rows of emp table, then the sql query will be something like

SELECT id, name FROM emp WHERE ROWNUM < = 10


And if we want sorted result then might be ( as i thought for first time)

SELECT id, name FROM emp WHERE ROWNUM < = 10 ORDER BY name

The above query does not work as we want. The WHERE clause is applied before the ORDER BY clause. Oracle picks the first 10 rows and then applies ORDER BY on them. We need to first sort the data and then select the first 10 rows. Here is the query:

SELECT id, name FROM (SELECT id, name FROM emp ORDER BY name) WHERE ROWNUM<=10


You have to do this if the column in ORDER BY clause is non-primary key. If the column is primary key then simple query will do. Look at the below sql query

SELECT id, name FROM emp WHERE ROWNUM < = 10 ORDER BY id DESC

here id is primary key.

Also one more thing i noticed that we cannot use greater than(>) operator with ROWNUM. The query returns zero rows.