15 Things You Should Know about the ORDER BY Clause

Oracle ORDER BY Clause
  1. When multiple columns/expressions are specified in the ORDER BY clause, the precedence of sorting is left to right.

  2. The ORDER BY clause can order in ascending (ASC) or descending (DESC) sequence, or a mix of both. If ASC or DESC is not explicitly stated, then ASC is the default.

  3. ORDER BY ASC places NULL values at the end of the query results. ORDER BY DESC places null values at the start of the query results.

  4. Read more

MERGE: Insert New Rows, Update Existing Rows in One Shot

MERGE Statement in Oracle

Oracle’s MERGE statement is tailor-made for situations when you want to do an "upsert" i.e. update existing rows in a table or insert new rows depending on a match condition. This is typically the case when you have to synchronize a table periodically with data from another source (table/view/query). In place of 3 separate unwieldy INSERT, UPDATE and DELETE statements with conditional sub-queries, the all-in-one MERGE does the job in one shot.

Read more

How to Manage those Pesky NULLs when Sorting Data

ORDER BY NULLS LAST or FIRST

A typical query scenario: you want to sort data in descending order, say students arranged by their GMAT scores. Given a table student (id, name, score), what can be simpler than adding an ‘ORDER BY score DESC’ to the query?

If that’s what you thought, here’s a complication. There are some students who did not take the GMAT at all. Their scores in the table are not zero, they are NULL. Oracle’s ORDER BY..DESC in this situation could give you a nasty surprise with the result.

Here’s how the result will look with the ORDER BY…DESC clause:

Read more

The Magic Of ROWNUM

ROWNUM in Oracle SQL

The “ROWNUM greater than” query never fails to have an eye-popping effect  the first time anyone sees it. If you haven’t worked with ROWNUM in Oracle much before, be prepared!

First things first. What is ROWNUM?

ROWNUM is a pseudocolumn, assigning a number to every row returned by a query. The numbers follow the sequence 1, 2, 3…N, where N is the total number of rows in the selected set. This is useful when you want to do some filtering based on the number of rows, such as:

Read more

Why the SQL WITH clause is not exactly like a function definition

WITH Clause - Unreferenced Query

The SQL WITH clause is similar in concept to a function definition in procedural code. In a function, we factor the common code, put it all together at one place and call it as many times as needed in the main program. That’s precisely how we use the WITH clause in SQL – factor out the common subquery, put it all together at one place and call it as many times as needed in the main query.

BUT there is a difference.

Read more