Use Part of Variable as Input to An SQL Query

  • What Grafana version and what operating system are you using?

  • v8.5.20

  • What are you trying to achieve?

  • I have a variable called ownerID which has 2 possible values

  •    3 - Value 1
    
  •    8 - Value 2
    

    I want to use only the 3 or 8 as input to an SQL query in another variable.

In other words, if the user selects 3 - Value 1, the SQL query in the second variable would only use the 3

Example:

SELECT name
FROM tablex
where Id=“This is what I need - it should use the value 3”

  • How are you trying to achieve it?
    I have tried regex but can’t get that to work

  • What did you expect to happen?
    I expect the SQL query to return the value name associated with Id = 3

you can do something like this in mssql:

other databases also have similar functionality to substring

That’s fine if the numeral part is only one character long, but what if the value is 2456 - next?
It needs some that can figure out the index of the first space and take the characters before that. And as a complication this is using Druid SQK, I neglected to mention that earlier.

using the hyphen as the character index:

i have not worked with druid, but something like this should work:

SELECT REGEXP_EXTRACT(“$ownerID”, ‘^(.*) -’, 1) AS before_dash
FROM datasource_name

Yep, that’s seems to have got it.
Thanks so much.