Introduction to Postgresql: Part 2
By: Mike Wolfe
Tags: Database, Postgresql, Data Science, Sql, Postgres

Introduction to Postgresql: Part 2

Photo by Geran de Klerk on Unsplash

In part 1, we talked about what Postgresql is, the intended use, and how to install it. Once we got Postgresql installed, we were ready to create our database. To open Postgresql, we were actually using the user “Postgres”. This is kind of like your default admin account. We used this because we don’t have any current users created, but that is something we will be doing a little later down the road. For this part, we need to create our tables. In the last part, I talked about creating my “Recipe” database. Again, you can use any database that will suit your own project.

When you are getting your database prepared, it doesn’t hurt to have an ERD (Entity Relationship Diagram) sketched out in front of you. Not only does it help you get your database design out, but it also helps to visualize the relationships between tables. With my ERD all ready to go, let’s get back into the Postgresql command-line version and get these tables underway.

Creating the Tables

As a reminder, to get started we will run the following command to enter the Postgresql command-line interface:

sudo -u postgres psql

Again, “postgres” is the user until we set up another user. We will do that at a later time. If you received an error like this the service may not be running:

Error when trying to start Postgresql.

To fix this, we simply start the service then login:

sudo service postgresql start

At the end of part one, we created our “Recipes” database (not case sensitive). Before creating the first table, we will need to connect to that database. In the Postgresql command-line interface, this is achieved by using “\c” like so:

\c recipes

Connecting to the Recipes database.

Now we can create our first table. As you look at your ERD or as you create your tables, remember the order you need to create. Parent tables need to be created before any child tables in a relationship.

My first table will contain only two columns, and one is just a Primary Key. As a rule of thumb, these tables aren’t typically needed. Because it is only one table, we could just use a column in the child table instead. However, I will be using this table later on for a short and sweet API call, so for the sake of returning only the data required, and for simplicity, I will create this table. But just as a note, with only two columns in regular practice this table shouldn’t be required.

Here is the first table:

CREATE TABLE MealType(

MealTypeID SERIAL PRIMARY KEY,

MealName VARCHAR NOT NULL

);

Confirmation that MealType was successfully created.

As you may notice, the syntax is very similar to MySQL. However, the Primary Key is set up slightly different. In MySQL, we use an “INT NOT NULL AUTO_INCREMENT”, or use an “IDENTITY” column, and add your Primary Key as usual. In Postgres, it seems it is very simple to declare our key by simply using a “SERIAL” value to increment the value.

Let’s set up the next table with a decimal value and another column with a default value. It will also be a parent table. The DECIMAL type is a standard SQL datatype, so declaring it will be no different than other SQL types such as MySQL. After we declare the datatype for the default value, simply use the keyword DEFAULT and the value you want.

CREATE TABLE Pantry(

PantryID SERIAL PRIMARY KEY,

Title VARCHAR NOT NULL,

TotalAmt DECIMAL (5, 2) NOT NULL,

TotalAmtUnit VARCHAR DEFAULT 'LBS' NOT NULL

);

Confirmation that Pantry was successfully created.

The next table I will need will be the Recipe table. This table will have a Foreign key. To do so, create a Foreign Key constraint just like you would in MySQL. After you add your columns, add the Foreign Key, declare which column the key will be, then keyword REFERENCES and then the table and Primary key for that table.

CREATE TABLE Recipe(

RecipeID SERIAL PRIMARY KEY,

MealTypeID INT NOT NULL,

Title VARCHAR NOT NULL,

FOREIGN KEY(MealTypeID) REFERENCES MealType(MealTypeID)

);

Confirmation that Recipe was successfully created.

Our next table will house the instructions for each recipe, so we will need a foreign key there as well. Nothing else special for this table:

CREATE TABLE Instructions(

InstructionID SERIAL PRIMARY KEY,

RecipeID INT NOT NULL,

StepNum INT NOT NULL,

Description VARCHAR NOT NULL,

FOREIGN KEY(RecipeID) REFERENCES Recipe(RecipeID)

);

Confirmation that Instructions was successfully created.

The final table will be for the ingredients. This table will have two Foreign Keys. One will be the Recipe table, and the other will be the Pantry table. It will be the associative table (which creates the association between recipes and pantry items). This connection is required for a future element I want to implement. Once the front end gets going, I want to be able to know if I have enough of an ingredient to cook or bake the recipe. To do so, I need to know how much of an ingredient I have, and how much is still remaining in the pantry. If there is enough in the pantry, the recipe will be available, and I’ll have to decide what to do with recipes where I don’t have all the required ingredients.

CREATE TABLE Ingredient(

IngredientID SERIAL PRIMARY KEY,

RecipeID INT NOT NULL,

MeasurementAmt DECIMAL(5, 2) NOT NULL,

MeasurementUnit VARCHAR NOT NULL,

Title VARCHAR NOT NULL,

PantryID INT NOT NULL,

FOREIGN KEY(RecipeID) REFERENCES Recipe(RecipeID),

FOREIGN KEY(PantryID) REFERENCES Pantry(PantryID)

);

Confirmation that Ingredient was successfully created.

So now that we have our tables defined and created, we need to make sure we can find them in the database. To view our list of tables, we need the equivalent to MySQL’s SHOW TABLES. In Postgresql, we use the following:

\dt

All tables displayed.

With all of our tables created, we are ready to start inserting test data. But to keep these short and easy to follow, we will start inserting those test records in the next part. The tables you created could be smaller or much larger than the database I created. Maybe you needed different types of fields, including the non-standard SQL data types such as document types or network address types. For my purposes, I would not need those types currently. If we think of something to add on, we can always do that later.

Conclusion

In this part, we learned how to create our tables. For the most part, the syntax was very similar to MySQL. There were a few differences, however, such as when creating the auto-increment primary key field. In Postgresql, we used the SERIAL data type. We also learned how to declare a PRIMARY KEY and a FOREIGN KEY. These were also much like MySQL when comparing syntax. We also learned how to connect to the Recipes database. Once all of our tables were created, we also learned how to display all of the tables we created. Because we created them using the owner “postgres”, which we logged in with earlier. We didn’t have a specific user-created quite yet, but we will be doing that later down the road.

For the next part, we can work on inserting our test data and perhaps updating and deleting records. Until next time, cheers!

Read all my articles for free with my weekly newsletter, thanks!

Want to read all articles on Medium? Become a Medium member today!