SQL

Projected Time

About 3.5-4 hours

Prerequisites

Motivation

Most software applications store data of some sort – user data, content, etc. Databases are used to store data, so software developers should know how to use them. Relational databases are a common type of database that are good for storing many types of data.

Most companies use relational databases to store their data.

Objectives

Participants will be able to:

Specific Things to Learn

Materials

Lesson

Common Mistakes / Misconceptions

Independent Practice

  1. Work through the Codecademy SQL Tutorial: https://www.codecademy.com/learn/learn-sql
  2. PostgreSQL is a popular, open-source version of SQL. Try it out:
  3. Using PostgreSQL, try creating tables and adding, updating, deleting, and querying data yourself!

Challenge

In PostgreSQL on your own machine, you are going to create the tables for a microblogging platform (an app similar to Twitter). Your database should be able to store user information and posts by specific users. One post must belong to exactly one user. One user can have many posts. Later, we’ll add the ability for users to follow each other, but not now.

  1. With pencil/pen and paper, write out the data for a database with the following spec. Fill in the fields with fake data that you make up. Be sure to link posts to a certain existing user!

  2. Use the psql command in your terminal to enter the PostgreSQL command line program. Once there, use SQL statements to create two tables according to the spec for the two tables in step 1.

  3. Once you have your two tables set up, compare your table set up with another apprentice’s.

  4. Add sample data to the tables yourself (make up some users and posts).

  5. Try writing queries that get data such as:

  6. Now let’s perform a database migration. We will add a new column to an existing table in our database. Add a text field named: bio to your existing users table!

  7. Add some sample data to your new bio fields, but not for every user (leave some of their bios blank).

  8. Try writing queries that get data such as:

Extra Challenge

If you complete the above, we’ll move on to creating a join table.

  1. Add a new table named follows that has an int field follower_id and an int field followed_id. Draw a picture for this table.

  2. Write some queries that get data such as:

Supplemental Materials