Querying state_attributes SQL and notifying attributes to file with an automation

I’ll just keep it simple.

I’m trying to set up an automation where on entity attribute change, the new attribute values are stored to a CSV. It’s for storing historical data from device tracker / geocoded location.

I’ve been able to use notify:

 notify:
   - platform: file
     name: geolog
     filename: geoolog.csv
     timestamp: True

AND automation:

alias: GeoLog
 description: ""
 trigger:
   - platform: state
     entity_id:
       - sensor.iphone_geocoded_location
 action:
   - service: notify.geolog
     data_template:
       message: "{{ states.sensor.iphone_geocoded_location }}"
 mode: single

to store major location updates to a CSV, but I would rather want to use every change of the entity state attribute change, since it is more precise. The best way (I would think), is involving an SQL query every hour or so, that takes all values from state_attributes containing the entity name, and parsing it to the CSV file, but after endless searching, I can’t find a way to implement a SQL query into an automation. Or even a service for that matter.

Could anybody point me in the right direction?

Every change if a state-attribute constitutes in state change.