CS 200: Data Bases and SQL

Video: Socratica SQL Youtube channel

SQL implements a relational database. This model was introduced by E.F.Codd in his 1970 paper: A Relational Model of Data for Large Shared Data Banks.

This notebook implements the code from SQL tutorial 18 lessons

SQL Keywords (we will not focus on the last four):

sqlite3 tutorial There are many out there among which to choose.

sql.py The source code for most of this notebook.

An introduction to SQL using Python's sqlite3 module

Demonstrates Python module sqlite3 using examples from the SQL tutorial

Create a connection to database: mydb and a cursor to point inside the object.

Use the CREATE command to build a table with the given fields. The example database is for movies.

Execute the command c1, after first dropping the movies table.

Here is how you get column names for a table.

It is advisable to wrap your database commands with try.

The output here is hardwired for the movies database.

Below we use the INSERT command to add a record to the movie database.

There is now one record in the database.

We can use Python to insert a bunch of data:

Before we add these movies, we should remove the first entry, using the DELETE command.

Aha, we have a duplicate entry from having INSERTed Toy Story before.

We will erase the table using the DELETE command. Note: WHERE 1=1 is an SQL idiom for everywhere. That is, it will delete every record.

Success! Now let's try loading the movies again.

This looks good. Now we will write the database to the file using commit().

SQL Lesson 1. SELECT Queries 101

We define a fetchall() function to query the database.

We use fetchone to get a single record.

SQL Lesson 2: Queries with constraints (Pt. 2)

The WHERE clause adds constraints to the query.

We can use comparison operators for numeric fields.

Multiple where clauses are AND conditions. Use the OR operator for disjoint conditions.

SQL Lesson 3: Queries with constraints (Pt. 2)

You can use LIKE for pattern matching, with % as a wildcard character.

SQL Lesson 4: Filtering and sorting Query results

We use the ORDER BY keywords to sort the output, and the LIMIT keyword to cap the number of results.

We incorporate both in fetchwheresort().

SQL Lesson 6: Multi-table queries with JOINs

Joins are commonly used to link together tables.

For example, you might have the following tables:

students (id, name, DOB, college, etc.)
course (id, title, department, hours, credithours, etc.)
classroom (id, building, room, size, AV, etc.)

Then you would have other tables linking the above:

enrollment (student.id, course.id, term, status, etc.)
assignedrooms (course.id, classroom.id, time)

This way you can have one student enrolled in multiple courses in multiple terms, and have a classroom allocated to multiple courses over time.

This approach is known as normalization.

See https://en.wikipedia.org/wiki/Database_normalization .

Below we create a new table of box office revenue for movies, both domestic and international sales.

We create fectchwherejoin() to JOIN the movies table with the boxoffice table.

Show the sales numbers for each movie that did better internationally rather than domestically

SQL Lesson 7: OUTER JOINs

Used when tables have asymetric data - may not have sales data for some movies.

SQL Lesson 8: A short note on NULLs

To process or identify missing data use WHERE column IS / IS NOT NULL.

RIGHT and FULL are not currently supported in sqlite3

switch order of tables

SQL Lesson 9: Queries with expressions

Use AS for column aliases.

Create new column: Sales ratio.

Create new column: gross sales millions.

SQL Lesson 10: Queries with aggregates (Pt. 1)

Calculate average domestic sales using AVG().

How many movies have a rating < 8? Use COUNT().

What are the movies with a rating < 8?

Calculate the max, min, avg ratings.

SQL Lesson 11: Queries with aggregates (Pt. 2)

SQL Lesson 12: Order of execution of a Query

SQL Lesson 13: Inserting rows

We did this above after creating the table

SQL Lesson 14: Updating rows

Change title and year. This is a bogus example.

SQL Lesson 15: Deleting rows

SQL Lesson 16: Creating tables

CREATE TABLE IF NOT EXISTS mytable (
    column DataType TableConstraint DEFAULT default_value,
    another_column DataType TableConstraint DEFAULT default_value,
    …
);

Common data types:

Common table constraints:

SQL Lesson 17: Altering tables

DROP not supported by sqlite.

SQL Lesson 18: Dropping tables

Advanced sqlite

From: http://sebastianraschka.com/Articles/2014_sqlite_in_python_tutorial.html

Should execute "connection.close()" before running doall()

evalsql()

From: https://docs.python.org/2/library/sqlite3.html