Filter data selected from a Table - Simple
Having connected to the database, it's now time to practice filtering your queries!
As mentioned in the video, a where() clause is used to filter the data that
a statement returns. For example, to select all the records from the census table where the sex is
Female (or 'F') we would do the following:
select([census]).where(census.columns.sex == 'F')
In addition to == we can use basically any python comparison operator (such as <=,
!=, etc) in the where() clause.
Cet exercice fait partie du cours
Introduction to Databases in Python
Instructions
- Select all records from the
censustable by passing incensusas a list toselect(). - Append a
whereclause tostmtto return only the records with astateof'New York'. - Execute the statement
stmtusing.execute()onconnectionand retrieve the results using.fetchall(). - Iterate over
resultsand print theage,sexandpop2000columns from each record. For example, you can print out theageofresultwithresult.age.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# Create a select query: stmt
stmt = ____
# Add a where clause to filter the results to only those for New York : stmt_filtered
stmt = stmt.____
# Execute the query to retrieve all the data returned: results
results = ____
# Loop over the results and print the age, sex, and pop2000
for ___ in ____:
print(result.age, ____, ____)