Postgresql83 Cheatsheet

You might also like

Download as pdf or txt
Download as pdf or txt
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 bit numeric(length,precision)
set_config [INNER] JOIN boolean oid
vacuum analyze verbose INTERSECT (ALL) bytea serial - serial4
vacuum full LEFT JOIN
character varying(length) - varchar(length) bigserial - serial8
NATURAL JOIN
RIGHT JOIN
character(length) - char(length) text
Common Functions
UNION (ALL) date time without timezone - time
cast, :: enum 1 time with timezone - timez
coalesce SQL Keywords
double precision - float4 float8 timestamp without timezone - timestamp
generate_series integer - int4 timestamp with timezone - timestampz
BETWEEN .. AND
greatest
CASE WHEN .. END bigint - int8 xml 1
least
nullif DELETE FROM
DISTINCT
random
DISTINCT ON ADMIN EXAMPLES
Sequence (Serial) Functions EXISTS
FROM select pg_size_pretty(pg_tablespace_size('pg_default')) as tssize,
currval GROUP BY pg_size_pretty(pg_database_size('somedb')) as dbsize,
lastval HAVING pg_size_pretty(pg_relation_size('someschema.sometable')) as tblsize;
nextval ILIKE
IN(..) --Example importing data to table sometable
String Functions LIKE --from tab delimited where NULLs appear as NULL
LIMIT ..OFFSET COPY sometable FROM "/path/to/textfile.txt" USING DELIMITERS '\t' WITH NULL As 'NULL';
|| NOT
ascii NOT IN(..) --Example exporting a query to a comma separated (CSV) called textfile.csv
chr --setting NULLS to text NULL
initcap NULLS FIRST1
COPY (SELECT * FROM sometable WHERE somevalue LIKE '%') TO '/path/to/textfile.csv'
length NULLS LAST1
WITH NULL As 'NULL' CSV HEADER QUOTE AS '"';
lower ORDER BY
lpad SELECT
ltrim SET vacuum analyze verbose;
md5 SIMILAR TO vacuum sometable;
position TRUNCATE TABLE vacuum full;
quote_ident UPDATE
quote_literal USING --Kills all active queries in selected db and list out process id
regexp_matches WHERE --and usename of process and if kill successful
regexp_replace SELECT procpid, usename, pg_cancel_backend(procpid)
Aggregates
regexp_split_to_array FROM pg_stat_activity
regexp_split_to_table avg WHERE datname = 'somedb';
repeat bit_and
replace
rpad
bit_or JOIN EXAMPLES
boolean_and
rtrim boolean_or SELECT o.order_id, o.order_date, o.approved_date, SELECT 'x' As bucket, o.order_id, o.order_date,
split_part count COUNT(i.item_id) As nlineitems, COUNT(i.item_id) As nlineitems,
strpos count(DISTINCT) SUM(i.unit_price*i.num_units) As total SUM(i.unit_price*i.num_units) As total
substr every FROM orders o FROM xorders o
trim max INNER JOIN orderitems i ON o.order_id = i.order_id INNER JOIN xorderitems i ON o.order_id = i.order_id
upper min GROUP BY o.order_id, o.order_date, o.approved_date GROUP BY o.order_id, o.order_date
stddev HAVING SUM(i.unit_price*i.num_units) > 200 UNION ALL
Database Globals stddev_pop (a bunch more)
ORDER BY o.approved_date NULLS FIRST; SELECT 'y' as bucket, o.order_id, o.order_date,
sum COUNT(i.item_id) As nlineitems,
current_date
sum(DISTINCT) SUM(i.unit_price*i.num_units) As total
current_time
variance
current_timestamp FROM yorders o
current_user xml_agg1 INNER JOIN yorderitems i ON o.order_id = i.order_id
localtime GROUP BY o.order_id, o.order_date
DDL
ORDER BY 1,3,2;
Date Functions
ADD CONSTRAINT
age CREATE AGGREGATE
date_part(text, timestamp) CREATE CAST
DDL EXAMPLES
century CREATE (DEFAULT) CONVERSION CREATE DATABASE somedb CREATE TABLE orders(
day CREATE DATABASE WITH OWNER = somelogin order_id serial NOT NULL,
decade CREATE DOMAIN ENCODING = 'WIN1252'; order_addeddt timestamp without time zone,
dow CREATE [OR REPLACE] FUNCTION
order_rating rating,
doy CREATE (UNIQUE) INDEX
CREATE LANGUAGE
CONSTRAINT pk_orders_order_id PRIMARY KEY (order_id)
epoch
hour CREATE OPERATOR )
WITH (OIDS=FALSE);
month CREATE OPERATOR FAMILY 1
quarter CREATE ROLE
second CREATE RULE CREATE TYPE rating AS
week CREATE SCHEMA
year ENUM('none', 'bronze', 'silver',
CREATE SEQUENCE 'gold', 'platinum');
date_trunc CREATE TABLE
extract CREATE TABLESPACE
interval ALTER TABLE CREATE AGGREGATE sum(text) ( CREATE OR REPLACE FUNCTION cp_test(somearg integer)
to_char CREATE TYPE SFUNC=textcat, RETURNS SETOF sometable AS
to_date CREATE [OR REPLACE] VIEW STYPE=text $$SELECT * FROM sometable where msg_id = $1;$$
to_timestamp DROP [object] ); LANGUAGE 'sql' STABLE;
Date Predicates

overlaps Enums 1 UPDATE/INSERT/DELETE EXAMPLES


UPDATE sometable UPDATE sometable
Array Constructs > < <= >= =
enum_cmp
SET somevalue = 5 SET calccount = s.thecount
ANY(array) enum_first WHERE sometable.somename = 'stuff'; FROM (SELECT COUNT(someothertable.someid) as thecount,
ARRAY[[4,5,6],..] enum_larger someothertable.someid
ARRAY() enum_last FROM someothertable
array_append enum_range GROUP BY someothertable.someid) s
array_cat enum_smaller WHERE sometable.someid = s.someid;
array_dims
array_lower XML 1 --This only works on 8.1+ -- --Pre 8.1+ only supports single values inserts
array_prepend
array_to_string database_to_xml INSERT INTO orders(order_addeddt, order_rating)
array_upper database_to_xmlschema INSERT INTO orders(order_addeddt, order_rating)
SOME(array) query_to_xml
VALUES ('2007-10-01 20:40', 'gold'),
('2007-09-01 11:00 AM', 'silver'), VALUES ('2007-10-01 20:40', 'gold');
string_to_array query_to_xml_and_xmlschema
table_to_xml ('2007-09-02 10:00 PM', 'none'),
Array Operators xmlattributes ('2007-10-10 PM', 'bronze');
xmlcomment
= xmlconcat --This is a fast delete that deletes everything in a table so be cautious.
<> xmlelement DELETE FROM sometable --Also only works on tables not referenced in foreign key contraints
< xmlforest WHERE somevalue = 'something';
> TRUNCATE TABLE sometable;
xpath
<= xmlpi
|| xmlroot MISCELLANEOUS EXAMPLES
Math Operators
Languages --Enum range query using enum defined above - returns all orders in (bronze, silver, gold)
--Sorts in order bronze, silver, gold. Keep in mind if you reverse gold and bronze you get nothing
% , ^, |/ c
||/,!, !! SELECT *
pljava FROM orders
@, &, | plpgsql
#,~, << WHERE order_rating
plperl(u) BETWEEN 'bronze' AND 'gold'
>>
plphp ORDER BY order_rating;
Math Functions
plproxy
plpython
This is a subset plr
abs plruby SELECT monthperiod.*,
cbrt plsh array_to_string(ARRAY(SELECT (d + 1)::varchar(20)
ceiling pltcl FROM generate_series(0,30) d
degrees sql WHERE monthperiod.start_date + (d || ' day')::interval
exp BETWEEN monthperiod.start_date
floor Key information_schema Views AND
log monthperiod.end_date), ',') as thedays
columns
ln FROM (SELECT (n + 1) As mnum,
sequences
mod trim(to_char(date '2007-01-01' + (n || ' month')::interval, 'Mon')) As short_mname,
tables
pi trim(to_char(date '2007-01-01' + (n || ' month')::interval, 'Month')) As long_mname,
views
power date '2007-01-01' + (n || ' month')::interval As start_date,
radians Key pg_catalog Tables/Views date '2007-01-01' + ((n + 1) || ' month')::interval + - '1 day'::interval As end_date
random FROM generate_series(0,11) n) As monthperiod;
sqrt pg_class
trunc pg_rules EXPLAIN ANALYZE SELECT * FROM sometable;
pg_settings
Trig Functions pg_stat_activity
acos
pg_stat_database COMMAND LINE EXAMPLES
pg_tablespaces These are located in bin folder of PostgreSQL
asin
To get more info about each do a --help e.g. psql --help
atan Large Object
atan2 Server Client
cos pg_dump -i -h someserver -p 5432 -U someuser -F c -b -v -f "\somepath\somedb.backup" somedb
cot lo_creat lo_close pg_dumpall -i -h someserver -p 5432 -U someuser -c -o -f "\somepath\alldbs.sql"
sin lo_create lo_creat pg_restore -i -h someserver -p 5432 -U someuser -d somedb -l "\somepath\somedb.backup"
lo_export lo_create psql -h someserver -p 5432 -U someuser -d somedb -f "\somepath\somefiletorun.sql"
tan lo_import lo_export
lo_unlink lo_import psql -h someserver -p 5432 -U someuser -d somedb -c "CREATE TABLE sometable(st_id serial, st_name varchar(25))"
lo_lseek 1New XML feature - output query as xml
lo_open
lo_read -P "t" only output rows
lo_tell 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";
lo_unlink
lo_write

http://www.postgresonline.com

You might also like