Skip to content

Commit d14de55

Browse files
Merge pull request #1718 from ilianiliev-redis/RDSC-3630-using-sql-case
RDSC-3630 Adding SQL Case examples
2 parents dc44f37 + f83a6e1 commit d14de55

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
---
2+
Title: Using SQL CASE
3+
aliases: /integrate/redis-data-integration/ingest/data-pipelines/transform-examples/redis-sql-case-example/
4+
alwaysopen: false
5+
categories:
6+
- docs
7+
- integrate
8+
- rs
9+
- rdi
10+
description: null
11+
group: di
12+
linkTitle: Using SQL CASE
13+
summary: Redis Data Integration keeps Redis in sync with the primary database in near
14+
real time.
15+
type: integration
16+
weight: 30
17+
---
18+
19+
The [`CASE`](https://www.w3schools.com/sql/sql_case.asp) statement allows you to specify conditions and return different values based on those conditions. You can use it both to create new fields or filter existing data.
20+
21+
## Using SQL CASE to create a new field
22+
The example below demonstrates how to use the `CASE` statement to create a new field called `Market` based on the value of the `BillingCountry` field in the `Invoice` table. The new field categorizes countries into regions such as "North America" and "Europe".
23+
24+
```yaml
25+
source:
26+
table: Invoice
27+
28+
transform:
29+
- uses: add_field
30+
with:
31+
field: "Market"
32+
language: sql
33+
expression: |
34+
CASE
35+
WHEN BillingCountry = 'USA' THEN 'North America'
36+
WHEN BillingCountry = 'Canada' THEN 'North America'
37+
WHEN BillingCountry = 'UK' THEN 'Europe'
38+
WHEN BillingCountry = 'France' THEN 'Europe'
39+
ELSE 'Other'
40+
END
41+
```
42+
43+
## Using SQL CASE to filter data
44+
45+
You can also use the `CASE` statement to filter data based on specific conditions. The example below demonstrates how to filter the `Invoice` table to include only invoices from the USA and Canada that have a `Total` value above their country-specific threshold.
46+
47+
Because the `Total` field is a Decimal in the source table, it is represented as a string in Debezium and so you must cast it to `REAL` to compare it numerically in the `CASE` statement. Without this cast, it will be compared as a string value, which will give the wrong result.
48+
49+
```yaml
50+
source:
51+
table: Invoice
52+
53+
transform:
54+
- uses: filter
55+
with:
56+
language: sql
57+
expression: |
58+
CASE
59+
WHEN BillingCountry = 'USA' AND CAST(Total AS REAL) > 11.99 THEN True
60+
WHEN BillingCountry = 'Canada' AND CAST(Total AS REAL) > 9.99 THEN True
61+
ELSE False
62+
END
63+
```

0 commit comments

Comments
 (0)