If you’re using SQL Server 2005 and up, you can also use this:
SELECT
t.NAME AS TableName,
i.name as indexName,
p.[Rows],
sum(a.total_pages) as TotalPages,
sum(a.used_pages) as UsedPages,
sum(a.data_pages) as DataPages,
(sum(a.total_pages) * 8) / 1024 as TotalSpaceMB,
(sum(a.used_pages) * 8) / 1024 as UsedSpaceMB,
(sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%' AND
i.OBJECT_ID > 255 AND
i.index_id <= 1
GROUP BY
t.NAME, i.object_id, i.index_id, i.name, p.[Rows]
ORDER BY
object_name(i.object_id)
In my opinion, it’s easier to handle than the sp_msforeachtable
output.
Mike G
4,2129 gold badges40 silver badges65 bronze badges
answered Sep 18, 2009 at 10:31
marc_smarc_s
727k174 gold badges1325 silver badges1454 bronze badges
11
A snippet I found at http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=21021 that helped me:
select t.name TableName, i.rows Records
from sysobjects t, sysindexes i
where t.xtype = 'U' and i.id = t.id and i.indid in (0,1)
order by TableName;
answered Jan 4, 2013 at 19:47
Erik AndersonErik Anderson
4,8553 gold badges30 silver badges30 bronze badges
2
To get that information in SQL Management Studio, right click on the database, then select Reports –> Standard Reports –> Disk Usage by Table.
answered Sep 18, 2013 at 12:25
petrapetra
2,6022 gold badges20 silver badges11 bronze badges
1
SELECT
T.NAME AS 'TABLE NAME',
P.[ROWS] AS 'NO OF ROWS'
FROM SYS.TABLES T
INNER JOIN SYS.PARTITIONS P ON T.OBJECT_ID=P.OBJECT_ID;
Mike G
4,2129 gold badges40 silver badges65 bronze badges
answered Apr 6, 2015 at 17:00
ANGANG
2273 silver badges3 bronze badges
1
As seen here, this will return correct counts, where methods using the meta data tables will only return estimates.
CREATE PROCEDURE ListTableRowCounts
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #TableCounts
(
TableName VARCHAR(500),
CountOf INT
)
INSERT #TableCounts
EXEC sp_msForEachTable
'SELECT PARSENAME(''?'', 1),
COUNT(*) FROM ? WITH (NOLOCK)'
SELECT TableName , CountOf
FROM #TableCounts
ORDER BY TableName
DROP TABLE #TableCounts
END
GO
answered Sep 18, 2009 at 12:52
KM.KM.
101k34 gold badges178 silver badges211 bronze badges
1
sp_MSForEachTable 'DECLARE @t AS VARCHAR(MAX);
SELECT @t = CAST(COUNT(1) as VARCHAR(MAX))
+ CHAR(9) + CHAR(9) + ''?'' FROM ? ; PRINT @t'
Output:
answered May 21, 2015 at 13:37
Rikin PatelRikin Patel
8,8087 gold badges70 silver badges78 bronze badges
2
Well luckily SQL Server management studio gives you a hint on how to do this.
Do this,
- start a SQL Server trace and open the activity you are doing (filter
by your login ID if you’re not alone and set the application Name
to Microsoft SQL Server Management Studio), pause the trace and discard any results you have recorded till now; - Then, right click a table and select property from the pop up menu;
- start the trace again;
- Now in SQL Server Management studio select the storage property item on the left;
Pause the trace and have a look at what TSQL is generated by microsoft.
In the probably last query you will see a statement starting with exec sp_executesql N'SELECT
when you copy the executed code to visual studio you will notice that this code generates all the data the engineers at microsoft used to populate the property window.
when you make moderate modifications to that query you will get to something like this:
SELECT
SCHEMA_NAME(tbl.schema_id)+'.'+tbl.name as [table], --> something I added
p.partition_number AS [PartitionNumber],
prv.value AS [RightBoundaryValue],
fg.name AS [FileGroupName],
CAST(pf.boundary_value_on_right AS int) AS [RangeType],
CAST(p.rows AS float) AS [RowCount],
p.data_compression AS [DataCompression]
FROM sys.tables AS tbl
INNER JOIN sys.indexes AS idx ON idx.object_id = tbl.object_id and idx.index_id < 2
INNER JOIN sys.partitions AS p ON p.object_id=CAST(tbl.object_id AS int) AND p.index_id=idx.index_id
LEFT OUTER JOIN sys.destination_data_spaces AS dds ON dds.partition_scheme_id = idx.data_space_id and dds.destination_id = p.partition_number
LEFT OUTER JOIN sys.partition_schemes AS ps ON ps.data_space_id = idx.data_space_id
LEFT OUTER JOIN sys.partition_range_values AS prv ON prv.boundary_id = p.partition_number and prv.function_id = ps.function_id
LEFT OUTER JOIN sys.filegroups AS fg ON fg.data_space_id = dds.data_space_id or fg.data_space_id = idx.data_space_id
LEFT OUTER JOIN sys.partition_functions AS pf ON pf.function_id = prv.function_id
Now the query is not perfect and you could update it to meet other questions you might have, the point is, you can use the knowledge of microsoft to get to most of the questions you have by executing the data you’re interested in and trace the TSQL generated using profiler.
I kind of like to think that MS engineers know how SQL server work and, it will generate TSQL that works on all items you can work with using the version on SSMS you are using so it’s quite good on a large variety releases prerviouse, current and future.
And remember, don’t just copy, try to understand it as well else you might end up with the wrong solution.
Walter
answered Jul 10, 2015 at 11:21
This approaches uses string concatenation to produce a statement with all tables and their counts dynamically, like the example(s) given in the original question:
SELECT COUNT(*) AS Count,'[dbo].[tbl1]' AS TableName FROM [dbo].[tbl1]
UNION ALL SELECT COUNT(*) AS Count,'[dbo].[tbl2]' AS TableName FROM [dbo].[tbl2]
UNION ALL SELECT...
Finally this is executed with EXEC
:
DECLARE @cmd VARCHAR(MAX)=STUFF(
(
SELECT 'UNION ALL SELECT COUNT(*) AS Count,'''
+ QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)
+ ''' AS TableName FROM ' + QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES AS t
WHERE TABLE_TYPE='BASE TABLE'
FOR XML PATH('')
),1,10,'');
EXEC(@cmd);
answered Oct 27, 2017 at 23:15
ShnugoShnugo
65.8k9 gold badges52 silver badges110 bronze badges
2
I want to share what’s working for me
SELECT
QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) + '.' + QUOTENAME(sOBJ.name) AS [TableName]
, SUM(sdmvPTNS.row_count) AS [RowCount]
FROM
sys.objects AS sOBJ
INNER JOIN sys.dm_db_partition_stats AS sdmvPTNS
ON sOBJ.object_id = sdmvPTNS.object_id
WHERE
sOBJ.type = 'U'
AND sOBJ.is_ms_shipped = 0x0
AND sdmvPTNS.index_id < 2
GROUP BY
sOBJ.schema_id
, sOBJ.name
ORDER BY [TableName]
GO
The database is hosted in Azure and the final result is:
Credit: https://www.mssqltips.com/sqlservertip/2537/sql-server-row-count-for-all-tables-in-a-database/
answered May 2, 2020 at 13:37
d.danailovd.danailov
9,5164 gold badges51 silver badges36 bronze badges
Here is my take on this question. It contains all schemas and lists only tables with rows. YMMV
select distinct schema_name(t.schema_id) as schema_name, t.name as
table_name, p.[Rows]
from sys.tables as t
INNER JOIN sys.indexes as i ON t.OBJECT_ID = i.object_id
INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id =
p.index_id
where p.[Rows] > 0
order by schema_name;
answered Jan 26, 2022 at 17:25
The first thing that came to mind was to use sp_msForEachTable
exec sp_msforeachtable 'select count(*) from ?'
that does not list the table names though, so it can be extended to
exec sp_msforeachtable 'select parsename(''?'', 1), count(*) from ?'
The problem here is that if the database has more than 100 tables you will get the following error message:
The query has exceeded the maximum
number of result sets that can be
displayed in the results grid. Only
the first 100 result sets are
displayed in the grid.
So I ended up using table variable to store the results
declare @stats table (n sysname, c int)
insert into @stats
exec sp_msforeachtable 'select parsename(''?'', 1), count(*) from ?'
select
*
from @stats
order by c desc
answered Sep 18, 2009 at 10:28
kristofkristof
52.6k24 gold badges86 silver badges110 bronze badges
You could try this:
SELECT OBJECT_SCHEMA_NAME(ps.object_Id) AS [schemaname],
OBJECT_NAME(ps.object_id) AS [tablename],
row_count AS [rows]
FROM sys.dm_db_partition_stats ps
WHERE OBJECT_SCHEMA_NAME(ps.object_Id) <> 'sys' AND ps.index_id < 2
ORDER BY
OBJECT_SCHEMA_NAME(ps.object_Id),
OBJECT_NAME(ps.object_id)
answered Oct 26, 2017 at 9:16
Steve FordSteve Ford
7,41319 silver badges40 bronze badges
If you use MySQL >4.x you can use this:
select TABLE_NAME, TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA="test";
Keep in mind that for some storage engines, TABLE_ROWS is an approximation.
answered Sep 18, 2009 at 10:32
1
The accepted answer didn’t work for me on Azure SQL, here’s one that did, it’s super fast and did exactly what I wanted:
select t.name, s.row_count
from sys.tables t
join sys.dm_db_partition_stats s
ON t.object_id = s.object_id
and t.type_desc = 'USER_TABLE'
and t.name not like '%dss%'
and s.index_id = 1
order by s.row_count desc
answered Oct 6, 2015 at 21:53
UnionPUnionP
1,17512 silver badges23 bronze badges
This sql script gives the schema, table name and row count of each table in a database selected:
SELECT SCHEMA_NAME(schema_id) AS [SchemaName],
[Tables].name AS [TableName],
SUM([Partitions].[rows]) AS [TotalRowCount]
FROM sys.tables AS [Tables]
JOIN sys.partitions AS [Partitions]
ON [Tables].[object_id] = [Partitions].[object_id]
AND [Partitions].index_id IN ( 0, 1 )
-- WHERE [Tables].name = N'name of the table'
GROUP BY SCHEMA_NAME(schema_id), [Tables].name
order by [TotalRowCount] desc
Ref: https://blog.sqlauthority.com/2017/05/24/sql-server-find-row-count-every-table-database-efficiently/
Another way of doing this:
SELECT o.NAME TABLENAME,
i.rowcnt
FROM sysindexes AS i
INNER JOIN sysobjects AS o ON i.id = o.id
WHERE i.indid < 2 AND OBJECTPROPERTY(o.id, 'IsMSShipped') = 0
ORDER BY i.rowcnt desc
answered Aug 10, 2018 at 2:20
rchackorchacko
1,94722 silver badges24 bronze badges
I think that the shortest, fastest and simplest way would be:
SELECT
object_name(object_id) AS [Table],
SUM(row_count) AS [Count]
FROM
sys.dm_db_partition_stats
WHERE
--object_schema_name(object_id) = 'dbo' AND
index_id < 2
GROUP BY
object_id
answered Aug 28, 2017 at 10:31
yakyayakya
4,3992 gold badges28 silver badges31 bronze badges
USE DatabaseName
CREATE TABLE #counts
(
table_name varchar(255),
row_count int
)
EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'
SELECT table_name, row_count FROM #counts ORDER BY table_name, row_count DESC
DROP TABLE #counts
answered Jul 11, 2018 at 14:18
foluisfoluis
9772 gold badges10 silver badges23 bronze badges
From this question:
https://dba.stackexchange.com/questions/114958/list-all-tables-from-all-user-databases/230411#230411
I added record count to the answer provided by @Aaron Bertrand that lists all databases and all tables.
DECLARE @src NVARCHAR(MAX), @sql NVARCHAR(MAX);
SELECT @sql = N'', @src = N' UNION ALL
SELECT ''$d'' as ''database'',
s.name COLLATE SQL_Latin1_General_CP1_CI_AI as ''schema'',
t.name COLLATE SQL_Latin1_General_CP1_CI_AI as ''table'' ,
ind.rows as record_count
FROM [$d].sys.schemas AS s
INNER JOIN [$d].sys.tables AS t ON s.[schema_id] = t.[schema_id]
INNER JOIN [$d].sys.sysindexes AS ind ON t.[object_id] = ind.[id]
where ind.indid < 2';
SELECT @sql = @sql + REPLACE(@src, '$d', name)
FROM sys.databases
WHERE database_id > 4
AND [state] = 0
AND HAS_DBACCESS(name) = 1;
SET @sql = STUFF(@sql, 1, 10, CHAR(13) + CHAR(10));
PRINT @sql;
--EXEC sys.sp_executesql @sql;
answered Feb 21, 2019 at 17:02
Jeremy F.Jeremy F.
1,76811 gold badges51 silver badges86 bronze badges
You can copy, past and execute this piece of code to get all table record counts into a table. Note: Code is commented with instructions
create procedure RowCountsPro
as
begin
--drop the table if exist on each exicution
IF OBJECT_ID (N'dbo.RowCounts', N'U') IS NOT NULL
DROP TABLE dbo.RowCounts;
-- creating new table
CREATE TABLE RowCounts
( [TableName] VARCHAR(150)
, [RowCount] INT
, [Reserved] NVARCHAR(50)
, [Data] NVARCHAR(50)
, [Index_Size] NVARCHAR(50)
, [UnUsed] NVARCHAR(50))
--inserting all records
INSERT INTO RowCounts([TableName], [RowCount],[Reserved],[Data],[Index_Size],[UnUsed])
-- "sp_MSforeachtable" System Procedure, 'sp_spaceused "?"' param to get records and resources used
EXEC sp_MSforeachtable 'sp_spaceused "?"'
-- selecting data and returning a table of data
SELECT [TableName], [RowCount],[Reserved],[Data],[Index_Size],[UnUsed]
FROM RowCounts
ORDER BY [TableName]
end
I have tested this code and it works fine on SQL Server 2014.
answered Apr 17, 2019 at 6:50
MujtabaMujtaba
3411 gold badge4 silver badges17 bronze badges
SELECT ( Schema_name(A.schema_id) + '.' + A.NAME ) AS TableName,
Sum(B.rows)AS RecordCount
FROM sys.objects A INNER JOIN sys.partitions B
ON A.object_id = B.object_id WHERE A.type = 'U'
GROUP BY A.schema_id,A.NAME ;
QUERY_PHOTO
QUERY_RESULT_PHOTO
answered Sep 19, 2020 at 9:57
Shnugo’s answer is the ONLY one that works in Azure with Externa Tables. (1) Azure SQL doesn’t support sp_MSforeachtable at all and (2) rows in sys.partitions for an External table is always 0.
answered Dec 23, 2020 at 12:26
VelocedgeVelocedge
1,1681 gold badge10 silver badges33 bronze badges
select T.object_id, T.name, I.indid, I.rows
from Sys.tables T
left join Sys.sysindexes I
on (I.id = T.object_id and (indid =1 or indid =0 ))
where T.type='U'
Here indid=1
means a CLUSTERED index and indid=0
is a HEAP
Ben
51.4k36 gold badges127 silver badges148 bronze badges
answered Jun 22, 2014 at 12:15
1
In this article, we are going to write an SQL query to count the number of rows in a table. For is we will be making use of the count() function of SQL. For this article, we will be making use of the Microsoft SQL Server as our database.
Let’s do the same by building a table inside the database and counting its rows. We will first create a database called “geeks” and then create an “Employee” table in this database and will execute our query on that table.
Creating a Database :
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
Using Database :
USE geeks;
Table Definition:
We have the following Employee table in our geeks database :
CREATE TABLE geeks( id int(20) , name varchar(200));
Output:
You can use the below statement to query the description of the created table:
EXEC sp_columns employees;
Adding Data to Table:
Use the below statement to add data to the Employee table:
INSERT INTO geeks(id,name) values(1,'nikhil'); INSERT INTO geeks(id,name) values(2,'kartik');
SQL Query to Count Number of Rows:
The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.
Syntax: SELECT COUNT(colmn_name) from table_name;
Example:
Using ‘ * ‘ we get all the rows as shown below:
SELECT * FROM geeks;
This will result in the below image:
The table we will be operating has 2 rows. So let’s feed in the query to get the no. of rows a specific column(say, id)as:
SELECT COUNT(id) from geeks;
Output:
We can even change the display name for displaying count:
SELECT COUNT(id) as id_count FROM geeks
Output:
Last Updated :
13 Apr, 2021
Like Article
Save Article
title | description | author | ms.author | ms.reviewer | ms.date | ms.service | ms.subservice | ms.topic | f1_keywords | helpviewer_keywords | dev_langs | monikerRange | ||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
COUNT (Transact-SQL) |
COUNT (Transact-SQL) |
markingmyname |
maghan |
randolphwest |
11/21/2022 |
sql |
t-sql |
reference |
|
|
TSQL |
>= aps-pdw-2016 || = azuresqldb-current || = azure-sqldw-latest || >= sql-server-2016 || >= sql-server-linux-2017 || = azuresqldb-mi-current |
COUNT (Transact-SQL)
[!INCLUDE sql-asdb-asdbmi-asa-pdw]
This function returns the number of items found in a group. COUNT
operates like the COUNT_BIG function. These functions differ only in the data types of their return values. COUNT
always returns an int data type value. COUNT_BIG
always returns a bigint data type value.
:::image type=”icon” source=”../../includes/media/topic-link-icon.svg” border=”false”::: Transact-SQL syntax conventions
Syntax
Aggregation function syntax
COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )
Analytic function syntax
COUNT ( [ ALL ] { expression | * } ) OVER ( [ <partition_by_clause> ] )
[!INCLUDEsql-server-tsql-previous-offline-documentation]
Arguments
ALL
Applies the aggregate function to all values. ALL serves as the default.
DISTINCT
Specifies that COUNT
returns the number of unique nonnull values.
expression
An expression of any type, except image, ntext, or text. COUNT
doesn’t support aggregate functions or subqueries in an expression.
*
Specifies that COUNT
should count all rows to determine the total table row count to return. COUNT(*)
takes no parameters and doesn’t support the use of DISTINCT. COUNT(*)
doesn’t require an expression parameter because by definition, it doesn’t use information about any particular column. COUNT(*)
returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.
OVER ( [ partition_by_clause ] [ order_by_clause ] [ ROW_or_RANGE_clause ] )
The partition_by_clause divides the result set produced by the FROM
clause into partitions to which the COUNT
function is applied. If not specified, the function treats all rows of the query result set as a single group. The order_by_clause determines the logical order of the operation. See OVER clause (Transact-SQL) for more information.
Return types
-
int NOT NULL when
ANSI_WARNINGS
isON
, however SQL Server will always treatCOUNT
expressions asint NULL
in metadata, unless wrapped inISNULL
. -
int NULL when
ANSI_WARNINGS
isOFF
.
Remarks
COUNT(*)
withoutGROUP BY
returns the cardinality (number of rows) in the resultset. This includes rows comprised of all-NULL
values and duplicates.COUNT(*)
withGROUP BY
returns the number of rows in each group. This includesNULL
values and duplicates.COUNT(ALL <expression>)
evaluates expression for each row in a group, and returns the number of nonnull values.COUNT(DISTINCT *expression*)
evaluates expression for each row in a group, and returns the number of unique, nonnull values.
COUNT
is a deterministic function when used without the OVER and ORDER BY clauses. It is nondeterministic when used with the OVER and ORDER BY clauses. For more information, see Deterministic and nondeterministic functions.
ARITHABORT
and ANSI_WARNINGS
When COUNT
has a return value exceeding the maximum value of int (that is, 231-1 or 2,147,483,647), the COUNT
function will fail due to an integer overflow. When COUNT
overflows and both the ARITHABORT
and ANSI_WARNINGS
options are OFF
, COUNT
will return NULL
. Otherwise, when either of ARITHABORT
or ANSI_WARNINGS
are ON
, the query will abort and the arithmetic overflow error Msg 8115, Level 16, State 2; Arithmetic overflow error converting expression to data type int.
will be raised. To correctly handle these large results, use COUNT_BIG
instead, which returns bigint.
When both ARITHABORT
and ANSI_WARNINGS
are ON
, you can safely wrap COUNT
call-sites in ISNULL( <count-expr>, 0 )
to coerce the expression’s type to int NOT NULL
instead of int NULL
. Wrapping COUNT
in ISNULL
means any overflow error will be silently suppressed, which should be considered for correctness.
Examples
A. Use COUNT and DISTINCT
This example returns the number of different titles that an [!INCLUDEssSampleDBCoFull] employee can hold.
SELECT COUNT(DISTINCT Title) FROM HumanResources.Employee; GO
[!INCLUDEssResult]
-----------
67
(1 row(s) affected)
B. Use COUNT(*)
This example returns the total number of [!INCLUDEssSampleDBCoFull] employees.
SELECT COUNT(*) FROM HumanResources.Employee; GO
[!INCLUDEssResult]
-----------
290
(1 row(s) affected)
C. Use COUNT(*) with other aggregates
This example shows that COUNT(*)
works with other aggregate functions in the SELECT
list. The example uses the [!INCLUDEssSampleDBnormal] database.
SELECT COUNT(*), AVG(Bonus) FROM Sales.SalesPerson WHERE SalesQuota > 25000; GO
[!INCLUDEssResult]
----------- ---------------------
14 3472.1428
(1 row(s) affected)
D. Use the OVER clause
This example uses the MIN
, MAX
, AVG
and COUNT
functions with the OVER
clause, to return aggregated values for each department in the [!INCLUDEssSampleDBnormal] database HumanResources.Department
table.
SELECT DISTINCT Name , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary , COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept FROM HumanResources.EmployeePayHistory AS eph JOIN HumanResources.EmployeeDepartmentHistory AS edh ON eph.BusinessEntityID = edh.BusinessEntityID JOIN HumanResources.Department AS d ON d.DepartmentID = edh.DepartmentID WHERE edh.EndDate IS NULL ORDER BY Name;
[!INCLUDEssResult]
Name MinSalary MaxSalary AvgSalary EmployeesPerDept
----------------------------- --------------------- --------------------- --------------------- ----------------
Document Control 10.25 17.7885 14.3884 5
Engineering 32.6923 63.4615 40.1442 6
Executive 39.06 125.50 68.3034 4
Facilities and Maintenance 9.25 24.0385 13.0316 7
Finance 13.4615 43.2692 23.935 10
Human Resources 13.9423 27.1394 18.0248 6
Information Services 27.4038 50.4808 34.1586 10
Marketing 13.4615 37.50 18.4318 11
Production 6.50 84.1346 13.5537 195
Production Control 8.62 24.5192 16.7746 8
Purchasing 9.86 30.00 18.0202 14
Quality Assurance 10.5769 28.8462 15.4647 6
Research and Development 40.8654 50.4808 43.6731 4
Sales 23.0769 72.1154 29.9719 18
Shipping and Receiving 9.00 19.2308 10.8718 6
Tool Design 8.62 29.8462 23.5054 6
(16 row(s) affected)
Examples: [!INCLUDEssazuresynapse-md] and [!INCLUDEssPDW]
E. Use COUNT and DISTINCT
This example returns the number of different titles that an employee of a specific company can hold.
USE ssawPDW; SELECT COUNT(DISTINCT Title) FROM dbo.DimEmployee;
[!INCLUDEssResult]
F. Use COUNT(*)
This example returns the total number of rows in the dbo.DimEmployee
table.
USE ssawPDW; SELECT COUNT(*) FROM dbo.DimEmployee;
[!INCLUDEssResult]
G. Use COUNT(*) with other aggregates
This example combines COUNT(*)
with other aggregate functions in the SELECT
list. It returns the number of sales representatives with an annual sales quota greater than $500,000, and the average sales quota of those sales representatives.
USE ssawPDW; SELECT COUNT(EmployeeKey) AS TotalCount, AVG(SalesAmountQuota) AS [Average Sales Quota] FROM dbo.FactSalesQuota WHERE SalesAmountQuota > 500000 AND CalendarYear = 2001;
[!INCLUDEssResult]
TotalCount Average Sales Quota
---------- -------------------
10 683800.0000
H. Use COUNT with HAVING
This example uses COUNT
with the HAVING
clause to return the departments of a company, each of which has more than 15 employees.
USE ssawPDW; SELECT DepartmentName, COUNT(EmployeeKey)AS EmployeesInDept FROM dbo.DimEmployee GROUP BY DepartmentName HAVING COUNT(EmployeeKey) > 15;
[!INCLUDEssResult]
DepartmentName EmployeesInDept
-------------- ---------------
Sales 18
Production 179
I. Use COUNT with OVER
This example uses COUNT
with the OVER
clause, to return the number of products contained in each of the specified sales orders.
USE ssawPDW; SELECT DISTINCT COUNT(ProductKey) OVER(PARTITION BY SalesOrderNumber) AS ProductCount , SalesOrderNumber FROM dbo.FactInternetSales WHERE SalesOrderNumber IN (N'SO53115',N'SO55981');
[!INCLUDEssResult]
ProductCount SalesOrderID
------------ -----------------
3 SO53115
1 SO55981
See also
- Aggregate Functions (Transact-SQL)
- COUNT_BIG (Transact-SQL)
- OVER Clause (Transact-SQL)