Monday, August 31, 2009

Interacting with PostgreSQL

  • The psql client has a lot of features that will make your PostgreSQL life easier
  • Besides PostgreSQL commands (SELECT, INSERT, UPDATE, CREATE TABLE), psql provides meta-commands
  • PostgreSQL commands are sent to the server, meta-commands are processed by psql itself
  • A meta-command begins with a backslash character ( \ )
You can obtain a list of all the meta-commands using the \? meta-command :

postgres=# \?

General

\c[onnect] [DBNAME|- USER|- HOST|- PORT|-]
connect to new database (currently "edb")

\h [NAME]
help on syntax of SQL commands, * for all commands)

\prompt [TEXT] NAME
prompt user to set internal variable

\password [USERNAME]
securely change the password for a user

\q
quit psql

\timing
toggle timing of commands (default off)

\! [COMMAND]
execute command in shell or start interactive shell

NOTE :
[ ] :
Optional Variables
| : denotes Or (a | b : a or b)

Using the psql Client

Connecting to a Database :

After Installing PostgreSQL you can login in psql client as following
$ psql -d movies

Welcome to psql, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help on internal slash commands
\g or terminate with semicolon to execute query
\q to quit

movies=# \q

The psql program is a text-based interface to a PostgreSQL database. When you are running
psql, you won't see a graphical application no buttons or pictures or other bells and whistles,
just a text-based interface. Later, I'll show you another client application that does provide a
graphical interface

A Simple Query :

At this point, you should be running the psql client application. Let's try a very simple query:

$ psql -d movies
Welcome to psql, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help on internal slash commands
\g or terminate with semicolon to execute query
\q to quit

movies=# SELECT user;

current_user
---------------
Deepu
(1 row)

movies=# \q

Followers