SQL SERVER – Session Counts by Database Are Not Lock Row Counts

Total Sessions and total lock rows answer different questions. My original query counted lock rows under a session label.

Delivery cases and their multiple fastening clips are inspected as different counts.

-- Sessions grouped by their current database context:
SELECT DB_NAME(database_id) AS DatabaseName,COUNT_BIG(*) AS UserSessions
FROM sys.dm_exec_sessions WHERE is_user_process=1
GROUP BY database_id ORDER BY DatabaseName;
-- Distinct sessions with locks in a database, a different question:
SELECT DB_NAME(resource_database_id) AS DatabaseName,
       COUNT(DISTINCT request_session_id) AS SessionsWithLocks
FROM sys.dm_tran_locks WHERE request_session_id>0
GROUP BY resource_database_id ORDER BY DatabaseName;

One session can own many locks. The first replacement counts user sessions by current database context, including visible idle sessions. The second counts distinct positive session IDs owning locks in each database.

Sessions can change context or access several databases. Activity also changes between snapshots. The lock-owner count excludes orphaned distributed transactions and other non-session identifiers.

Choose connection context, active requests or lock ownership according to the question. Use the required DMV permissions. The consulting and video resources provide related context.

Related reading

A lock count is not a session count, it is a different measure of current resource ownership.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL DMV, SQL Scripts, SQL Server
Previous Post
SQL SERVER – Threads Not Counted for Max Worker Threads
Next Post
SQL SERVER – Checking Column Existence Is Different from DROP IF EXISTS

Related Posts

2 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.