This time we will practice:
- Creating a database using postgres utility and psql
- Renaming a database using psql
- Deleting a database using postgres utility and psql
- Collection of commands
Please make sure the postgres server is running. Check this Getting Started with PostgreSQL on Mac Part 3.
Creating a database
Just like creating a role, we could create a database using both postgres utility or using psql as well.
Using postgres utility
Open terminal
Enter and type this command to create a database with name
my_databasefor rolemyrole.BASH1createdb -U myrole my_databasebut if you don’t have any role setup at the moment, enter this:
BASH1createdb my_databaseThis will create a database owned by the default user.
Check the database is created, open postgres shell by running this on terminal
psqlorpsql postgres.Run this command on shell to list the databases:
BASH1\listYou should see the newly created database.
Deleting a database using postgres utility
Open terminal and run this command:
BASH1dropdb my_databaseYou can go to psql shell and run command
\listto check thatmy_databaseshould be gone from the list.
Using psql
Open terminal
Go to psql shell:
BASH1psql postgresType and enter this query to create a database:
BASH1CREATE DATABASE my_database;Check the database is created by running
\listcommand.Let’s rename the database while we are in psql shell.
Run this command to rename the database:
BASH1ALTER DATABASE my_database RENAME TO updated_database;
Deleting a database using psql
Open postgres shell (
psql postgres) and run this command:BASH1DROP DATABASE updated_databaseYou can go to psql shell and run command
\listto check thatupdated_databaseshould be gone from the list.
From here, you can use any postgreSQL clients (python client etc) or directly using psql console to start using the database.
Collection of commands
Terminal commands:
pg_ctl -D /usr/local/var/postgres -l logfile start: start a postgres server of the specified path cluster.pg_ctl -D /usr/local/var/postgres -l logfile stop: stop a postgres server of the specifiec path cluster.- Postgress utilities .
psql -U <role name>: open psql shell or console as a role.psql postgres: open psql shell or console as the default role (superuser).
Psql shell/console commands:
\du: list roles.\list: list databases.\connect <database name>: connect to a database specified.\dt: list tables in a database.\q: quit psql shell / console.
