Kaustubh Ghole
Kaustubh Ghole

Reputation: 577

How to print count table query of bigquery in python?

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).

Upvotes: 4

Views: 17653

Answers (3)

Jeff Oberlander
Jeff Oberlander

Reputation: 78

BigQuery first returns a query object and from there you can get the result using .result(). But that is an Iterator object so you have to iterate to get the values. In a count (*) you know that there is only one row to iterate on so you can use "next". And that returns a row with one value in it and thus the [0].

    myquery = "select count(*) from `myproject.mydataset.mytable`"
    iterator = client.query(myquery).result()
    first_row = next(iterator)
    print("Total rows available: ",first_row[0])

Upvotes: 0

Bobbylank
Bobbylank

Reputation: 1946

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)

Upvotes: 5

Nico Griffioen
Nico Griffioen

Reputation: 5405

RowIterator has an attribute called total_rows.

Simply change your last statement to

 print("Total rows available: ", result.total_rows)

Upvotes: 6

Related Questions