Databases

Add column to postgres table

How to manually add columns to a postgres database

While adding new fields to my Django models, running the command manage.py makemigrations didn’t create any migrations and I couldn’t do anything because the database table was missing those columns.

On ThumbsUpNews the whole project is being served through docker-compose and running docker-compose exec db psql didn’t work since I didn’t have my username on the database.

After spending a few minutes searching, I’ve discovered that you could run the sql command with the —username flag to use a different user.

docker-compose exec db psql --username=<youruser>

Inside the PostgreSQL interactive terminal, I figured that I could just add the columns that were missing on the table. But it seems that I couldn’t find that table.

Using the command \l allows us to list all databases available and I’ve noticed that I had a table named postgres which is the name of my docker container for the database.

Then we have to run the command \c postgres to connect to that database, then we can run the command \d <table name> to see the existing columns of that table.

Then all I had to do was to add new columns to the database.

sql
1ALTER TABLE <name of table>
2ADD COLUMN <name of colum> <colum type>;

We have to tell Postgres that we want to alter the table x and what kind of change we want to do, in this case, add a column. So let’s say that you want to add the column named description and for type, we just want a text type with unlimited length.

You can do that by running the command:

sql
1ALTER TABLE <name of table>
2ADD COLUMN description text;

Note that you need to finish the ADD COLUMN line with a ;

That’s all there is to add columns to a Postgres database table.

Reference

Webmentions

0 Like 0 Comment

You might also like these

This article will show you how to setup DynamoDB locally, so you can test your code without having to use your AWS account.

Read More
Databases

How to setup DynamoDB locally

How to setup DynamoDB locally

This article will show you how to create an use indexes in DynamoDB using the python library aioboto3.

Read More
Databases

How to create and use indexes in DynamoDB

How to create and use indexes in DynamoDB

Twitch suggests that we should pass a `hub.secret` so we can compare sha-256 hashes and check the authenticity of the request. This is how I did it in Python.

Read More
Python

Handle Twitch hub.secret logic in python

Handle Twitch hub.secret logic in python

How to return an attribute from a many-to-many object relationship from a Django Ninja API endpoint.

Read More
Python

Django Ninja Schemas and Many To Many

Django Ninja Schemas and Many To Many