SqlDependency .NET: Real-Time Query Notifications

Your app polls the database 86,400 times a day—mostly for zilch. SqlDependency ends that nonsense, pushing changes straight to your .NET code like a cosmic bat-signal.

SqlDependency in .NET: Ditch Polling, Let SQL Server Ring Your Doorbell — theAIcatchup

Key Takeaways

  • SqlDependency swaps wasteful polling for instant database push notifications in .NET.
  • Requires Service Broker enabled and strict query rules—clean up those SELECT * habits.
  • Perfect for real-time apps; my bet: essential for future AI agents querying live data.

86,400 polls a day. That’s what the typical .NET app hurls at its SQL Server, every frantic second of every hour, chasing ghosts of data that rarely budge.

And here’s SqlDependency in .NET—your escape hatch. This under-the-radar gem flips polling on its head. The database doesn’t wait for questions; it shouts when the party’s starting.

Think of it like this: polling’s that insecure friend texting “u there?” nonstop. SqlDependency? A trusted courier dropping packages at your door, no fanfare needed.

Why Your App’s Secretly a Resource Hog

But let’s zoom out. In a world where AI agents gulp data like oxygen, lag kills. SqlDependency isn’t just efficient—it’s prophetic. Remember the web’s polling era, before WebSockets burst onto the scene? Same vibe. We’re on the cusp of databases as active players, not passive vaults, powering edge AI that reacts before you blink.

Put simply: polling is like constantly opening the fridge to check if new food appeared. SqlDependency is like a doorbell that rings when the delivery arrives.

That’s from the docs, but damn if it doesn’t nail it. No more CPU bonfires, no network gridlock. Just pure, electric responsiveness.

The Magic Under the Hood

Service Broker. Query Notifications. Two SQL Server superpowers teaming up. You craft a precise query—no sloppy SELECT * allowed—slap a SqlDependency on your SqlCommand, and boom. Subscription live.

Data shifts? Insert, update, delete—SQL Server pings your event handler. One-shot per sub, but chain ‘em, and you’ve got eternal vigilance.

Here’s the thing. Constraints bite: primary keys mandatory, no aggregates, two-part names only. Feels picky? Yeah, but it forces clean queries. Your sloppy joins? Time to refactor.

Setting Up the Battlefield

Fire up SQL Server Management Studio. This script preps everything—no half-measures.

USE master;
GO
IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'SimpleSqlDepDB')
CREATE DATABASE SimpleSqlDepDB;
GO
USE SimpleSqlDepDB;
GO
ALTER DATABASE SimpleSqlDepDB SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
GO

Service Broker off? Dead in the water. I’ve seen devs rage for hours—check SELECT is_broker_enabled FROM sys.databases WHERE name = 'YourDB';. Flip it, or cry.

Table next. Messages queue, simple as dirt.

IF OBJECT_ID('dbo.Messages', 'U') IS NULL
BEGIN
CREATE TABLE dbo.Messages (
Id INT IDENTITY(1,1) PRIMARY KEY,
Message NVARCHAR(100) NOT NULL,
Status NVARCHAR(20) NOT NULL DEFAULT 'New'
);
END
GO
INSERT INTO Messages (Message, Status) VALUES ('Initial message', 'New');
GO

Coding the Beast in .NET 10

New console app. NuGet Microsoft.Data.SqlClient at 7.0.0. Implicit usings? Enabled. Nullable? You bet.

Program.cs unfolds like this:

using System;
using System.Data;
using Microsoft.Data.SqlClient;

class Program
{
    private static string connectionString = "Server=.\\SQLEXPRESS;Database=SimpleSqlDepDB;Integrated Security=true;TrustServerCertificate=true;";

    static void Main()
    {
        SqlDependency.Start(connectionString);

        Console.WriteLine("Listening for new messages... Press Ctrl+C to exit.");

        while (true)
        {
            ListenForNewMessages();
        }
    }

    static void ListenForNewMessages()
    {
        using var connection = new SqlConnection(connectionString);
        var command = new SqlCommand("SELECT Id, Message, Status FROM dbo.Messages WHERE Status = 'New'", connection);

        var dependency = new SqlDependency(command);
        dependency.OnChange += (sender, e) =>
        {
            if (e.Type == SqlNotificationEventType.Change)
            {
                Console.WriteLine("Change detected! Checking new messages...");
                PrintNewMessages();
                ListenForNewMessages(); // Re-subscribe
            }
        };

        connection.Open();
        command.ExecuteReader(CommandBehavior.CloseConnection);
    }

    static void PrintNewMessages()
    {
        using var connection = new SqlConnection(connectionString);
        var command = new SqlCommand("SELECT Id, Message FROM dbo.Messages WHERE Status = 'New'", connection);
        connection.Open();
        using var reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine($"New message: {reader["Message"]} (ID: {reader["Id"]})");
        }
    }
}

Run it. Open another SSMS tab. INSERT INTO Messages (Message) VALUES ('Fresh alert!');. Watch the console explode with joy. Instant. Re-registers. Eternal loop of awareness.

## Can SqlDependency Scale to Your Chaos?

Limits lurk. Azure SQL? Broker’s gimpy—tier-dependent. Complex queries? Nope, no TOP sans ORDER BY, no subqueries dancing wild. Need audit trails? SqlDependency whispers “change happened,” not “what changed.” Pair with Change Data Capture for that.

But my hot take: this is the unsung hero for agentic AI. Imagine LLMs querying live inventories, reacting sans delay. Polling chokes under load; this thrives. Prediction? By 2026, every real-time .NET AI stack mandates it—or dies trying.

## Why Skip SqlDependency in 2025?

You won’t. Not if real-time’s your jam. Stock tickers, chat queues, IoT floods—it’s doorbell magic at enterprise scale. Corporate hype? Nah, this is battle-tested since .NET 2.0. Microsoft just… forgets to shout.

Tweak for production: Threading, error dance, pooled connections. But core? Rock-solid.


🧬 Related Insights

Frequently Asked Questions

What is SqlDependency in .NET?

SqlDependency lets SQL Server notify your .NET app instantly when query results change, killing polling waste via Service Broker and Query Notifications.

How do I enable Service Broker for SqlDependency?

Run ALTER DATABASE YourDB SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;. Verify with SELECT is_broker_enabled FROM sys.databases;. Reboot can disable it—check always.

What are SqlDependency query limitations?

No SELECT *, aggregates, TOP without ORDER BY, UNION, complex subs. Tables need PK/unique index; use explicit columns and two-part names.

Elena Vasquez
Written by

Senior editor and generalist covering the biggest stories with a sharp, skeptical eye.

Frequently asked questions

What is SqlDependency in .NET?
SqlDependency lets SQL Server notify your .NET app instantly when query results change, killing polling waste via Service Broker and Query Notifications.
How do I enable Service Broker for SqlDependency?
Run `ALTER DATABASE YourDB SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;`. Verify with `SELECT is_broker_enabled FROM sys.databases;`. Reboot can disable it—check always.
What are SqlDependency query limitations?
No SELECT *, aggregates, TOP without ORDER BY, UNION, complex subs. Tables need PK/unique index; use explicit columns and two-part names.

Worth sharing?

Get the best AI stories of the week in your inbox — no noise, no spam.

Originally reported by Dev.to

Stay in the loop

The week's most important stories from theAIcatchup, delivered once a week.