Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How To Use Case Expression On SQL Select

DZone's Guide to

How To Use Case Expression On SQL Select

·
Free Resource
// 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
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}