Functional Dependency & Hashing and Indexing
Overview
In this lab, we will work on functional dependencies and how can we use them to decide on relation decomposition. We will also work with indices and evaluate how they speed-up the process of querying databases.
Functional Dependency
Functional dependency is a constraint between the attributes that represents a tool for measuring whether the grouping of the attributes into relation schemas is appropriate or not.
Suppose that we decompose the schema $R(A, B, C,D, E)$ into $$R_1 = (A, B, C),$$ $$R_2 = (A, D, E)$$
Show that this decomposition is a lossless decomposition if the following set $\mathfrak{F}$ of functional dependencies holds:
$A\longmapsto BC$
$CD\longmapsto E$
$B\longmapsto D$
$E\longmapsto A$
Solution:
A decomposition $\{R_1, R_2\}$ is a lossless decomposition if $R_1 \bigcap R_2 \longmapsto R_1$ OR $R_1 \bigcap R_2 \longmapsto R_2.$
Since $R_1 = (A, B, C),R_2 = (A, D, E)$, then $R_1 \bigcap R_2 = \{A\}$ and $A\longmapsto BC$. This means $A\longmapsto B$ and $A\longmapsto C$.
Hence, $R_1 \bigcap R_2 = A\longmapsto R_1$.
Show that if we combine the relations goal and teams into teams_goals (matchid, teamid, teamname, player, coach, gtime) then the resulting relation is not in Boyce–Codd normal form (BCNF).
Solution:
For a relation $R$ to be in BCNF, any FD $X\longmapsto Y$ with $X \subseteq R$ and $Y \subseteq R$ should satisfy:
Either $X\longmapsto Y$ is a trivial FD; or
$X$ is a super key in $R$.
However, we know that $teamid\longmapsto teamname$. Since this FD is not trivial and $teamid$ is not a super key in the relation teams_goals, then the relation teams_goals is not in BCNF.
Given the relation $R(A, B, C, D, E, F, G)$, the following functional dependencies are non-trivial FDs over $R$:
$\mathfrak{F}= \{ $
$\ \ \ \ ABD\longmapsto EG,$
$\ \ \ \ C\longmapsto DG,$
$\ \ \ \ E\longmapsto FG,$
$\ \ \ \ AB\longmapsto C,$
$\ \ \ \ G\longmapsto F$
$\}$.
Find the candidate key for $R$.
Solution:
Using Armstrong’s axioms, we can find that $AB \longmapsto X, \ \ \ \ \forall X \in R$, which means that $AB$ is the primary key of $R$.
$$ \begin{cases} C \longmapsto DG \end{cases} \quad \Longrightarrow \left\lbrace \begin{array}{r@{\;}l} % make space to RHS of \in and = symbols equal to that used for mathrel items C \longmapsto D \\ C \longmapsto G \end{array} \right. $$ $$ \begin{cases} AB \longmapsto C\\ C \longmapsto D \\ C \longmapsto G \\ G \longmapsto F \end{cases} \quad \Longrightarrow \left\lbrace \begin{array}{r@{\;}l} % make space to RHS of \in and = symbols equal to that used for mathrel items AB \longmapsto C \\ AB \longmapsto D \\ AB \longmapsto G \\ AB \longmapsto F \end{array} \right. $$ $$ \begin{cases} ABD \longmapsto EG\\ AB \longmapsto D \end{cases} \quad \Longrightarrow \begin{array}{r@{\;}l} % make space to RHS of \in and = symbols equal to that used for mathrel items AB \longmapsto EG \end{array} \quad \Longrightarrow \left\lbrace \begin{array}{r@{\;}l} % make space to RHS of \in and = symbols equal to that used for mathrel items AB \longmapsto E \\ AB \longmapsto G \end{array} \right. $$We can see that $AB\longmapsto R$ since they determine all other attributes. Hence, $AB$ is a superkey. Moreover, no single attribute can determince $R$, which satisfy that $AB$ is the minimal set of attributes that can determine $R$. is a key candidate and since no single attribute can determine all other attributes, is a primary key.
In the Football Database that we have been using, perform the following tasks:
Join the relations goal and game into goal_game (matchid, teamid, player, gtime, mdate, stadium, team1, team2) and display the content of the new relation.
We start by creating a new table goal_game:
After that, we copy the content of the join into the newly created table:
To display the content of the new relation, we use:
Save the resulting relation in the database.
Split the relation goal_game back into two relations goal_1 (matchid, teamid, player, gtime) and game_1(id, mdate, stadium, team1, team2).
Solution:
CREATE TABLE goal_game(
"matchid" INTEGER,
"teamid" CHAR (3),
"player" CHAR (50),
"gtime" NUMERIC,
"mdate" VARCHAR (20),
"stadium" VARCHAR(50),
"team1" CHAR(3),
"team2" CHAR(3)
);
INSERT INTO goal_game SELECT matchid, teamid, player, gtime, mdate, stadium, team1, team2
FROM goal a JOIN game b ON a.matchid = b.id
SELECT * FROM goal_game
Solution:
This step was done when we created the table and copied the results of the join query inside the table.
Solution:
We will create two new relations similar to the original relations of instructor and department but we will not specifiy the primary/foreign keys as follow:
CREATE TABLE IF NOT EXISTS goal_1 (
matchid INTEGER,
teamid CHAR(3),
player VARCHAR(50),
gtime NUMERIC
);
INSERT INTO goal_1 SELECT matchid, teamid, player, gtime FROM goal_game;
Table goal_1 will include exactly the same data as table goal.
CREATE TABLE IF NOT EXISTS game_1 (
id INTEGER,
mdate VARCHAR(20),
stadium VARCHAR(50),
team1 CHAR(3),
team2 CHAR(3)
);
INSERT INTO game_1 SELECT matchid, mdate, stadium, team1, team2 FROM goal_game;
Table game_1 will contain duplicate records for those matches where more than one goal were scored. SQL allows for having duplicates. However, we can copy only the records with distinct matchid as:
CREATE TABLE IF NOT EXISTS game_1 (
id INTEGER,
mdate VARCHAR(20),
stadium VARCHAR(50),
team1 CHAR(3),
team2 CHAR(3)
);
INSERT INTO game_1 SELECT DISTINCT matchid, mdate, stadium, team1, team2 FROM goal_game;
Compare the entries in the goal relation with those in the goal_1 and those in the game with those in the game_1. Comment on your findings.
Solution:
The new tables will include the same data as the original ones when inserting only the distinct records to table game_1. Based on that, if we join the tables again, we will get the same table goal_game. That means, splitting table goal_game into goal_1 and game_1 is a lossless decomposition.
We can also see that $goal\_1 \bigcap game\_1 = matchid$, which is the PRIMARY KEY for table $game\_1$.
Now, split the relation goal_game back into two relations: goal_2 (matchid, teamid, player, gtime, stadium) and game_2 (stadium, mdate, team1, team2).
CREATE TABLE IF NOT EXISTS goal_2 (
matchid INTEGER,
teamid CHAR(3),
player VARCHAR(50),
gtime NUMERIC,
stadium VARCHAR(50)
);
INSERT INTO goal_2 SELECT DISTINCT matchid, teamid, player, gtime, stadium FROM goal_game;
CREATE TABLE IF NOT EXISTS game_2 (
stadium VARCHAR(50),
mdate VARCHAR(20),
team1 CHAR(3),
team2 CHAR(3)
);
INSERT INTO game_2 SELECT DISTINCT stadium, mdate, team1, team2 FROM goal_game;
Join the relations goal_2 and game_2 into goal_game_2 (matchid, teamid, player, gtime, mdate, stadium, team1, team2).
CREATE TABLE IF NOT EXISTS goal_game_2(
matchid INTEGER,
teamid CHAR(3),
player VARCHAR(50),
gtime NUMERIC,
mdate VARCHAR(20),
stadium VARCHAR(15),
team1 CHAR(3),
team2 CHAR(3)
);
INSERT INTO goal_game_2(matchid, teamid, player, gtime, mdate, stadium, team1, team2)
SELECT matchid, teamid, player, gtime, mdate, L.stadium, team1, team2 FROM goal_2 L
JOIN game_2 M
ON L.stadium = M.stadium
Compare the relation goal_game with the relation goal_game_2.
Solution:
Table goal_game_2 will have more records as every goal scored in a given stadium will appear in all the games that played in that stadium. We can see that splitting the goal_game relation into goal_2 and game_2 is a lossy decomposition as more incorrect records will be formed when we join these relations. Theoretically, since $goal\_2 \bigcap game\_2$ is not a primary key in $goal\_2$ or $game\_2$, then the decomposition of goal_game into goal_2 and game_2 is a a lossy decomposition.
Split the relation goal_game_2 back into two relations: goal_3 (matchid, teamid, player, gtime) and game_3 (id, mdate, stadium, team1, team2). Compare the entries in the goal relation with those in the goal_3 and those in the game with those in the game_3. Comment on your findings.
CREATE TABLE IF NOT EXISTS goal_3 (
matchid INTEGER,
teamid CHAR(3),
player VARCHAR(50),
gtime NUMERIC
);
INSERT INTO goal_3 SELECT DISTINCT matchid, teamid, player, gtime FROM goal_game_2;
CREATE TABLE IF NOT EXISTS game_3 (
id INTEGER,
mdate VARCHAR(20),
stadium VARCHAR(50),
team1 CHAR(3),
team2 CHAR(3)
);
INSERT INTO game_3 SELECT DISTINCT matchid, mdate, stadium, team1, team2 FROM goal_game_2;
When comparing goal with goal_3, we see that they have the same records because the primary key of the relation goal is included always in every split and join. However, comparing game with game_3 shows that game_3 has more incorrect records due to the join after splitting the relation goal_game using lossless decomposition.
Hashing and Indexing
In databases, indexes are used to speed up the retrieval of rows by creating a data structure that allows the database engine to quickly locate the required data. There are several types of indexes:
The most common type of index, created on a single column in a table. This index is useful for answering frequent queries on that specific column.
CREATE INDEX idx_name ON table_name(column_name);
An index that is created on multiple columns. It’s beneficial when queries involve multiple columns in the WHERE clause. It can be created using:
CREATE INDEX idx_name ON table_name(column1, column2);
Index to enforce uniqueness of the indexed column(s). This ensures that no two rows can have the same values for the indexed column(s). It can be created using:
CREATE UNIQUE INDEX idx_name ON table_name(column_name);
Index that is automatically created by the Database Management System (DBMS) when you define a PRIMARY KEY or UNIQUE constraint on a table.
In this exercise, you will practice on creating and deleting indexes in a database.
After uploading the database, list the available indexes for a given table using the code:
PRAGMA index_list('goal');
#TODO: Check the type of the indexes that you will see.
When running this query, we see information about one index that was created by the DBMS, which is sqlite_autoindex_goal_1. This type of indices gets created on the primary key attribute(s) of the relation.
Create an index using the code:
CREATE INDEX idx_player ON goal(player);
#TODO: Try to create multiple indexes on different tables.
CREATE INDEX idx_stadium ON game(stadium);
CREATE INDEX idx_coach ON teams(coach);
CREATE INDEX idx_name ON teams(teamname);
Delete indexes from those that you have created using the code:
DROP INDEX idx_name;
#TODO: Try to delete multiple indexes on different tables.
DROP INDEX idx_stadium;
DROP INDEX idx_coach;
DROP INDEX idx_name;
For this exercise, we will create a database with only one big table of synthetic data about employees.
Copy this code to Google Colab and run it (You don’t have to fully understand how it works).
import sqlite3
import random
import datetime
NUM_ROWS = 5_000_000
conn = sqlite3.connect(f'employees_{NUM_ROWS}.db')
cur = conn.cursor()
cur.execute('''
CREATE TABLE IF NOT EXISTS Employees (
EmployeeID INTEGER PRIMARY KEY,
FirstName TEXT,
LastName TEXT,
Email TEXT UNIQUE,
DepartmentID char(6),
Salary REAL,
HireDate DATE
);
''')
def random_date(start, end):
return start + datetime.timedelta(
days=random.randint(0, int((end - start).days)))
first_names = [
"John", "Jane", "Michael", "Emily", "James", "Patricia", "Robert", "Linda", "William", "Barbara",
"David", "Elizabeth", "Joseph", "Susan", "Charles", "Margaret", "Thomas", "Dorothy", "Christopher", "Nancy",
"Daniel", "Karen", "Matthew", "Betty", "Anthony", "Helen", "Mark", "Sandra", "Paul", "Ashley",
"Steven", "Deborah", "Andrew", "Jessica", "Kenneth", "Sarah", "Joshua", "Laura", "Kevin", "Anna",
"Brian", "Kimberly", "George", "Melissa", "Edward", "Michelle", "Ronald", "Emily", "Timothy", "Amanda",
"Jason", "Angela", "Jeffrey", "Rebecca", "Ryan", "Cynthia", "Jacob", "Stephanie", "Gary", "Katherine",
"Nicholas", "Shirley", "Eric", "Brenda", "Jonathan", "Catherine", "Stephen", "Christine", "Larry", "Marie",
"Justin", "Janet", "Scott", "Samantha", "Brandon", "Carolyn", "Frank", "Rachel", "Gregory", "Heather",
"Raymond", "Diane", "Benjamin", "Virginia", "Patrick", "Julie", "Alexander", "Joyce", "Jack", "Victoria",
"Dennis", "Olivia", "Jerry", "Christina", "Tyler", "Kelly", "Aaron", "Emma", "Jose", "Lauren"
]
last_names = [
"Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis", "Rodriguez", "Martinez",
"Hernandez", "Lopez", "Gonzalez", "Wilson", "Anderson", "Thomas", "Taylor", "Moore", "Jackson", "Martin",
"Lee", "Perez", "Thompson", "White", "Harris", "Sanchez", "Clark", "Ramirez", "Lewis", "Robinson",
"Walker", "Young", "Allen", "King", "Wright", "Scott", "Torres", "Nguyen", "Hill", "Flores", "Green",
"Adams", "Nelson", "Baker", "Hall", "Rivera", "Campbell", "Mitchell", "Carter", "Roberts", "Gomez",
"Phillips", "Evans", "Turner", "Diaz", "Parker", "Cruz", "Edwards", "Collins", "Reyes", "Stewart",
"Morris", "Morales", "Murphy", "Cook", "Rogers", "Gutierrez", "Ortiz", "Morgan", "Cooper", "Peterson",
"Bailey", "Reed", "Kelly", "Howard", "Ramos", "Kim", "Cox", "Ward", "Richardson", "Watson",
"Brooks", "Chavez", "Wood", "James", "Bennett", "Gray", "Mendoza", "Ruiz", "Hughes", "Price",
"Alvarez", "Castillo", "Sanders", "Patel", "Myers", "Long", "Ross", "Foster", "Jimenez", "Powell"
]
domains = ['example.com', 'test.com', 'demo.com']
start_date = datetime.date(2000, 1, 1)
end_date = datetime.date(2023, 12, 31)
locations = ['AM', 'UT', 'RT', 'EN']
for i in range(NUM_ROWS):
first_name = f'{random.choice(first_names)}_{i%10000}'
last_name = f'{random.choice(last_names)}_{i%10000}'
email = f"{first_name.lower()}.{last_name.lower()}{i}@{random.choice(domains)}"
department_id = locations[random.randint(0, 3)] + str(random.randint(1, 100))
salary = round(random.uniform(30000, 150000), 2)
hire_date = random_date(start_date, end_date).isoformat()
cur.execute('''
INSERT INTO Employees (FirstName, LastName, Email, DepartmentID, Salary, HireDate)
VALUES (?, ?, ?, ?, ?, ?);
''', (first_name, last_name, email, department_id, salary, hire_date))
if i % 100000 == 0:
print(f"inserted numberd of rows {i}")
conn.commit()
conn.commit()
conn.close()
print(f"Database with {NUM_ROWS} rows created successfully!")
#TODO: Download the generated database and upload it to DB-Browser.
#TODO: For each of the following queries perform the following list of tasks:
Run the query and record its running time.
Create an index on the column that is specified in the query.
Run the query again with the indexed column and record the running time.
The queries:
Q1:
SELECT * FROM Employees WHERE LastName = "Adams_278";
Q2:
SELECT * FROM Employees WHERE Salary = 66355.3;
Since the salary is randomly generated, this value might not be in your database. You may start by displaying a few records from the Employees table and pick one of the values in the salary column. You can use the query below to display the first 100 records.
SELECT * FROM Employees LIMIT 100
Q3:
SELECT DISTINCT DepartmentID FROM Employees WHERE DepartmentID = 'EN98' AND Salary = 93255.3;
Similar to the previous query, you may display a few records first and select values that are in the same record for the DepartmentID and the Salary.
Q4:
SELECT DISTINCT DepartmentID FROM Employees
Additionally, try more queries in you own.
It can be clearly observed that indexing improves the query time. For example:
First query: running time before indexing = 602 ms and after indexing 15 ms.
Second query: running time before indexing = 613 ms and after indexing 16 ms.
Third query, running time before indexing = 666 ms and after indexing 14.3 ms.
Fourth query, running time before indexing = 1809 ms and after indexing 345 ms.
These reading were collected on a specific machine and the running will vary from a machine to another.