Learn how to install PostgreSQL on Windows, configure the System Path for PowerShell compatibility, and seamlessly use psql and Django’s dbshell for database management.
1. Installation via EnterpriseDB
Download the Windows installer from the official PostgreSQL website. Run the executable and follow the prompts. During installation, take note of the password you set for the postgres user and the default port, which is 5432.
By default, the tools are installed at: C:\Program Files\PostgreSQL\<VERSION>\bin
2. Configuring PowerShell Path
To run PostgreSQL commands directly in PowerShell, you must add the "bin" folder to your System Environment Variables:
- Search for "Edit the system environment variables" in the Start Menu.
- Click "Environment Variables".
- Under "System Variables", select "Path" and click "Edit".
- Click "New" and add the path to your bin folder (e.g.,
C:\Program Files\PostgreSQL\16\bin). - Restart PowerShell to apply the changes.
3. Running Django dbshell
In Django, python manage.py dbshell is a shortcut that opens the PostgreSQL terminal using the credentials defined in your settings.py. Ensure your virtual environment is active before running the command.
.\venv\Scripts\Activate.ps1
python manage.py dbshell
4. Common psql Commands and Examples
Once you are inside the psql or dbshell prompt, use these commands to manage your database:
List Databases
Command:
\l
Example: Use this to verify that your Django database (e.g., my_project_db) was created successfully.
Connect to Database
Command:
\c database_name
Example: \c shop_db switches your focus so you can run queries against the 'shop_db' database.
List Tables
Command:
\dt
Example: After running Django migrations, use \dt to see tables like auth_user or django_migrations.
Describe Table
Command:
\d table_name
Example: \d blog_post shows the column types, null constraints, and foreign keys for your 'blog_post' table.
Exit
Command:
\q
Example: Type this and hit Enter to close the database shell and return to your PowerShell prompt.