Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a row count in DBI without running two separate calls to process?

Tags:

perl

dbi

I'm running DBI in Perl and can't figure out how, when I run a prepared statement, I can figure out if the returned row count is 0.

I realize I can set a counter inside my while loop where I fetch my rows, but I was hoping there was a less ugly way to do it.

like image 279
Yevgeny Simkin Avatar asked May 12 '09 22:05

Yevgeny Simkin


People also ask

How do I count all rows?

If you need a quick way to count rows that contain data, select all the cells in the first column of that data (it may not be column A). Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count.

How do I get row count in SQL SELECT query?

In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.

How do you find the total number of rows in each table of the schema?

This can be achieved by using the following query. SELECT table_schema, SUM(row_count) AS total_rows FROM ( SELECT table_schema, count_rows_of_table(table_schema, table_name) AS row_count FROM information_schema.

How do I count rows in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.


2 Answers

The "caveat" in the documentation (linked to in a comment on another answer) is important, and provides the real, correct answer:

Generally, you can only rely on a row count after a non-SELECT execute (for some specific operations like UPDATE and DELETE), or after fetching all the rows of a SELECT statement.

For SELECT statements, it is generally not possible to know how many rows will be returned except by fetching them all. Some drivers will return the number of rows the application has fetched so far, but others may return -1 until all rows have been fetched. So use of the rows method or $DBI::rows with SELECT statements is not recommended.

like image 85
John Siracusa Avatar answered Sep 28 '22 20:09

John Siracusa


Based on a quick look here, it seems that after you run

$statement->execute($arg)

you can access the row count via

$statement->rows
like image 22
Harper Shelby Avatar answered Sep 28 '22 20:09

Harper Shelby