Ordering your SQL records with ORDER BY
You can also order your SQL query results. For example, if you wanted to get all records from the Customer
table of the Chinook database and order them in increasing order by the column SupportRepId
, you could do so with the following query:
"SELECT * FROM Customer ORDER BY SupportRepId"
In fact, you can order any SELECT
statement by any column.
In this interactive exercise, you'll select all records of the Employee
table and order them in increasing order by the column BirthDate
.
Packages are already imported as follows:
import pandas as pd
from sqlalchemy import create_engine
Get querying!
This exercise is part of the course
Introduction to Importing Data in Python
Exercise instructions
- Using the function
create_engine()
, create an engine for the SQLite databaseChinook.sqlite
and assign it to the variableengine
. - In the context manager, execute the query that selects all records from the
Employee
table and orders them in increasing order by the columnBirthDate
. Assign the result tors
. - In a call to
pd.DataFrame()
, apply the methodfetchall()
tors
in order to fetch all records inrs
. Store them in the DataFramedf
. - Set the DataFrame's column names to the corresponding names of the table columns.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Create engine: engine
# Open engine in context manager
with engine.connect() as con:
rs = ____
df = ____
# Set the DataFrame's column names
# Print head of DataFrame
print(df.head())