Database Reference
In-Depth Information
\g create_script.sql
\i create_script.sql
Because we want the output of our query to be saved as an executable statement,
we need to remove the headers by using
\t
. We use
\a
to remove extra line
breaks that psql normally puts in.
Create a table with nine varchar columns.
We use the
\g
option to force our query to output to a file.
The
\i
followed by the script name executes the script.
\i
is the interactive
equivalent of the noninteractive
-f
.
To run
Example 3-1
, we enter the following at an OS prompt:
psql -f build_stage.psql -d postgresql_book
Example 3-1
is an adaptation of an approach we describe in
How to Create an N-column
the
DO
command introduced in PostgreSQL 9.0.
psql Customizations
If you spend most of your day in psql, consider tailoring the psql environment to your
needs. psql reads settings from a configuration file called
psqlrc
, if present. When psql
launches, it searches for this file and runs all commands therein.
On Linux/Unix, the file is generally named
.psqlrc
and should be placed in your home
directory. On Windows, the file is called
psqlrc.conf
and is located in the
%APPDATA
%\postgresql
folder, which usually resolves to
C:\Users\
username
\AppData\Roaming
\postgresql
. Don't worry if you can't find the file right after installation; you usually need
to create it. Any settings in the file will override psql defaults. To find more details about
the file, see the
psql documentaion
.
The contents of a
psqlrc
file looks like
Example 3-2
. You can add any
psql
command to
it for execution at start-up.
Example 3-2. Example psqlrc file
\pset null 'NULL'
\encoding latin1
\set PROMPT1 '%n@%M:%>%x %/# '
\pset pager always
\timing on
\set qstats92 'SELECT usename, datname, left(query,100) || ''...'' As query
FROM pg_stat_activity WHERE state != ''idle'' ;'