3

I am trying to print count of rows available in table of bigquery in python,I have written below code:

from google.cloud import bigquery def main():
    myquery = "select count(*) from `myproject.mydataset.mytable`"
    client = bigquery.Client()
    job = client.query(myquery)
    result = job.result()
    print("Total rows available: ",result)

When I execute above code it gives me output as

"Total rows available: google.cloud.bigquery.table.RowIterator object at 0x00000247B65F29E8>".

It means I am getting object value as my output. But I want to print actual count of rows available in my table(query result).

Nico Griffioen
  • 5,143
  • 2
  • 27
  • 36
Kaustubh Ghole
  • 537
  • 1
  • 10
  • 25
  • It'd probably be better if you used the [Table](https://googleapis.dev/python/bigquery/latest/usage/tables.html) object to do so. See the example for connecting with your table then just print [`table.num_rows`](https://github.com/googleapis/google-cloud-python/blob/master/bigquery/google/cloud/bigquery/table.py#L530); this operation would be free of charge and much faster. – Willian Fuks Oct 11 '19 at 00:06

2 Answers2

7

RowIterator has an attribute called total_rows.

Simply change your last statement to

 print("Total rows available: ", result.total_rows)
Nico Griffioen
  • 5,143
  • 2
  • 27
  • 36
  • I just tried this way but it gives me "Total rows available: None" as output. But in actual I have 634700 rows in that respective BQ table (output if i run same query from BQ console). – Kaustubh Ghole Oct 10 '19 at 11:57
  • 1
    In any case, expected result with this change only should be 1. As count returns one row. – Stav Hacohen Mar 26 '21 at 11:07
  • No. `result.total_rows` and `result.num_results` only report how many results have been iterated and show None or 0 before you start to iterate over the RowIterator – Mark B Oct 07 '21 at 13:56
  • `results.total_rows` is perfect. https://cloud.google.com/bigquery/docs/samples/bigquery-query-total-rows – Ryan Loggerythm Dec 05 '22 at 18:13
5

Try changing your query to

myquery = "select count(*) size from `myproject.mydataset.mytable`"
client = bigquery.Client()
job = client.query(myquery)
result = job.result()
for row in results:
    print("Total rows available: ",row.size)
Bobbylank
  • 1,906
  • 7
  • 15