Data Extraction & Integrity Constraints

In this lab, we will use the football datasets.

Data Extraction with SQL & Python

DE with SQL (continued)

SQL Queries with Aggregate Functions
  1. Write an SQL query that returns the names of the teams and the total number of goals scored by the players of that team.

  2. SELECT teamname, Count(*) FROM goal 
    JOIN teams ON teamid = id
    GROUP BY teamid
  3. Assuming that every match lasts for 90 minutes, write an SQL query that returns the average scoring time for the Spanish team (total number of minutes played divided by the total number of goals scored).

  4. 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')
  5. Write an SQL query that returns the number of players who scored goals from the Spanish, Dutch, Polish, and Greek teams.

  6. SELECT Count(*) AS number_of_players_scored FROM  
    (SELECT DISTINCT player FROM goal
     WHERE teamid IN  ('ESP', 'NED', 'POL', 'GRE'))
  7. Given the query below, answer the following questions:

    1. What does this query do?

    2. Why we used HAVING?

    3. What do we need to do in order to replace HAVING by WHERE?

  8. SELECT player, count(*) as number_of_goals 
    FROM goal 
    GROUP BY player 
    HAVING number_of_goals  >  2;
    Answer
    1. 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.

    2. Because we used GROUP BY, we cannot use WHERE to specify the condition. Instead, we specify the condition using the HAVING statement

    3. We use subquery as follows:

    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.

Creating DataFrames
Creating a DataFrame from Pandas Series
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        
        
Creating a DataFrame from Data Matrix
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        
        
Printing the number of columns and the number of rows in a DataFrame
print("number of columns = ", len(df.columns))
print("number of rows = ", len(df))
Creating a DataFrame using data stored in a csv file
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.

Extracting Data from Pandas DataFrames

Use the california_housing_train dataset in the following exercises:

Extracting rows and blocks
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
Extracting columns
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
Extracting rows
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
Extracting rows that satisfy a specific condition
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]]

Profiling the DataFrames

We will also use the california_housing_train dataset in the following exercises:

Displaying the names of the attributes
TODO: print the names of the columns (attributes) of the dataframe.

You can access the name of the attributes using df.columns

df.columns
Displaying the datatype of each column
dataTypeSeries = df.dtypes
for col_idx in range(len(df.columns)):
    print(df.columns[col_idx], 'has type (', dataTypeSeries[col_idx], ')')
Displaying the number of unique values in each column
for col in  df.columns:
    print(col, ' has (', len(df[col].unique()), ') unique values')
displaying quantities of interest such as min, max, …
# 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())
counting the missing values
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')
Connecting to an SQLite DB

First, we need to import the required library. The sqlite3 library is installed by default on Google Colab.

Creating connection to the databse

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
Querying the database

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
        
Creating a DataFrame from the query 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 
Example

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) 
Exercise

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)
Merging DataFrames

This is equivalent to the union and join operator in RA and SQL.

Finding the union of two tables

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
Joining two tables

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.

  1. Identify and define the PRIMARY KEYS for each of the relations (goal, game, teams).

  2. The list of attributes that represent a primary key for each relation are listed in the table below.
    table (relation) Primary Key
    game id
    teams id
    goal (matchid, teamid, player, gtime)
    To define the PRIMARY KEY for the table goal, we use:
    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.
  3. 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.

  4. 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 
    );
  5. 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).

  6. 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:
    1. First, rename the existing table as teams_old

    2. ALTER TABLE teams RENAME TO teams_old
    3. Second, we create the table teams with the added attribute

    4. 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)
      );
    5. Third, copy the data from the table teams_old to the new table

    6. INSERT INTO teams(id, teamname, coach) SELECT id, teamname, coach FROM teams_old
    7. Finally, delete the old table:

    8. DROP TABLE teams_old
  7. 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?

  8. 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;
  9. Try the following query: INSERT INTO teams values("FRA", "France", "Zidane"). Will the query work or not and why?

  10. 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:
    Execution finished with errors.
    Result: UNIQUE constraint failed: teams.id
Useful Queries
Display the schema of a relation
PRAGMA table_info(tab_name)
Display the schema of a relation
PRAGMA table_info(tab_name)
Check if the referential integrity is forced or not
PRAGMA foreign_keys;
Force the referential integrity
PRAGMA foreign_keys = 1;