Category Archives: Database

Oracle Derived Columns In SELECT Statements

It seems that using a derived column in a SELECT statement, without a table alias can cause problems.

The following base statement executes error free:

  1. SELECT *
  2. FROM MyTable

This statement errors with ORA-00936: missing expression:

  1. SELECT TO_DATE(B, 'DD-MON-YYYY') - TO_DATE(A, 'DD-MON-YYYY'), *
  2. FROM MyTable

This slightly modified statement will execute as expected:

  1. SELECT TO_DATE(B, 'DD-MON-YYYY') - TO_DATE(a, 'DD-MON-YYYY'), mt.*
  2. FROM MyTable mt

Initially, the idea of changing the order of the fields came to mind; it didn’t help. After adding in the alias and checking with a colleague – it worked. I don’t know why the derived column causes problems, however I thought it interesting none the less.

Oracle COALESCE Function

Oracle implements many convenient functions to handle NULL values in the database, one of which is the COALESCE function. The Oracle COALESCE function accepts a varying length list of arguments and returns the first non-NULL value in the list. If all arguments in the list evaluate to a NULL value, then the COALESCE function will return a NULL value.

The standard format for the COALESCE function is:

  1. COALESCE(arg1, arg2, ..., argN)

There are many practical uses for the Oracle COALESCE function, two common actions include:

  1. Passing in a list of common items, which may or may not have data in them in a hope you’ll get back something which you can use.
  2. Generating a default value for a field which contains NULL values.

As a simple, yet practical example of how to use the COALESCE function; following demonstrates how to substitute in a default value in a SELECT statement when there are NULL values present:

  1. SELECT COALESCE(ADDRESS2, 'EMPTY') FROM ADDRESSES

Since there is always more than one way to achieve the same outcome, the following two statements will return the same results as the previous example:

  1. SELECT DECODE(ADDRESS2, NULL, 'EMPTY', ADDRESS2) FROM ADDRESSES
  2. SELECT CASE WHEN ADDRESS2 IS NULL THEN 'EMPTY' ELSE ADDRESS2 END FROM ADDRESSES

The next time you’re dealing with NULL values and you’d prefer a nicer looking result; consider giving the COALESCE function a try.

WordPress Plugin: Hicksdesign Style Archives

The Hicksdesign Style Archives plugin now has a permanent URL.

Looking for a better way of displaying your blog archive list than a list of links to your monthly archive pages? There are many ways to display an archive list of posts, most common is a series of links to your ‘monthly archive’ pages. While perfectly functional, it just wasn’t working for me.

After looking around, I really liked the way that Jon Hicks displays his blog archive list. Using Jon’s method gives a little more substance to an otherwise fairly sparse page and the post titles break up the page nicely with their varying length.

Usage

  1. Download arl_hicksdesign_archives.zip
  2. Unzip the file locally
  3. Upload arl_hicksdesign_archives.php into your plugins folder (normally: /wp-content/plugins/)
  4. Enable the plugin via your administration console
  5. Edit your appropriate WordPress template file and add a call to arl_hicksdesign_archives()

Download

Zip: arl_hicksdesign_archives.zip
Source: arl_hicksdesign_archives.phps

ChangeSet

  • 2006-05-01:
    • Implemented get_permalink() to fix bug
    • Implemented get_month_link() to fix potential bug
  • 2006-04-29: Fixed spelling mistake in plugin name, arl_hicksdesign_archives().
  • 2006-04-26: Initial release.

Oracle DECODE Function

The Oracle DECODE function provides similar functionality to an IF-THEN-ELSE statement. The general format for an Oracle DECODE function is:

DECODE(expression, value1, result1 [, valuen, resultn], [default])

In the above example, expression represents what you want to evaluate. The valueX fields represent what you would like expression evaluated against, while the resultX fields are the values you want substituted if a match is found.

Anything you can do with an Oracle DECODE function, you could just as easily achieve with an IF-THEN-ELSE block. You would normally use a DECODE function over the IF-THEN-ELSE when you have a simple comparison or you prefer the readability of a DECODE function.

As a practical example, consider the small block of data below which might represent a subset of data from a multi-user system.

userid username power
10 john 1
11 cameron 2
12 al 5
13 simon 4
14 lucas 0
15 sally 3

If you issued the following SQL statement against that data, you should expect the output below:

SELECT userid, username, DECODE(power, 1, 'Registered', 2, 'Trusted', 3, 'Moderator', 4, 'Author', 5, 'Administrator', 'Pleb') As status FROM Users;

userid username status
10 john Registered
11 cameron Trusted
12 al Administrator
13 simon Author
14 lucas Pleb
15 sally Moderator

The caveat of using the Oracle DECODE function is that the expression must evaluate to a single value. As such, you can not use an evaluation which has multiple possible values. In such a circumstance, you would need to find a way (read: algorithm) to make each possible value evaluate to a single value. By doing so however, you are removing the simplicity of the DECODE function and an IF-THEN-ELSE block would probably suit better.

Next time you’re going to reach for the trusty IF-THEN-ELSE block by default, consider using a DECODE function – in the right circumstances, it’ll make your SQL simpler.

Oracle RETURNING Clause

The Oracle RETURNING clause was implemented as part of the Oracle 10g release and is used to return information about the effected rows after issuing Data Manipulation Language (DML) statements. Prior to Oracle 10g, you would have needed to work around not having this feature, most likely by issuing additional statements to the database.

The RETURNING clause has a few restrictions:

  • it is only available for use on tables, materialised views, normal views based on a single table or an expression based on the previous three items
  • it is only valid on a single-set aggregate. A single set aggregate is DML which only effects a single row or using an aggregate function in the RETURNING statement (such as SUM).

The general syntax for the RETURNING clause is:

INSERT INTO <table> (c1, c2, .., cn) VALUES (v1, v2, .., vn) RETURNING <expression> INTO <variables>
UPDATE <table> SET (c1) = (v1), (c2) = (v2), (cn) = (vn) WHERE <condition> RETURNING <expression> INTO <variables>
DELETE FROM <table> WHERE <condition> RETURNING <expression> INTO <variables>

This feature is particularly useful when INSERTing into a table, where the Primary Key is sourced from a sequence and fetched via a TRIGGER. In the below example, the ID of the newly inserted row is assigned to pContactID using the RETURNING clause. This is an elegant solution as it means you don’t have to SELECT the NEXTVAL from the sequence and assign that value to the ContactID during INSERT simply so you can return the new primary key value.

PROCEDURE Ins
(pContactID     OUT Contacts.ContactID%TYPE,
 pFirstname     IN Contacts.Firstname%TYPE,
 pSurname       IN Contacts.Surname%TYPE)
IS
BEGIN
 INSERT INTO Contacts
 (fname, sname)
 VALUES
 (pFirstname, pSurname)
 RETURNING ContactID INTO pContactID;
END;

You could just as easily use it to return the information about a row deleted, such as:

PROCEDURE Del
(pContactID     IN Contacts.ContactID%TYPE,,
 pFirstname     OUT Contacts.Firstname%TYPE,
 pSurname       OUT Contacts.Surname%TYPE)
IS
BEGIN
 DELETE FROM Contacts
 WHERE ContactID = pContactID
 RETURNING fname, sname INTO pFirstname, pSurname;
END;

Since the RETURNING clause is for use with aggregates, an example illustrating its use is in order. The below example modifies pContactID salary by pPercentageChange and subsequently returns the updated total company salary expenditure.

PROCEDURE UpdateSalary
(pContactID        IN Contacts.ContactID%TYPE,
 pPercentageChange IN NUMBER,
 pGrossSalary      OUT NUMBER)
IS
BEGIN
 UPDATE Contacts
 SET salary = salary * pPercentageChange
 WHERE ContactID = pContactID
 RETURNING SUM(salary) INTO pGrossSalary;
END;

The Oracle RETURNING clause provides the PL/SQL developer with a lot of flexibility. The real benefits however, come from the simplified PL/SQL and clarity gained in the code. If you’ve got a lot of application code or PL/SQL which isn’t utilising the power available to you – it might be time to undertake a clean up in your project.