Like syntax in grafana

The data source is postgresql.

I define a panel variable meter_code whose type is Textbox.
I want to do a fuzzy query on this variable:

select *
from meter
where meter_code like '%$meter_code%';

This works fine when meter_code has a value:

select *
from meter
where meter_code like '%METXJJSZXNSB1%';

When meter_code is null:

select *
from meter
where meter_code like '%%';

This is not the result I want, I hope it should be:

select *
from meter

Please, what should I do? Thanks!

its not really a grafana issue but that said try

select *
from meter
where $meter_code is null
 or meter_code like '%$meter_code%';

Very good, I think this is a way to solve the problem.
I wonder if it’s possible to automatically omit the following SQL statement like ‘=’ if the value is null

what do you mean by that?

select *
from meter
where meter_code = $meter_code;

If $meter_code is null
So the Grafana execution statement is:

select *
from meter

Grafana will automatically ignore the ‘where’ section
where meter_code = $meter_code;

Grafana shouldn’t do that. Its job is to replace template variable with value, apart from that it’s a query responsibility to consider different possible cases.

1 Like