DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Roger has posted 34 posts at DZone. View Full User Profile

How To Use Case Expression On SQL Select

11.06.2009
| 3027 views |
  • submit to reddit
        // Here's the problem: you have two tables, customer and address. Both tables have last-modified timestamps. You're building a data-mart that is going to de-normalize both tables. Problem is, which timestamp do you read to tell if your data needs to be refreshed?

// The answer is you need to respect whichever timestamp has the latest date, regardless of which table it resides in. Fortunately, the CASE statement lets you do just this.

// NOTE: I have no idea whether this query is efficient or not. It does, however, solve the problem. Also, the SQL below was written to run against DB2. I have not tested it against Oracle, SQL-Server, etc.

                SELECT
                    C.CUSTOMERID,
                    C.CUSTOMERNAME,
                    C.PHONE,
                    A.ADDRESS1,
                    A.ADDRESS2,
                    A.ADDRESS3,
                    A.ADDRESSCITY,
                    A.ADDRESSSTATE,
                    A.ADDRESSZIP,
                    (CASE
                        WHEN A.LASTUPDATEDTS > C.LASTUPDATEDTS
                        THEN A.LASTUPDATEDTS
                        ELSE C.LASTUPDATEDTS END) LASTUPDATETS
                FROM CUSTOMER C
                    JOIN ADDRESS A on C.ADDRESSID = A.ADDRESSID