Select subject if not empty, otherwise select text

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Select subject if not empty, otherwise select text

Post by Luke »

I am trying to write a query that selects the "subject" column unless that column is empty, in which case it should select the text "(No Subject)". Is there a function or something I can use in MySQL to accomplish something like this?

Code: Select all

SELECT
    UNLESS_IS_EMPTY(subject, '(No Subject)') -- Is there a function that does something like this?
FROM messages
WHERE
   ...
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: Select subject if not empty, otherwise select text

Post by Luke »

Heh, nevermind! I found the function I need. It's called "IF":

Code: Select all

SELECT
    IF(subject = '', '(No Subject)', subject) AS title
FROM messages
WHERE
   ...
Post Reply