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!
Deze oefening maakt deel uit van de cursus
Introduction to Importing Data in Python
Oefeninstructies
- Using the function
create_engine(), create an engine for the SQLite databaseChinook.sqliteand assign it to the variableengine. - In the context manager, execute the query that selects all records from the
Employeetable and orders them in increasing order by the columnBirthDate. Assign the result tors. - In a call to
pd.DataFrame(), apply the methodfetchall()torsin 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.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
# 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())