Search code examples
sqlmysqlgrafana-alerts

Compare last values of two columns in SQL table to Create Grafana Alerts Condition


I have columns such as 'LTP' = 10, 'lowerbound' = 20, 'Timestamp' in a SQL table. If last value of 'LTP' < 'lowerbound', then alert should get triggered in Grafana.

In Grafana: how to create an alert by comparing values of columns in SQL table?


Solution

  • SQL Query Working in Grafana using CASE to Check multiple conditions in Single Grafana Alert:

    SELECT 
        CASE
            WHEN difference < lower_range THEN 1
            WHEN difference > upper_range THEN 0
            ELSE 2
        END AS condition_result
    FROM <db name>.<tl name>
    ORDER BY DATE DESC
    LIMIT 1;
    

    IF We want to sum up the value of two conditions based on last two rows, the sql query for that as below:

    SELECT SUM(condition_result) AS total_sum
    FROM (
        SELECT 
            CASE
                WHEN final_lowerband < Close THEN 1
                WHEN final_upperband > Close THEN 2
                ELSE 0
            END AS condition_result,
            ROW_NUMBER() OVER (ORDER BY DATE DESC) AS row_num
        FROM <db name>.<table name>
        ORDER BY DATE DESC
        LIMIT 2
    ) AS ranked_data;