You are on page 1of 1

Admin Functions Command Line Official PostgreSQL 8.3 Documentation URL: http://www.postgresql.org/docs/8.

3/static/
We cover only a subset of what we feel are the most useful constructs that we could squash in a single cheatsheet page
COPY .. FROM .. pg_dump
COPY .. TO .. pg_dumpall commonly used
1 New in this release.
current_setting pg_restore
pg_cancel_backend psql DATA TYPES
pg_column_size
pg_database_size JOIN Types Below are common data types with common alternative names.
pg_relation_size Note: There are many more and one can define new types with create type. All table structures create an implicit type struct as well.
pg_size_pretty CROSS JOIN
pg_tablespace_size EXCEPT (ALL) datatype[] - e.g. varchar(50)[] (defines an array of a type)
pg_total_relation_size FULL JOIN
[INNER] JOIN bit numeric(length,precision)
set_config
vacuum analyze verbose INTERSECT (ALL) boolean oid
vacuum full LEFT JOIN bytea serial - serial4
NATURAL JOIN character varying(length) - varchar(length) bigserial - serial8
Common Functions RIGHT JOIN character(length) - char(length) text
UNION (ALL) date time without timezone - time
cast, :: time with timezone - timez
coalesce SQL Keywords enum 1
generate_series double precision - float4 float8 timestamp without timezone - timestamp
greatest BETWEEN .. AND integer - int4 timestamp with timezone - timestampz
CASE WHEN .. END
least
DELETE FROM
bigint - int8 xml 1
nullif
random DISTINCT
DISTINCT ON ADMIN EXAMPLES
Sequence (Serial) Functions EXISTS
FROM
currval GROUP BY select pg_size_pretty(pg_tablespace_size('pg_default')) as tssize,
lastval HAVING pg_size_pretty(pg_database_size('somedb')) as dbsize,
nextval ILIKE pg_size_pretty(pg_relation_size('someschema.sometable')) as tblsize;
IN(..)
String Functions LIKE --Example importing data to table sometable
LIMIT ..OFFSET --from tab delimited where NULLs appear as NULL
|| NOT
ascii
COPY sometable FROM "/path/to/textfile.txt" USING DELIMITERS '\t' WITH NULL As 'NULL';
NOT IN(..)
chr
initcap NULLS FIRST1 --Example exporting a query to a comma separated (CSV) called textfile.csv
length NULLS LAST1 --setting NULLS to text NULL
lower ORDER BY COPY (SELECT * FROM sometable WHERE somevalue LIKE '%') TO '/path/to/textfile.csv'
lpad SELECT WITH NULL As 'NULL' CSV HEADER QUOTE AS '"';
ltrim SET
md5 SIMILAR TO vacuum analyze verbose;
position TRUNCATE TABLE
quote_ident UPDATE vacuum sometable;
quote_literal USING vacuum full;
regexp_matches WHERE
regexp_replace --Kills all active queries in selected db and list out process id
regexp_split_to_array Aggregates --and usename of process and if kill successful
regexp_split_to_table SELECT procpid, usename, pg_cancel_backend(procpid)
repeat avg
bit_and FROM pg_stat_activity
replace WHERE datname = 'somedb';
rpad bit_or
rtrim boolean_and
split_part boolean_or JOIN EXAMPLES
strpos count
count(DISTINCT) SELECT o.order_id, o.order_date, o.approved_date, SELECT 'x' As bucket, o.order_id, o.order_date,
substr
trim every COUNT(i.item_id) As nlineitems, COUNT(i.item_id) As nlineitems,
upper max SUM(i.unit_price*i.num_units) As total SUM(i.unit_price*i.num_units) As total
min FROM orders o FROM xorders o
Database Globals stddev INNER JOIN orderitems i ON o.order_id = i.order_id INNER JOIN xorderitems i ON o.order_id = i.order_id
stddev_pop (a bunch more) GROUP BY o.order_id, o.order_date
current_date sum GROUP BY o.order_id, o.order_date, o.approved_date
current_time sum(DISTINCT) HAVING SUM(i.unit_price*i.num_units) > 200 UNION ALL
current_timestamp variance ORDER BY o.approved_date NULLS FIRST; SELECT 'y' as bucket, o.order_id, o.order_date,
current_user xml_agg1 COUNT(i.item_id) As nlineitems,
localtime SUM(i.unit_price*i.num_units) As total
DDL FROM yorders o
Date Functions INNER JOIN yorderitems i ON o.order_id = i.order_id
ADD CONSTRAINT
age GROUP BY o.order_id, o.order_date
CREATE AGGREGATE
date_part(text, timestamp) CREATE CAST ORDER BY 1,3,2;
century CREATE (DEFAULT) CONVERSION
day CREATE DATABASE
decade CREATE DOMAIN DDL EXAMPLES
dow CREATE [OR REPLACE] FUNCTION CREATE DATABASE somedb CREATE TABLE orders(
doy CREATE (UNIQUE) INDEX WITH OWNER = somelogin order_id serial NOT NULL,
epoch CREATE LANGUAGE
hour ENCODING = 'WIN1252'; order_addeddt timestamp without time zone,
CREATE OPERATOR
month order_rating rating,
CREATE OPERATOR FAMILY 1 CONSTRAINT pk_orders_order_id PRIMARY KEY (order_id)
quarter
CREATE ROLE
second
CREATE RULE
)
week
CREATE SCHEMA WITH (OIDS=FALSE);
year
CREATE SEQUENCE
date_trunc CREATE TABLE
extract CREATE TYPE rating AS
CREATE TABLESPACE
interval ALTER TABLE ENUM('none', 'bronze', 'silver',
to_char 'gold', 'platinum');
CREATE TYPE
to_date CREATE [OR REPLACE] VIEW
to_timestamp
DROP [object]
CREATE AGGREGATE sum(text) ( CREATE OR REPLACE FUNCTION cp_test(somearg integer)
Date Predicates
SFUNC=textcat, RETURNS SETOF sometable AS
overlaps Enums 1 STYPE=text $$SELECT * FROM sometable where msg_id = $1;$$
); LANGUAGE 'sql' STABLE;
Array Constructs > < <= >= =
enum_cmp
ANY(array) enum_first UPDATE/INSERT/DELETE EXAMPLES
ARRAY[[4,5,6],..] enum_larger
ARRAY()
UPDATE sometable UPDATE sometable
enum_last
array_append enum_range
SET somevalue = 5 SET calccount = s.thecount
array_cat enum_smaller WHERE sometable.somename = 'stuff'; FROM (SELECT COUNT(someothertable.someid) as thecount,
array_dims someothertable.someid
array_lower XML 1 FROM someothertable
array_prepend GROUP BY someothertable.someid) s
array_to_string database_to_xml WHERE sometable.someid = s.someid;
array_upper database_to_xmlschema
SOME(array) query_to_xml
string_to_array --This only works on 8.1+ -- --Pre 8.1+ only supports single values inserts
query_to_xml_and_xmlschema
table_to_xml
Array Operators xmlattributes INSERT INTO orders(order_addeddt, order_rating)
xmlcomment VALUES ('2007-10-01 20:40', 'gold'), INSERT INTO orders(order_addeddt, order_rating)
= xmlconcat ('2007-09-01 11:00 AM', 'silver'), VALUES ('2007-10-01 20:40', 'gold');
<> xmlelement
< ('2007-09-02 10:00 PM', 'none'),
xmlforest ('2007-10-10 PM', 'bronze');
> xpath
<= xmlpi
|| --This is a fast delete that deletes everything in a table so be cautious.
xmlroot DELETE FROM sometable --Also only works on tables not referenced in foreign key contraints
Math Operators
Languages
WHERE somevalue = 'something'; TRUNCATE TABLE sometable;
% , ^, |/ c
||/,!, !!
@, &, |
pljava MISCELLANEOUS EXAMPLES
plpgsql
#,~, <<
plperl(u) --Enum range query using enum defined above - returns all orders in (bronze, silver, gold)
>>
plphp --Sorts in order bronze, silver, gold. Keep in mind if you reverse gold and bronze you get nothing
Math Functions plproxy SELECT *
plpython FROM orders
This is a subset plr WHERE order_rating
abs plruby BETWEEN 'bronze' AND 'gold'
cbrt plsh ORDER BY order_rating;
ceiling pltcl
degrees sql
exp
floor Key information_schema Views SELECT monthperiod.*,
log array_to_string(ARRAY(SELECT (d + 1)::varchar(20)
columns FROM generate_series(0,30) d
ln
mod sequences WHERE monthperiod.start_date + (d || ' day')::interval
tables BETWEEN monthperiod.start_date
pi
views AND
power
radians monthperiod.end_date), ',') as thedays
Key pg_catalog Tables/Views
random FROM (SELECT (n + 1) As mnum,
sqrt pg_class trim(to_char(date '2007-01-01' + (n || ' month')::interval, 'Mon')) As short_mname,
trunc pg_rules trim(to_char(date '2007-01-01' + (n || ' month')::interval, 'Month')) As long_mname,
pg_settings date '2007-01-01' + (n || ' month')::interval As start_date,
Trig Functions
pg_stat_activity date '2007-01-01' + ((n + 1) || ' month')::interval + - '1 day'::interval As end_date
pg_stat_database FROM generate_series(0,11) n) As monthperiod;
acos
pg_tablespaces
asin EXPLAIN ANALYZE SELECT * FROM sometable;
atan Large Object
atan2
Server Client
cos
cot lo_creat lo_close
COMMAND LINE EXAMPLES
These are located in bin folder of PostgreSQL
sin lo_create lo_creat
To get more info about each do a --help e.g. psql --help
tan lo_export lo_create
lo_import lo_export
lo_unlink lo_import pg_dump -i -h someserver -p 5432 -U someuser -F c -b -v -f "\somepath\somedb.backup" somedb
lo_lseek
lo_open pg_dumpall -i -h someserver -p 5432 -U someuser -c -o -f "\somepath\alldbs.sql"
lo_read pg_restore -i -h someserver -p 5432 -U someuser -d somedb -l "\somepath\somedb.backup"
lo_tell psql -h someserver -p 5432 -U someuser -d somedb -f "\somepath\somefiletorun.sql"
lo_unlink
lo_write psql -h someserver -p 5432 -U someuser -d somedb -c "CREATE TABLE sometable(st_id serial, st_name varchar(25))"
1New XML feature - output query as xml
-P "t" only output rows
psql -h someserver -p 5432 -U someuser -d somedb -P "t" -c "SELECT query_to_xml('select * from sometable', false, false, 'sometable')" -o "outputfile.xml";
http://www.postgresonline.com

You might also like