|
| 1 | +# Using TRANSFORM function in Snowflake to extract values from a json array |
| 2 | + |
| 3 | +TRANSFORM function in Snowflake can be used for advanced array transformations. You can apply a function or lambda expression to each element in an array and return a new array with the transformed values. Here's the basic syntax: |
| 4 | + |
| 5 | +```sql |
| 6 | +TRANSFORM(input_array, expr) |
| 7 | +``` |
| 8 | + |
| 9 | +```sql |
| 10 | +SELECT TRANSFORM([1, 2, 3], x -> x * 2); |
| 11 | +-- Result: [2, 4, 6] |
| 12 | +``` |
| 13 | + |
| 14 | +## An Illustrative Example |
| 15 | +Suppose we have a table that has Coupons as a JSON Array for each Sales Order as following |
| 16 | + |
| 17 | +|order_id|coupon_json_array| |
| 18 | +|-----|--------------------------------------------------------------------------| |
| 19 | +| 111 | [{Coupon:"bbb", Discount: -1 }, {Coupon:"aaa", Type:FreeShip}] | |
| 20 | +| 222 | [{Coupon:"ccc", Discount: -2}] | |
| 21 | +| 333 | [{Coupon:"ccc", Discount: -2}, {Coupon:"aaa"}, {Coupon:"eee"} ] | |
| 22 | +| 444 | | |
| 23 | + |
| 24 | + |
| 25 | +For each Order, we need to get the comma-separate list of Coupons, if there are any as following |
| 26 | + |
| 27 | +order_id | coupons_applied |
| 28 | +-- | -- |
| 29 | +222 | ccc |
| 30 | +333 | ccc, aaa, eee |
| 31 | +111 | bbb, aaa |
| 32 | +444 | |
| 33 | +444 | |
| 34 | + |
| 35 | +We can using the TRANSFORM function to apply a Lambda Fuction to each element in the JSON array to extract the Coupon as following: |
| 36 | + |
| 37 | +```sql |
| 38 | +SELECT |
| 39 | + order_id, |
| 40 | + TRANSFORM( |
| 41 | + parse_json(orders.coupon_json_array)::ARRAY, |
| 42 | + promo OBJECT -> promo:"Coupon" |
| 43 | + ) as coupons_applied |
| 44 | +FROM orders; |
| 45 | +``` |
| 46 | + |
| 47 | +| order_id | coupons_applied | |
| 48 | +|----------|-------------------------------| |
| 49 | +| 111 | [ "bbb", "aaa" ] | |
| 50 | +| 222 | [ "ccc" ] | |
| 51 | +| 333 | [ "ccc", "aaa", "eee" ] | |
| 52 | +| 444 | | |
0 commit comments