How To Use Case Expression On SQL Select
Join the DZone community and get the full member experience.Join For Free
// 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