diff --git a/homeassistant/components/sql/sensor.py b/homeassistant/components/sql/sensor.py index d9e40ab713e..b9e3b9ce81d 100644 --- a/homeassistant/components/sql/sensor.py +++ b/homeassistant/components/sql/sensor.py @@ -97,7 +97,7 @@ def setup_platform( value_template.hass = hass # MSSQL uses TOP and not LIMIT - if not ("LIMIT" in query_str or "SELECT TOP" in query_str): + if not ("LIMIT" in query_str.upper() or "SELECT TOP" in query_str.upper()): query_str = ( query_str.replace("SELECT", "SELECT TOP 1") if "mssql" in db_url diff --git a/tests/components/sql/test_sensor.py b/tests/components/sql/test_sensor.py index 11f59444c2c..629ec464e58 100644 --- a/tests/components/sql/test_sensor.py +++ b/tests/components/sql/test_sensor.py @@ -31,6 +31,30 @@ async def test_query(hass): assert state.attributes["value"] == 5 +async def test_query_limit(hass): + """Test the SQL sensor with a query containing 'LIMIT' in lowercase.""" + config = { + "sensor": { + "platform": "sql", + "db_url": "sqlite://", + "queries": [ + { + "name": "count_tables", + "query": "SELECT 5 as value limit 1", + "column": "value", + } + ], + } + } + + assert await async_setup_component(hass, "sensor", config) + await hass.async_block_till_done() + + state = hass.states.get("sensor.count_tables") + assert state.state == "5" + assert state.attributes["value"] == 5 + + async def test_invalid_query(hass): """Test the SQL sensor for invalid queries.""" with pytest.raises(vol.Invalid):