Why am I not able to add a variable amount of time to a datetime column in a custom expression?

Hey, new here. Not sure if this is a bug or if I'm misunderstanding how to do this. Either way, I couldn't find this in the GitHub issues.

I want to add a certain amount of time to a datetime column depending on a condition. In this example using the sample database, if the discount is below 3, then return 3, else 2.

I first define the condition using a custom column and case function. Then, I want to make another column using the function datetimeAdd(), and add a certain amount of days to the product -> created at column. For the amount of units to be added, I use the custom column. However, I get an invalid expression error. Upon checking the SQL I do see that the case function returns integers. Why can't the variable be used as an amount of time to be added?

Supplementary info:

{
  "browser-info": {
    "language": "en-GB",
    "platform": "MacIntel",
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
    "vendor": "Google Inc."
  },
  "system-info": {
    "file.encoding": "UTF-8",
    "java.runtime.name": "OpenJDK Runtime Environment",
    "java.runtime.version": "11.0.23+9",
    "java.vendor": "Eclipse Adoptium",
    "java.vendor.url": "https://adoptium.net/",
    "java.version": "11.0.23",
    "java.vm.name": "OpenJDK 64-Bit Server VM",
    "java.vm.version": "11.0.23+9",
    "os.name": "Linux",
    "os.version": "6.6.32-linuxkit",
    "user.language": "en",
    "user.timezone": "GMT"
  },
  "metabase-info": {
    "databases": [
      "h2"
    ],
    "hosting-env": "unknown",
    "application-database": "h2",
    "application-database-details": {
      "database": {
        "name": "H2",
        "version": "2.1.214 (2022-06-13)"
      },
      "jdbc-driver": {
        "name": "H2 JDBC Driver",
        "version": "2.1.214 (2022-06-13)"
      }
    },
    "run-mode": "prod",
    "version": {
      "date": "2024-07-04",
      "tag": "v0.50.10",
      "hash": "49d9e46"
    },
    "settings": {
      "report-timezone": null
    }
  }
}

Hey there!

In my opinion your issue is due to how SQL works.

You cannot use a custom column (Number of days to add) directly in another field within the same SELECT statement.

There are a few solutions:

  • Do not use the Question UI, but use directly SQL with a dedicated WITH statement.
  • Create an intermediate model in which you pre-define your CASE WHEN condition, and then build your additional logic on top of that model.

Hope this helps!

If you were writing SQL, you wouldn't be able to do that either.

Try something like this (sort out your own field names):

case (discount < 3 then datetimeadd(created, 3, "day),
datetimeadd(created, 2,"day"))
1 Like

Ah great, the solution above works. Thanks!