Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 49 additions & 2 deletions source/_integrations/sql.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ sql:
query:
description: An SQL QUERY string, should return 1 result at most.
required: true
type: string
type: template
Comment thread
gjohansson-ST marked this conversation as resolved.
column:
description: The field name to select.
required: true
Expand Down Expand Up @@ -149,16 +149,18 @@ The `sql.query` action returns a list of rows, where each row is a dictionary of
#### Data type conversion

The data returned by the database is converted to be compatible with the action response. The following conversions are applied:

- `Decimal` types are converted to floats.
- `Date` and `Datetime` objects are converted to ISO 8601 formatted strings.
- `bytes` and `bytearray` are converted to a hexadecimal string prefixed with `0x`.
- All other basic types (string, integer, float, boolean) are returned as is.

#### Example

Example of calling the `sql.query` action in an automation:
##### Example of calling the `sql.query` action in an automation:

{% raw %}

```yaml
action: sql.query
data:
Expand All @@ -178,11 +180,13 @@ data:
3;
response_variable: sun_history
```

{% endraw %}

This would return a result similar to this, which will be stored in the `sun_history` variable:

{% raw %}

```yaml
result:
- state: below_horizon
Expand Down Expand Up @@ -245,6 +249,48 @@ LIMIT

Use `state` as column for value.

### Amount of state changes since using a template

This example shows the amount of state changes of the sensor `sensor.temperature_in`
using another sensor's state to provide the time window.

```yaml
sensor:
- platform: random
name: Temperature in
unit_of_measurement: "°C"
```

The query will look like this:

{% raw %}

```sql
SELECT
count(state) as changes
FROM
(
SELECT
states.state
FROM
states
WHERE
metadata_id = (
SELECT
metadata_id
FROM
states_meta
WHERE
entity_id = 'sensor.temperature_in'
)
AND last_updated_ts >= strftime('%s','{{ states("sensor.datetime_helper") }}')
)
```

{% endraw %}

Use `changes` as column for value.

### Previous state of an entity

Based on previous example with temperature, the query to get the former state is :
Expand Down Expand Up @@ -275,6 +321,7 @@ WHERE
1
);
```

Use `state` as column for value.

### State of an entity x time ago
Expand Down