Otaqui.Com

Pete Otaqui’s blog about web development and everything else

Selecting a Different Table Column if the Original Record is NULL in MYSQL Using IFNULL

one comment

MySQL’s documentation is OK, but it’s examples are sometimes quite poor.

I have a particular setup where values across two tables – a course table and a schedule table which relates to it – can be effectively “overridden”. The idea is that for any given course, one can set “default” values, and then these can be overridden every time a course is actually scheduled to happen.

The courses table looks something like this:

COURSES
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY
title VARCHAR(255) NOT NULL
subtitle VARCHAR(255) NOT NULL
description TEXT NOT NULL

SCHEDULES
id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY
course_id INT(11) NOT NULL
subtitle VARCHAR(255) NULL
description TEXT NULL

Hopefully you can see what I would want during a SELECT – to get the values from the schedules table if they aren’t null, or otherwise get the value from the courses table if they are.

This is achieved with the IFNULL built in function in MySQL. IFNULL takes two arguments, and returns the first argument if it (the first argument that is) is not null, or the second argument if it is. The actual SQL for my example looks like this:

SELECT courses.title, IFNULL(schedules.subtitle,courses.subtitle) AS subtitle, IFNULL(schedules.description,courses.description) AS description FROM schedules LEFT JOIN courses ON schedule.course_id=course.id;

This will give you the “subtitle” and “description” values from the linked table (schedules) if they exist, or the default values from the original table (courses) if they don’t.

Written by pete

February 5th, 2009 at 9:31 pm

Posted in Professional

Tagged with ,

One Response to 'Selecting a Different Table Column if the Original Record is NULL in MYSQL Using IFNULL'

Subscribe to comments with RSS or TrackBack to 'Selecting a Different Table Column if the Original Record is NULL in MYSQL Using IFNULL'.

  1. My Uncle (Uncle-In-Law?) Ian points out that you can also use COALESCE() in this case, which takes an arbitrary number of arguments and will return the first non-NULL value

    pete

    6 Feb 09 at 1:03 am

Leave a Reply