0
0
PostgreSQLquery~5 mins

Creating databases and connecting in PostgreSQL

Choose your learning style9 modes available
Introduction

We create databases to store and organize data. Connecting lets us use and manage that data.

When starting a new project that needs to save information.
When you want to separate data for different applications.
When you need to organize data for easy access and updates.
When setting up a test environment with its own data.
When you want to manage data securely and efficiently.
Syntax
PostgreSQL
CREATE DATABASE database_name;

\c database_name

CREATE DATABASE makes a new database with the name you choose.

\c database_name connects you to that database in the PostgreSQL command line.

Examples
This creates a new database called myshop.
PostgreSQL
CREATE DATABASE myshop;
This connects you to the myshop database so you can start using it.
PostgreSQL
\c myshop
Creates a database named testdb for testing purposes.
PostgreSQL
CREATE DATABASE testdb;
Connects to the testdb database to run commands there.
PostgreSQL
\c testdb
Sample Program

This creates a database called sampledb and then connects to it.

PostgreSQL
CREATE DATABASE sampledb;

\c sampledb
OutputSuccess
Important Notes

You must have permission to create databases in PostgreSQL.

Use \l to list all databases in the PostgreSQL command line.

To connect from outside the command line, use connection strings or tools like pgAdmin.

Summary

Creating a database sets up a place to store your data.

Connecting to a database lets you work with its data.

Use CREATE DATABASE and \c commands in PostgreSQL.