How to switch databases in psql? - postgresql

In MySQL, I used use database_name;
What's the psql equivalent?

In PostgreSQL, you can use the \connect meta-command of the client tool psql:
\connect DBNAME
or in short:
\c DBNAME

You can connect to a database with \c <database> or \connect <database>.

At the PSQL prompt, you can do:
\connect (or \c) dbname

You can select the database when connecting with psql. This is handy when using it from a script:
sudo -u postgres psql -c "CREATE SCHEMA test AUTHORIZATION test;" test

use \c databaseName or \connect databaseName
(Working on psql 13.3)

\l for databases
\c DatabaseName to switch to db
\df for procedures stored in particular database

Though not explicitly stated in the question, the purpose is to connect to a specific schema/database.
Another option is to directly connect to the schema. Example:
sudo -u postgres psql -d my_database_name
Source from man psql:
-d dbname
--dbname=dbname
Specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line.
If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string. See Section 31.1.1, “Connection Strings”, in the
documentation for more information.

Using psql's meta-command \c or \connect [ dbname [ username ] [ host ] [ port ] ] | conninfo (see documentation).
Example: \c MyDatabase
Note that the \c and \connect meta-commands are case-sensitive.

Use below statement to switch to different databases residing inside
your postgreSQL RDMS
\c databaseName

You can also connect to a database with a different ROLE as follows.
\connect DBNAME ROLENAME;
or
\c DBNAME ROLENAME;

You can connect using
\c dbname
If you would like to see all possible commands for POSTGRESQL or SQL follow this steps :
rails dbconsole
(You will be redirected to your current ENV database)
?
(For POSTGRESQL commands)
or
\h
(For SQL commands)
Press Q to Exit

If you want to switch to a specific database on startup, try
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql vigneshdb;
By default, Postgres runs on the port 5432. If it runs on another, make sure to pass the port in the command line.
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p2345 vigneshdb;
By a simple alias, we can make it handy.
Create an alias in your .bashrc or .bash_profile
function psql()
{
db=vigneshdb
if [ "$1" != ""]; then
db=$1
fi
/Applications/Postgres.app/Contents/Versions/9.5/bin/psql -p5432 $1
}
Run psql in command line, it will switch to default database; psql anotherdb, it will switch to the db with the name in argument, on startup.

Listing and Switching Databases in PostgreSQL
When you need to change between databases, you’ll use the \connect command, or \c followed by the database name as shown below:
postgres=# \connect database_name
postgres=# \c database_name
Check the database you are currently connected to.
SELECT current_database();
PostgreSQL List Databases
postgres=# \l
postgres=# \list

Connect to database:
Method 1 : enter to db : sudo -u postgres psql
Connect to db : \c dbname
Method 2 : directly connect to db : sudo -u postgres psql -d my_database_name

You can just enter use [dbName] to switch between databases without reentering your password.

Related

Restoring the Dump using PostgreSQL's psql

I'm trying to restore the DB from an SQL file using
psql dbname < dumpfile
but after I connect to my DB psql provides a prompt with the name of the database to which psql is currently connected, followed by the string =>. For example:
testdb=>
So how can I enter the command, or which Meta-Command should I use to restore the DB with the psql command? (Already connected to my DB)
psql is the command line client. You cannot call psql when you are already in an interactive psql session.
Either you connect with psql -d testdb in an interactive session and import the dump with \i dumpfile, or you stay on the shell and call psql in a non-interactive session with the dump file as script: psql -d testdb -f dumpfile
you can use \c <database_name>
it will connect you to the desired database
for example
global=> \l
List of databases
Name | Owner | Encoding
test | pgadmins | UTF8
global=> \c test
You are now connected to database "test" as user "user1".
test=>

How to create user in postresql version 12?

I have loged in postresql as default postgres user:
psql -U postres
and following the official documentation: https://www.postgresql.org/docs/12/app-createuser.html I have type this:
create user -d -e --role=myrole -r -s myuser;
and nothing happens. Postresql ignores the command.
\du
does not return myuser in user list.
It ignores the command when added any option, only this works:
create user myuser;
CREATE USER is a SQL statement that has its own syntax https://www.postgresql.org/docs/12/sql-createuser.html whereas createuser is an executable that has a different syntax: https://www.postgresql.org/docs/12/app-createuser.html: you cannot mix them.

Postgres - npm script to drop/add database

I want to simplify my life and automate the process of adding/dropping my test db via an npm script, however I am running into issues.
Attempt 1:
"drop-db:local": "psql postgres \"drop database blog_db; create database blog_db; \\c blog_db; CREATE EXTENSION \"pgcrypto\";\""
After running this, I keep getting the following error
psql: error: could not connect to server: FATAL: Peer authentication failed for user "drop database blog_db; create database blog_db; \c "
Attempt 2:
changed
psql postgres
to
psql -h localhost -U rm postgres
So this opens the db in my terminal but that seems to ignore some stuff as mentioned in the msg below
psql: warning: extra command-line argument "drop database blog_db; create database blog_db; \c blog_db; CREATE EXTENSION pgcrypto;" ignored
What am I doing wrong?
This is a list of my db users
postgres=# \du
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
rm | Superuser, Create DB | {}
db version: psql (12.2 (Ubuntu 12.2-2.pgdg18.04+1))
You need to use -c or -f with your psql command.
As the psql help shows:
-c, --command=COMMAND run only single command (SQL or internal) and exit
-f, --file=FILENAME execute commands from file, then exit
As you are using multiple commands so it will be better of you use -f followed by a sql file name that has all the commands e.g your drop_create_db.sql file can have following code:
drop database blog_db;
create database blog_db;
\c blog_db;
CREATE EXTENSION "pgcrypto";
And you may run this file by using the following command
"drop-db:local": psql -U postgres -d postgres -p 5432 -f /tmp/drop_create_db.sql

postgres: how to execute script inside a .sql file

In SQLite you can do
sqlite3 i.db < x.sql
where x.sql is a create table statement and i.db is the database
What is the equivalent in PostgreSQL ?
The default command line tool for Postgres is psql it supports command line parameters to specify the database and a script name:
psql -d db_name -f x.sql
For details (e.g. how to specify the database user you want to use for the connection) see the manual: https://www.postgresql.org/docs/current/static/app-psql.html
With a similar approach:
psql -U your_role your_db < x.sql
Within psql:
\i /path/to/x.sql

drop db in postgres

I try dropdb mydbname in shell. It do not give any error. But still when I call \l it is still there.
I logged into the postgres server using sudo -u postgres psql.
Other than my main concern I need to know how to go into the database other than just staying outside of it. (as a example if I want to list the tables)
In order to drop database you can use SQL command (but I do not understand why dropdb didn't work) DROP DATABASE mydbname:
sudo -u postgres psql -c "DROP DATABASE mydbname"
It would be good to check if database is not used:
select * from pg_stat_activity where datname = 'mydbname';
The sudo -u postgres psql connects to postgres database. You need to specify database: sudo -u postgres psql mydbname and then you can use metdata commands like \d, \dt, \dv, ...
When you say "shell" ... do you mean the psql shell, not the unix command line shell?
I'd say you're running into this issue:
Postgresql not creating db with “createdb” as superuser, yet not outputting errors
ie you're trying to use dropdb as a psql command, when it's a unix shell command. You're not getting an error because of this:
In psql, why do some commands have no effect?
You didn't terminate the command with a semicolon.
Are you missing the comma(;)? This command worked for me:
drop database <database_name>;
Server should be running, then:
dropdb <database name>
If server is not running, first try:
pg_ctl start -D <mylocal_db_path> -l <mylogfile.log>