Please share the query rather than a screenshot of part of it: even if you think it is the same, something may have changed on the way across.
Please format the code correctly by surrounding with three backticks (```) — should look like this but with your query:
SELECT
states.state
FROM
states
INNER JOIN states_meta ON
states.metadata_id = states_meta.metadata_id
WHERE
states_meta.entity_id = 'sensor.temperature_in'
AND last_updated_ts <= strftime('%s', 'now', '-1 day')
ORDER BY
last_updated_ts DESC
LIMIT
1;
The example worked perfectly for me: all I did was swap sensor.temperature_in for sensor.outside_temperature that exists on my system. Gives me the temperature 24 hours ago.
What version of HA are you running? The entity_id was de-duplicated out to the states_meta table about 10 months ago (ref), so if you’re running 2023.3 or earlier, that may be the issue.
SELECT
states.state
FROM
states
INNER JOIN states_meta ON
states.metadata_id = states_meta.metadata_id
WHERE
states_meta.entity_id = 'sensor.online_thermometer_temperature'
AND last_updated_ts <= strftime('%s', 'now', '-1 day')
ORDER BY
last_updated_ts DESC
LIMIT
1;
I am using:
Core2024.1.5
Supervisor2023.12.1
Operating System9.5
Frontend20240104.0
I have played more and i know now that WHERE condition is the problem. If i remove
AND last_updated_ts <= strftime('%s', 'now', '-1 day')
OK so for all coming here with the same problem. Original solution provided on SQL integration page that works for default Home Assistant database which is:
SELECT
states.state
FROM
states
INNER JOIN states_meta ON
states.metadata_id = states_meta.metadata_id
WHERE
states_meta.entity_id = 'sensor.temperature_in'
AND last_updated_ts <= strftime('%s', 'now', '-1 day')
ORDER BY
last_updated_ts DESC
LIMIT
1;
for MariaBD must be changed to:
SELECT
states.state
FROM
states
INNER JOIN states_meta ON
states.metadata_id = states_meta.metadata_id
WHERE
states_meta.entity_id = 'sensor.temperature_in'
AND last_updated_ts <= UNIX_TIMESTAMP(NOW() - INTERVAL 1 DAY)
ORDER BY
last_updated_ts DESC
LIMIT
1;
Thank you very much Troon for your help. You pointed me to the fact that MariaDB is the problem here, and to be exact problem is from fact that strftime() is not being supported for MariaDB and must be replaced with UNIX_TIMESTAMP()
I would like to add a small contribution here. If you want to have data longer than what is stored in your recorder database, you have to use the long term statistics database.
Use the SQL integration, column “mean” and use this query:
SELECT
statistics.mean
FROM
statistics INNER JOIN statistics_meta ON
statistics.metadata_id = statistics_meta.id
WHERE
statistics_meta.statistic_id = 'sensor.some_random_sensor' AND
start_ts <= strftime('%s', 'now', '-30 days')
ORDER BY start_ts DESC LIMIT 1