Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL count rows in a table

I need to send a SQL query to a database that tells me how many rows there are in a table. I could get all the rows in the table with a SELECT and then count them, but I don't like to do it this way. Is there some other way to ask the number of the rows in a table to the SQL server?

like image 308
Celeste Capece Avatar asked Mar 07 '15 16:03

Celeste Capece


People also ask

How do I count rows in a table in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do I count the number of rows in a SQL group?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.

What does count (*) do in SQL?

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.

Which statement is used to count rows in a table?

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.


2 Answers

Yes, SELECT COUNT(*) FROM TableName

like image 121
CyberDude Avatar answered Oct 04 '22 01:10

CyberDude


select sum([rows]) from sys.partitions where object_id=object_id('tablename')  and index_id in (0,1) 

is very fast but very rarely inaccurate.

like image 29
benjamin moskovits Avatar answered Oct 04 '22 01:10

benjamin moskovits