SQL Server 2008 - find table with most rows - sql

Is there a way in SQL Server 2008 to find the table with the most rows in the database?

This will get you close:
SELECT
[TableName] = so.name,
[RowCount] = MAX(si.rows)
FROM
sysobjects so,
sysindexes si
WHERE
so.xtype = 'U'
AND
si.id = OBJECT_ID(so.name)
GROUP BY
so.name
ORDER BY
2 DESC

Here's basically the same T-SQL that Chris Ballance provided, but using the new Object Catalog Views instead of the compatability views:
SELECT SchemaName = schemas.[name],
TableName = tables.[name],
IndexName = indexes.[name],
IndexType =
CASE indexes.type
WHEN 0 THEN 'Heap'
WHEN 1 THEN 'Clustered'
END,
IndexPartitionCount = partition_info.PartitionCount,
IndexTotalRows = partition_info.TotalRows
FROM sys.tables
JOIN sys.indexes
ON tables.object_id = indexes.object_id
AND indexes.type IN ( 0, 1 )
JOIN ( SELECT object_id, index_id, PartitionCount = COUNT(*), TotalRows = SUM(rows)
FROM sys.partitions
GROUP BY object_id, index_id
) partition_info
ON indexes.object_id = partition_info.object_id
AND indexes.index_id = partition_info.index_id
JOIN sys.schemas ON tables.schema_id = schemas.schema_id
ORDER BY SchemaName, TableName;

I just customize my SSMS 2008 to show the following additional columns
for tables
- Row Count
- Data Space Used (KB)
for databases
- Primary Data Location
- Last Backup Date
- Created Date
....
Works quicker for me most of the time without opening a query, I just click on the column header to go ASC or DESC

Related

DMVs to get index configuration information

I want to check whether all the tables in my Database has clusterd index on which type of column(eg:int) and whether the clustered index is on a single/multipe columns. I was not able to figure out which DMvs or Views to retreive this information. Please help.
below sql will give you list of the clusterd indexes and table name with few more detail. you can modified this to get to you results.
SELECT 'ClusteredIndexName' = SI.Name,
'TableName' = SO.Name,
'ColumCount' = IK.IndexColumnCount,
'IsUnique' = CASE WHEN SI.is_unique = 0 THEN 'N' ELSE 'Y' END
,SI.type_desc
FROM SYS.INDEXES SI
JOIN SYS.OBJECTS SO -- Joining on SYS.OBJECTS to get the TableName
ON SO.OBJECT_ID = SI.Object_ID
JOIN ( -- Joining on a Derived view to work out how many columns exist on the clustered index
SELECT 'IndexColumnCount' = MAX(KEY_ORDINAL), OBJECT_ID, index_id
FROM SYS.INDEX_COLUMNS
GROUP BY OBJECT_ID, index_id
) AS IK
ON IK.object_id = SI.Object_ID
AND IK.index_id = SI.index_id
WHERE SI.type_desc = 'CLUSTERED' and
SI.OBJECT_ID NOT IN (SELECT OBJECT_ID
FROM SYS.ALL_OBJECTS
WHERE TYPE = 'S') -- Not system tables
AND SO.Type = 'U'
AND SO.is_ms_shipped = 0
Sql Server Management Studio lets you see the definition of all indexes on a table. Find the table in the Tables folder, expand, and expand Indexes. Select Properties on a particular index to view columns and other properties.
SELECT * FROM sys.indexes (I think, its been a while since I used SQL Server).

How to determine if sql table is Temporal?

With SQL Server 2016 supporting Temporal Tables I wonder if there is a way to determine if a table is currently temporal? Something like
select * from sys.objects where object_id('dbo.MyTable', 'u') = parent_object_id and type_desc = "SYSTEM_VERSIONED"
SELECT temporal_type
FROM sys.tables
WHERE object_id = OBJECT_ID('dbo.MyTable', 'u')
0 = NON_TEMPORAL_TABLE
1 = HISTORY_TABLE
2 = SYSTEM_VERSIONED_TEMPORAL_TABLE
Documentation
Another way of listing temporal tables with their history tables together is given in this SQL tutorial as List Temporal and History Tables in a SQL Server Database
select
t.object_id,
t.name,
t.temporal_type,
t.temporal_type_desc,
h.object_id,
h.name,
h.temporal_type,
h.temporal_type_desc
from sys.tables t
inner join sys.tables h on t.history_table_id = h.object_id
Here is a simple answer to the original basic question:
SELECT *
FROM sys.tables
WHERE name = 'MyTable'
AND schema_id = SCHEMA_ID('dbo')
AND temporal_type_desc = 'SYSTEM_VERSIONED_TEMPORAL_TABLE'
And here is a similar query looking for the actual system managed history table:
SELECT h.* FROM sys.tables p
INNER JOIN sys.tables h
ON p.history_table_id = h.object_id
WHERE p.name = 'MyTable'
AND p.schema_id = SCHEMA_ID('dbo')
AND p.temporal_type_desc = 'SYSTEM_VERSIONED_TEMPORAL_TABLE';
This query will give you the system versioned tables, the associated history tables, the retention policy, and whether the retention policy is enabled at the database level.
From Microsoft Docs
SELECT DB.is_temporal_history_retention_enabled,
SCHEMA_NAME(T1.schema_id) AS TemporalTableSchema,
T1.name as TemporalTableName, SCHEMA_NAME(T2.schema_id) AS HistoryTableSchema,
T2.name as HistoryTableName,T1.history_retention_period,
T1.history_retention_period_unit_desc
FROM sys.tables T1
OUTER APPLY (select is_temporal_history_retention_enabled from sys.databases
where name = DB_NAME()) AS DB
LEFT JOIN sys.tables T2
ON T1.history_table_id = T2.object_id WHERE T1.temporal_type = 2

Determining page count on each SQL table without using DBCC

I am trying to compress the largest tables in my database. I will do this by running the SP_ForEachDB stored procedure. However I cannot figure out how to view the total page count. I can get the row count with this query...
USE DEVELOP04_HiltonUS
GO
SELECT
[TableName] = so.name,
[RowCount] = MAX(si.rows)
FROM
sysobjects so,
sysindexes si
WHERE
so.xtype = 'U'
AND
si.id = OBJECT_ID(so.name)
GROUP BY
so.name
ORDER BY
2 DESC
Which returns:
TABLE NAME ROW COUNT
PlannedShift 38268660
BudgetStaffStat 19353104
BudgetKBIStat 14142631
EmployeeShiftAdjustment 13493745
Requirement 11020921
EmployeeShiftError 6857235
JobclassLaborData 5638692
and so on for all my tables.
I am looking for the same thing but returning page Count instead.
SELECT OBJECT_SCHEMA_NAME(s.object_id) schema_name,
OBJECT_NAME(s.object_id) table_name,
SUM(s.used_page_count) used_pages,
SUM(s.reserved_page_count) reserved_pages
FROM sys.dm_db_partition_stats s
JOIN sys.tables t
ON s.object_id = t.object_id
GROUP BY s.object_id
ORDER BY schema_name,
table_name;

find all tables not referenced in stored procedures

I have sql server database with numerous tables, some no longer used so I want to remove them. All database interactivity is via stored procedure to these tables.
Is there a database sql script that I can use that will list all tables not referenced in any of the stored procedures in the database?
If SQL Server 2008 then the dependencies information is now reliable.
SELECT SCHEMA_NAME(t.schema_id),
t.name
FROM sys.tables t
WHERE is_ms_shipped = 0
AND NOT EXISTS (SELECT *
FROM sys.sql_expression_dependencies d
WHERE d.referenced_entity_name = t.name
AND (( is_ambiguous = 1 or is_caller_dependent=1)
OR
d.referenced_id = t.object_id) )
You can't do this if you use any dynamic T-SQL. Dynamic T-SQL won't show up in any investigation of object dependencies.
Instead, you can use the DMV sys.dm_db_index_usage_stats to find what objects haven't been referenced by any queries. Here's a query I did on SQLServerPedia for that:
http://sqlserverpedia.com/wiki/Find_Indexes_Not_In_Use
The query is designed for performance tuning indexes, so you'll need to tweak a few lines. Here's the modified query:
SELECT
o.name
, indexname=i.name
, i.index_id
, reads=user_seeks + user_scans + user_lookups
, writes = user_updates
, rows = (SELECT SUM(p.rows) FROM sys.partitions p WHERE p.index_id = s.index_id AND s.object_id = p.object_id)
, CASE
WHEN s.user_updates < 1 THEN 100
ELSE 1.00 * (s.user_seeks + s.user_scans + s.user_lookups) / s.user_updates
END AS reads_per_write
, 'DROP INDEX ' + QUOTENAME(i.name)
+ ' ON ' + QUOTENAME(c.name) + '.' + QUOTENAME(OBJECT_NAME(s.object_id)) as 'drop statement'
FROM sys.dm_db_index_usage_stats s
INNER JOIN sys.indexes i ON i.index_id = s.index_id AND s.object_id = i.object_id
INNER JOIN sys.objects o on s.object_id = o.object_id
INNER JOIN sys.schemas c on o.schema_id = c.schema_id
WHERE OBJECTPROPERTY(s.object_id,'IsUserTable') = 1
AND s.database_id = DB_ID()
ORDER BY reads
Keep in mind that this catches all indexes, and you'll need to sift through - some of your objects may be heaps, some may have clustered indexes, etc. I'll leave this as a wiki so someone more ambitious than me can edit it to build a deduped list. :-D
Check this discussion tsql script to find tables not being used by stored procedures, views, functions, etc?
And this article(listed from above discussion) http://www.mssqltips.com/tip.asp?tip=1294 discusses about SQL object dependencies.
Perhaps something along these lines:
select t.table_name
from INFORMATION_SCHEMA.TABLES t
where not exists (
select 1 from INFORMATION_SCHEMA.ROUTINES r
where object_definition(object_id(r.ROUTINE_NAME)) like '%'+t.TABLE_NAME+'%'
) order by t.TABLE_NAME
The first query lists table with the stored proc name that uses it.
The second query lists table with the number of stored procs using it.
-- list all tables / sprocs
select t.name [Table], p.name [StoredProc]
from sys.tables t
left join sys.procedures p on (OBJECT_DEFINITION(p.object_id)) like '%' + t.name + '%'
where t.type = 'U'
order by t.name, p.name
-- count stored procs using table
select t.name [Table], count(p.name) [Count]
from sys.tables t
left join sys.procedures p on (OBJECT_DEFINITION(p.object_id)) like '%' + t.name + '%'
where t.type = 'U'
group by t.name
order by t.name
Here's one you might try:
select
name
from
sys.tables t
left join
sys.sql_dependencies d
on
t.object_id =
d.referenced_major_id
where
d.referenced_major_id is null
Otherwise, here's a reference I've used in the past:
http://www.mssqltips.com/tip.asp?tip=1294
If performace isnt to much of a problem you could try the following.
Select Distinct Object_Name(ID)
From syscomments
Where ID Not In (Select ID From syscomments Where Text Like '%<TableName>%')
This will check each view, rule, default, trigger, CHECK constraint, DEFAULT constraint, and stored procedure within your database
Most of this code doesn't work if there are schemas other than "dbo", or if the user's default schema is not "dbo". Here's an update to one of the scripts to fix that:
select t.Table_Schema + '.' + t.table_name
from INFORMATION_SCHEMA.TABLES t
where not exists (
select 1 from INFORMATION_SCHEMA.ROUTINES r
where object_definition(object_id(r.routine_schema + '.' + r.ROUTINE_NAME)) like '%'+t.TABLE_NAME+'%'
) order by t.TABLE_NAME

Sql Query to list all views in an SQL Server 2005 database

I need an sql query to enumerate all views (I only need the view names) of a specific database in SQL Server 2005.
To finish the set off (with what has already been suggested):
SELECT * FROM sys.views
This gives extra properties on each view, not available from sys.objects (which contains properties common to all types of object) or INFORMATION_SCHEMA.VIEWS. Though INFORMATION_SCHEMA approach does provide the view definition out-of-the-box.
SELECT SCHEMA_NAME(schema_id) AS schema_name
,name AS view_name
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexed') AS IsIndexed
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexable') AS IsIndexable
FROM sys.views
SELECT *
FROM sys.objects
WHERE type = 'V'
Run this adding DatabaseName in where condition.
SELECT TABLE_NAME, ROW_NUMBER() OVER(ORDER BY TABLE_NAME) AS 'RowNumber'
FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_CATALOG = 'DatabaseName'
or remove where condition adding use.
use DataBaseName
SELECT TABLE_NAME, ROW_NUMBER() OVER(ORDER BY TABLE_NAME) AS 'RowNumber'
FROM INFORMATION_SCHEMA.VIEWS
select v.name
from INFORMATION_SCHEMA.VIEWS iv
join sys.views v on v.name = iv.Table_Name
where iv.Table_Catalog = 'Your database name'
Some time you need to access with schema name,as an example you are using AdventureWorks Database you need to access with schemas.
SELECT s.name +'.'+v.name FROM sys.views v inner join sys.schemas s on s.schema_id = v.schema_id
Necromancing.
Since you said ALL views, technically, all answers to date are WRONG.
Here is how to get ALL views:
SELECT
sch.name AS view_schema
,sysv.name AS view_name
,ISNULL(sysm.definition, syssm.definition) AS view_definition
,create_date
,modify_date
FROM sys.all_views AS sysv
INNER JOIN sys.schemas AS sch
ON sch.schema_id = sysv.schema_id
LEFT JOIN sys.sql_modules AS sysm
ON sysm.object_id = sysv.object_id
LEFT JOIN sys.system_sql_modules AS syssm
ON syssm.object_id = sysv.object_id
-- INNER JOIN sys.objects AS syso ON syso.object_id = sysv.object_id
WHERE (1=1)
AND (sysv.type = 'V') -- seems unnecessary, but who knows
-- AND sch.name = 'INFORMATION_SCHEMA'
/*
AND sysv.is_ms_shipped = 0
AND NOT EXISTS
(
SELECT * FROM sys.extended_properties AS syscrap
WHERE syscrap.major_id = sysv.object_id
AND syscrap.minor_id = 0
AND syscrap.class = 1
AND syscrap.name = N'microsoft_database_tools_support'
)
*/
ORDER BY
view_schema
,view_name
This is old, but I thought I'd put this out anyway since I couldn't find a query that would give me ALL the SQL code from EVERY view I had out there. So here it is:
SELECT SM.definition
FROM sys.sql_modules SM
INNER JOIN sys.Objects SO ON SM.Object_id = SO.Object_id
WHERE SO.type = 'v'