Data Extraction & Integrity Constraints
In this lab, we will use the football datasets.
Data Extraction with SQL & Python
DE with SQL (continued)
-
Write an
SQLquery that returns the names of the teams and the total number of goals scored by the players of that team. -
Assuming that every match lasts for 90 minutes, write an
SQLquery that returns the average scoring time for the Spanish team (total number of minutes played divided by the total number of goals scored). -
Write an
SQLquery that returns the number of players who scored goals from the Spanish, Dutch, Polish, and Greek teams. Given the query below, answer the following questions:
What does this query do?
Why we used
HAVING?What do we need to do in order to replace
HAVINGbyWHERE?
The query returns a relation with the two attributes (
player, number_of_goals) that contains the names of players who scored more than 2 goals.Because we used
GROUP BY, we cannot useWHEREto specify the condition. Instead, we specify the condition using theHAVINGstatementWe use subquery as follows:
SELECT teamname, Count(*) FROM goal
JOIN teams ON teamid = id
GROUP BY teamid
SELECT tot_time/ESPgoals AS avg_Spain_score_time FROM
(SELECT count(*)*90 AS tot_time FROM game
WHERE team1 = 'ESP' OR team2 = 'ESP')
JOIN
(SELECT count(*) AS ESPgoals FROM goal
WHERE teamid = 'ESP')
SELECT Count(*) AS number_of_players_scored FROM
(SELECT DISTINCT player FROM goal
WHERE teamid IN ('ESP', 'NED', 'POL', 'GRE'))
SELECT player, count(*) as number_of_goals
FROM goal
GROUP BY player
HAVING number_of_goals > 2;
Answer
SELECT player, number_of_goals FROM
(SELECT player, count(*) AS number_of_goals
FROM goal
GROUP BY player)
WHERE number_of_goals > 2;
DE with PYTHON
In the following exercises, you will practice on working with Pandas DataFrames. You will practice on how to extract parts of the data using Python APIs. You will also practice on connecting to an SQLite database, send SQL queries, and extract the results to a Pandas DataFrame. There are parts where the code is available so you need to run the code, understand and comment on the output. There are also a set of exercises where you need to write the code yourself.
First, we need to import the libraries that are required for our code. You can run the code on Google Colab or using your favorite IDE for Python.
import Pandas as pd
import csv
Run the code and comment on the output. After that, solve the exercises with the TODO.
data = {'State': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
'Year': [2000, 2001, 2002, 2001, 2002, 2003],
'Population': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}
df = pd.DataFrame(data)
df
data = [['Ohio', 2000, 1.5], ['Ohio', 2001, 1.7], ['Ohio', 2002, 3.6],
['Nevada', 2001, 2.4],['Nevada', 2002, 2.9], ['Nevada', 2003, 3.2]]
cols = ['State', 'Year', 'Population']
df = pd.DataFrame(data, columns = cols)
df
print("number of columns = ", len(df.columns))
print("number of rows = ", len(df))
df = pd.read_csv( filepath_or_buffer = 'sample_data/california_housing_train.csv',
delimiter = ',', doublequote = True,
quotechar = '"',na_values = ['na', '-', '.', ''],
quoting = csv.QUOTE_ALL, encoding = "ISO-8859-1")
df
You may also use your own dataset or the movies dataset that can be downloaded from this LINK.
Use the california_housing_train dataset in the following exercises:
df.info() # index & data types
n = 4
dfh = df.head(n) # get first n rows
dft = df.tail(n) # get last n rows
top_left_corner_df = df.iloc[:5, :5]
TODO: display the content of dfh, dft, top_left_corner_df.
dfh, dft, top_left_corner_df
This will display the dataframes as arrays in plain text format. It will be hard to read as it will look like:
A better way isto use a separate cell for displaying every dataframe as follows:
dfh
Displays the dataframe in a table format as:

dft
top_left_corner_df
col_set = df.iloc[:, 5:9]
col_set
This code extracts columns 6, 7, 8, 9 assuming the first column is numbered 1 not as the python index 0.
For columns that are not in the same range, we separate the columns indexes with a comma, e.g.
col_set2 = df[df.columns[[6, 8, 11]]][:]
col_set2
TODO: write the code to extract ROWS 11, 13, and 15 from the DataFrame.
row_set = df.iloc[[10, 12, 14], ] # Index in Python starts from 0
row_set
df.loc[(df['total_rooms'] > 5000).values,
['longitude', 'latitude', 'total_rooms', 'median_house_value']]
Another way:
df.loc[(df['total_rooms'] > 5000).values, [0, 1, 3, 8]]
We will also use the california_housing_train dataset in the following exercises:
TODO: print the names of the columns (attributes) of the dataframe.
You can access the name of the attributes using df.columns
df.columns
dataTypeSeries = df.dtypes
for col_idx in range(len(df.columns)):
print(df.columns[col_idx], 'has type (', dataTypeSeries[col_idx], ')')
for col in df.columns:
print(col, ' has (', len(df[col].unique()), ') unique values')
# TODO: print the min, max, average and standard deviation of the attributes with numerical datatype
dataTypeSeries = df.dtypes
for col_idx in range(len(df.columns)):
if (not (dataTypeSeries[col_idx] == 'object')):
print(df.columns[col_idx], 'has Min = ', df[df.columns[col_idx]].min(),
'Max = ', df[df.columns[col_idx]].max(),
'Average = ', df[df.columns[col_idx]].mean(),
'Standard Deviation = ', df[df.columns[col_idx]].std())
s = df['longitude'].isnull()
s.sum()
# TODO: print the name of each column in the dataframe and the number of missing values in that column.
The code above counts the number of missing values for a single column, we need to repeat that for all columns.
for column in df.columns:
s = df[column].isnull().sum()
print(column, 'has (', s, ') missing values')
First, we need to import the required library. The sqlite3 library is installed by default on Google Colab.
The following function receives the name of the database file as input and returns a connector to the database.
def create_connection( db_file):
""" create a database connection to the SQLite database specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
Sending a query to the database and receiving the resulting relation can be done through the following function, which receives a connector and a query and returns the results after running the query.
def run_query(conn, query):
"""
Query all rows in the teams table
:param conn: the Connection object
:return: the results of executing the query
"""
# Create a cursor
cur = conn.cursor()
# Send the query to the database
cur.execute(query)
# Extract the results of the query
results = cur.fetchall()
# Return the results
return results
The following function receives a connector and table name, then it sends two queries to get the names of the columns and the data. After receiving the query output, it creates a Pandas dataframe and returns it.
def convert_db_table_to_DF(conn, table):):
# get the names of the attributes in the database table
header_query = "SELECT name FROM pragma_table_info('" + table + "') ORDER BY cid;"
cols_init = run_query(conn, header_query)
cols = [cols_init[i][0] for i in range(len(cols_init))]
# get the records of the table
content_query = "Select * FROM " + table
data = run_query(conn, content_query)
df = pd.DataFrame(data, columns = cols)
return df
Querying the database to get the names of the tables in the database.
database = "sample_data/football.db"
# create a database connection
conn = create_connection(database)
with conn:
query = 'SELECT name FROM sqlite_schema WHERE type = "table"'
data = run_query(conn, query)
print(data)
Write your own query
'''
#TODO: Write the code to read the data in the game table, store it in
a DataFrame and display the contents of the DataFrame.
'''
database = "sample_data/football.db"
# create a database connection
conn_fb = create_connection(database)
with conn_fb:
tab_name = 'game'
game = convert_db_table_to_DF(conn_fb, tab_name)
This is equivalent to the union and join operator in RA and SQL.
TODO: read the contents of the files california_housing_train.csv and california_housing_test.csv and store them in df_train and df_test. Find the union the two dataframes and store the results in a DataFrame `df_cal_housing.
df_train = pd.read_csv( filepath_or_buffer = 'sample_data/california_housing_train.csv',
delimiter = ',', doublequote = True,
quotechar = '"',na_values = ['na', '-', '.', ''],
quoting = csv.QUOTE_ALL, encoding = "ISO-8859-1")
df_test = pd.read_csv( filepath_or_buffer = 'sample_data/california_housing_test.csv',
delimiter = ',', doublequote = True,
quotechar = '"',na_values = ['na', '-', '.', ''],
quoting = csv.QUOTE_ALL, encoding = "ISO-8859-1")
union_df = pd.concat([df_train, df_test], axis=0) #You can ignore "axis = 0" as this is the default
union_df
TODO: connect to the football database and read the data in the goals and game relations. Store their contents in two DataFrames df_goal and df_game and join them into df_goal_game dataframe.
database = "sample_data/football.db"
# create a database connection
conn_fb = create_connection(database)
with conn_fb:
tab_name = 'game'
df_game = convert_db_table_to_DF(conn_fb, tab_name)
with conn_fb:
tab_name = 'goal'
df_goal = convert_db_table_to_DF(conn_fb, tab_name)
df_merge_col = pd.merge(df_goal, df_game, left_on = 'matchid', right_on = 'id')
df_merge_col
Integrity Constraints & Database Design
Integrity constraints are arbitrary predicates that ensure the consistency and the validity of the values in a database. They act as guards against any accidental damage that could happen to the database. In the following exercises, you will practice using a set of integrity constraints that have been studied during the lecture.
Identify and define the PRIMARY KEYS for each of the relations (goal, game, teams).
The list of attributes that represent a primary key for each relation are listed in the table below.
Identify and define the FOREIGN KEYS in each of the relations in the previous question. Define how you would like to enforce the Referential Integrity.
Add an attribute Confederation in the table teams, where the values are restricted to be from the list (UEFA, CONMEBOL, CAF, AFC, CONCACAF, OFC and CONIFA).
Since we need to define constraints on the new attribute, we cannot use ALTER TABLE table_name ADD COLUMN column_name. Instead, we will create a new copy of the table with the new constraints:
First, rename the existing table as teams_old
Second, we create the table teams with the added attribute
Third, copy the data from the table teams_old to the new table
Finally, delete the old table:
Write an SQL query to remove the record of the teams with id = "ESP". Will the query work by default or not. If it didn't work, what do you need to do?
Try the following query: INSERT INTO teams values("FRA", "France", "Zidane"). Will the query work or not and why?
If the referential integrity is OFF, there will no error and the record will be inserted in the table. However, if the referential integrity is ON, we will receive the following error message:
| table (relation) | Primary Key |
|---|---|
| game | id |
| teams | id |
| goal | (matchid, teamid, player, gtime) |
CREATE TABLE goal (
"matchid" INTEGER NOT NULL,
"teamid" CHAR(3),
"player" VARCHAR(50) NOT NULL,
"gtime" numeric NOT NULL,
PRIMARY KEY (matchid, teamid, player, gtime)
);
You can use similar code to define the primary key for the tables game and teams. We can create a new database with the new definition of the tables.
CREATE TABLE IF NOT EXISTS goal (
"matchid" INTEGER NOT NULL,
"teamid" CHAR(3) NOT NULL,
"player" VARCHAR(50) NOT NULL,
"gtime" numeric NOT NULL,
PRIMARY KEY (matchid, teamid, player, gtime),
FOREIGN KEY ("matchid") REFERENCES "game" ON DELETE CASCADE,
FOREIGN KEY ("teamid") REFERENCES "teams" ON DELETE CASCADE
);
ALTER TABLE teams RENAME TO teams_old
CREATE TABLE IF NOT EXISTS teams (
"id" CHAR(3) NOT NULL,
"teamname" VARCHAR(50) ,
"coach" VARCHAR(50),
"Confederation" VARCHAR(50) CHECK(Confederation IN ("UEFA", "CONMEBOL", "CAF", "AFC", "CONCACAF", "OFC", "CONIFA")),
PRIMARY KEY (id)
);
INSERT INTO teams(id, teamname, coach) SELECT id, teamname, coach FROM teams_old
DROP TABLE teams_old
DELETE FROM teams
WHERE id = 'ESP';
If the referential integrity is forced, the query will succeed if the policy is SET NULL, SET DEFAULT or CASCADE. If the policy is No ACTION, the query will not work. However, we can turn the referential integrity off using:
PRAGMA foreign_keys = OFF;
Execution finished with errors.
Result: UNIQUE constraint failed: teams.id
PRAGMA table_info(tab_name)
PRAGMA table_info(tab_name)
PRAGMA foreign_keys;
PRAGMA foreign_keys = 1;