0

I have a database containing a table and I want to compute the mean of a column without importing all of the rows and doing it directly in python; I think doing that would take longer (computation-wise and code-wise) than doing it using sqlite. I figured that the following should work:

cursor.execute('SELECT AVG(column) FROM table')

However, I have no idea how to actually extract the output of this SQL command. I can't find a useful method of the cursor class in the documentation (https://docs.python.org/3/library/sqlite3.html) to help me with this.

Please tell me if what I'm doing makes no sense or is stupid; I have not used SQL before so it might be either of both of the above.

Thank you

2
  • 1
    See stackoverflow.com/questions/3687412/… Commented Apr 11, 2017 at 20:10
  • 1
    The result has a single column and a single row, but that's not fundamentally different from any other query result. Commented Apr 11, 2017 at 20:13

1 Answer 1

2

Not sure of your other code, but I think you're looking for the .fetchone() method. Something along these lines should work:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('SELECT AVG(column) FROM table')
print(c.fetchone())

.fetchone() method returns one result, if you're looking to return more than one result from an execute you would use a loop like:

for row in c.execute('SELECT * FROM table')
    print(row)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.