ISF DP Computer Science

Database Programming #

In this lab you will practice SQL commands and create tables for a relational database.


Syllabus Topics [SL] #

  • A3.1.1 Explain the features, benefits and limitations of a relational database.
  • A3.2.1 Describe database schemas.
  • A3.2.2 Construct ERDs.
  • A3.2.3 Outline the different data types used in relational databases.
  • A3.2.4 Construct tables for relational databases.

Key Vocabulary #

WordDefinition
Entityanything that can have data stored about it that can be described
Entity Relationship Diagrams (ERDs)a visual representation of the entities in a database and the relationship between them
Recordone instance of an entity; a row in a table
Primary Keya column that uniquely identifies a record in a table
Composite Keysmultiple columns that form a primary key
Relational Databasea set of tables
Relationshipa connection established between different tables where the foreign key in one table refers to the primary key in another table
One-to-Oneone record in one table is associated with exactly one record in another table (e.g. one country has one capital)
One-to-Manyone record in one table is associated with one or more records in another table (e.g. one teacher has many classes)
Many-to-Manymultiple records in one table is associated with one or more records in another table (e.g. many actors in many movies)
Schemaarchitecture showing how data is organized and the relationship between data
Conceptual Schemaabstract model describing the structure of the data without considering how it will physically be implemented; an ERD is a conceptual schema
Logical Schemaa detailed design of the structure of tables with fields and data types and the relationship between tables and constrains
Viewa virtual table based on the result of a query

[0] Setup #

๐Ÿ’ป Download sqlite3 to run SQL commands from the command line. The documentation is at sqlite.org/docs.html

brew install sqlite3

๐Ÿ’ป Go to your dpcs folder and create a new folder for this unit.

cd ~/desktop/dpcs/
mkdir unit04_databases
cd unit04_databases

๐Ÿ’ป Clone your repo. This will copy it onto your computer. Be sure to replace yourgithubusername with your actual username.

git clone https://github.com/isf-dp-cs/lab_db_programming_yourgithubusername
๐Ÿ’ป In the Terminal, type the following command to open the lab folder.
cd lab_db_programming_yourgithubusername

๐Ÿ’ป Enter the Poetry Shell to start the lab. As a reminder, we will run this command at the start of each lab, but only when we are inside a lab folder.

poetry shell
๐Ÿ‘พ ๐Ÿ’ฌ Exiting the poetry shell

When you want to exit the shell, you can type exit or ^D


[1] Riddle Schema #

The first example is a simple database with one table. It stores Riddles.

Conceptual Schema #

In a conceptual schema, the diagram should only describe the structure of the relationships of the data.


erDiagram

    RIDDLES {
        
    }

Logical Schema #

In a logical schema, the diagram should only describe the fields, data types, primary key, and foreign key.


erDiagram

    RIDDLES {
        id integer PK
        question text
        answer text
        total_guesses integer
        correct_guesses integer
        difficulty text
    }


[2] Riddles Worksheet #

๐Ÿ’ป Open a new database file in the sqlite3 shell.

sqlite3 database_riddles.db

๐Ÿ’ป Create the riddles table. The semicolon ; MUST be used to denote the end of your command.

CREATE TABLE IF NOT EXISTS riddles (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    question TEXT NOT NULL,
    answer TEXT NOT NULL,
    total_guesses INTEGER DEFAULT 0,
    correct_guesses INTEGER DEFAULT 0,
    difficulty TEXT DEFAULT 'easy'
);

๐Ÿ’ป Exit the sqlite3 shell

control + c OR control + d

๐Ÿ’ป List the files. You should see your newly created database_riddles.db in the directory!

ls

๐Ÿ‘€ Take a look at init_db.py. This is where the new rows are added to the riddles table. The riddles are populated from the riddles.json file.

๐Ÿ’ป Run init_db.py to fill your database.

python init_db.py

๐Ÿ’ป Enter the sqlite3 shell again.

sqlite3 database_riddles.db

๐Ÿ’ป Turn on headers to be able to view the columns names`

.headers on

๐Ÿ’ป Turn on column mode to display queries in clear columns

.mode column

โœ๏ธ Write out a query to answer each question on the worksheet.

๐Ÿ’ป Test each query out in your shell to make sure it works as expected. Don’t forget the semi-colon ; to end each statement.

๐Ÿ’ป Exit sqlite3

control + c OR control + d

[3] Team Schema #

In this lab you will create a relational database representing sports teams and players.

Conceptual Schema #

In a conceptual schema, the diagram should only describe the structure of the relationships of the data. Here we see that one team has many players.

Crows-foot style notation


erDiagram

    TEAM ||--|{ PLAYER: ""
    
    TEAM {
        
    }

    PLAYER {
      
    }

Chen style notation


flowchart TD

    TEAM[TEAM] -->|1| B{has}
    B --> |N| PLAYER[PLAYER]
    

Logical Schema #

In a logical schema, the diagram should only describe the fields, data types, primary key, and foreign key.


erDiagram
    TEAM ||--|{ PLAYER: ""
    
    TEAM {
        team_id integer PK
        team_name text
        sport text
    }

    PLAYER {
        player_id integer PK
        team_id integer FK
        first_name text
        last_name text
        position text
        games_played integer
    }


[4] Create a Database #

๐Ÿ’ป Create a new database file

sqlite3 database.db

๐Ÿ’ป Turn on headers to be able to view the columns names`

.headers on

๐Ÿ’ป Turn on column mode to display queries in clear columns

.mode column

๐Ÿ’ป Create the teams table. The semicolon ; MUST be used to denote the end of your command.

create table teams(
    team_id integer primary key AUTOINCREMENT,
    team_name char,
    sport char
);

๐Ÿ’ป Insert 5 records Because the team_id will auto-increment, we do not need to enter it. You can use the up arrow to cycle through previous commands.

insert into teams (team_name, sport) values ("ISF", "Basketball");

๐Ÿ’ป Query for all records. Don’t forget the semi-colon ;

select * from teams;

๐Ÿ’ป Test the query commands you learned in the last lab.

SELECT, DISTINCT, FROM, WHERE, BETWEEN, ORDER BY, GROUP BY, HAVING, ASC,
DESC, LIKE with % wildcard, AND, OR, NOT

[5] Modify your Database #

๐Ÿ’ป Delete a record with a where query. It will delete all records that match the query. Try to delete multiple rows at at time.

delete from teams 
where team_id=0;

๐Ÿ’ป Update a record with a where query. It will delete all records that match the query. Try to delete multiple rows at at time.

update teams 
set team_name="Hong Kong"
where team_id=1;

[6] Add the Relational Database #

๐Ÿ’ป Create a new table for the players

CREATE TABLE players (
    player_id integer primary key autoincrement,
    team_id integer,
    first_name char NOT NULL,
    last_name char NOT NULL,
    position char NOT NULL,
    games_played INTEGER DEFAULT 0,
    foreign key (team_id) references teams(team_id)
);

๐Ÿ’ป Insert 5 records into players

๐Ÿ’ป User JOIN to view both of the tables combined.


[7] HL: Create a View #

๐Ÿ’ป Create a new view based on a SELECT command. You can then use the view_name as the table_name in commands.

create view b_sports as
select sport from teams
where sport like "%b%";

๐Ÿ’ป Create a new view with both tables combined.

๐Ÿ’ป On your view, test all aggregation commands

AVERAGE, COUNT, MAX, MIN, SUM

[8] Deliverables #

โšกโœจ Once you finish the lab, be sure to complete these two steps:

๐Ÿ“‹ Update Syllabus Checklist: Go to your Syllabus Content Checklist in your Google Drive and update it accordingly.

๐Ÿ’ป Push your work to Github

  • git status
  • git add -A
  • git status
  • git commit -m “describe your code here”
  • git push
  • remote