---
title: "Creating a Microsoft SQL Tag"
description: "Configure a SQL query as a tag data source"
source_url: https://ai-ops.com/docs/tags/creating-mssql
---

# Creating a Microsoft SQL Tag

After [creating a tag](https://ai-ops.com/docs/tags/creating-getting-started.md) on a Microsoft SQL device, you need to provide the SQL query that Koios will execute to read this tag's value. You can configure this during creation or afterwards on the tag's **Configuration** tab.

> [!NOTE] No device browser available
> Unlike other protocols, Microsoft SQL tags don't have a browse function. You'll need to know the database schema and write the query yourself.

## Protocol Fields

### SQL Query

The SQL query that Koios executes against the database on each scan to read this tag's value.

- **Optional** during creation, but required for the tag to collect data
- The query should return a **single numeric value**
- Maximum length: 1,024 characters

```sql
SELECT TOP 1 temperature FROM sensor_readings
WHERE sensor_id = 'AHU-01'
ORDER BY timestamp DESC
```

### Query Guidelines

**Return a single value.** Koios reads the first column of the first row of the result set. If your query returns multiple rows or columns, only the first value is used.

**Keep queries lightweight.** The query runs on every scan cycle, so avoid expensive joins, full table scans, or complex aggregations that could slow down the database.

**Use parameterized values where possible.** If you need the most recent reading, use `TOP 1` with an `ORDER BY` on the timestamp column rather than scanning the entire table.

> [!WARNING] Query runs repeatedly at the scan rate
> This query executes every time the device scans — typically every few seconds. Make sure it performs well under repeated execution. Add appropriate indexes to the source table if needed.

### Example Queries

**Latest sensor reading:**
```sql
SELECT TOP 1 value FROM readings
WHERE tag_name = 'Supply_Temp'
ORDER BY timestamp DESC
```

**Aggregated value:**
```sql
SELECT AVG(temperature) FROM hourly_averages
WHERE zone = 'Warehouse-1'
AND timestamp > DATEADD(HOUR, -1, GETDATE())
```

**Count of active alarms:**
```sql
SELECT COUNT(*) FROM active_alarms
WHERE severity >= 3
```

## After Configuration

1. **Save** the tag configuration
2. **Test the tag** — click `Test` to verify the query returns a valid value (see [Testing a Tag](https://ai-ops.com/docs/tags/troubleshooting.md#testing-a-tag))
3. **Enable the tag** — flip the enable switch to start collecting data

> [!TIP] Enable the device first
> Tags only collect data when their parent device is also enabled and running. Make sure the SQL device's connection credentials and database are correctly configured.
