Search code examples
androidsqlsqlitecoalesce

Sql query issue with coalesce


I want to get string from three columns and I am using this query

String selectQuery = "select distinct coalesce(" + SENDERNAME + " , "+ SENDEREMAILID + " , " + SENDERMOBILENUMBER + ")  FROM "+ TABLE_REC ;

But if a perticular column has empty string it takes and shows it but if it null it is not accepting.

I want to check empty and null to not take into account. i.e. I want to show some string to the user instead of empty string.

Here are the images

These Shows the database and query

enter image description hereenter image description here

When I fetch records and if particular record with empty and not null then it shows empty string like this

enter image description hereenter image description here


Solution

  • COALESCE changes only NULL values, not empty strings.

    To be able to use another comparison, use CASE:

    SELECT CASE WHEN SenderName <> '' THEN SenderName ELSE 'empty' END FROM TableRec
    

    (The expression SenderName <> '' fails for both empty strings and NULLs.)

    To combine three fields, you must nest multiple CASE expressions:

    SELECT CASE WHEN SenderName <> ''
                THEN SenderName
                ELSE CASE WHEN SenderEmailId <> ''
                          THEN SenderEmailId
                          ELSE SenderMobileNumber
                     END
           END
    FROM TableRec