4. SQL Syntax
Value Expression
http://developer.postgresql.org/pgdocs/postgres/sql-expressions.html
Calling Function
Named notation is especially useful for functions that have a large number of parameters (makes the associations between parameters and actual arguments more explicit and reliable)
Positional notation, a function call is written with its argument values in the same order as they are defined in the function declaration (parameters can only be omitted from right to left)
CREATE FUNCTION concat_lower_or_upper(a text, b text, uppercase boolean DEFAULT false)
RETURNS text AS $$
SELECT CASE WHEN $3 THEN UPPER($1 || ' ' || $2) ELSE LOWER($1 || ' ' || $2) END;
$$ LANGUAGE SQL IMMUTABLE STRICT;
Positional Notation
SELECT concat_lower_or_upper('Hello', 'World', true);
HELLO WORLD
SELECT concat_lower_or_upper('Hello', 'World');
hello world
Named notation
SELECT concat_lower_or_upper(a := 'Hello', b := 'World', uppercase := true);
HELLO WORLD
SELECT concat_lower_or_upper(a := 'Hello', uppercase := true, b := 'World');
HELLO WORLD
Mixed Notation
SELECT concat_lower_or_upper('Hello', 'World', uppercase := true);
HELLO WORLD
5. Data DefinitionConstraints - following example demonstrates different methods of constraints usage.
CREATE TABLE products ( CHECK (price > 0), price numeric, price1 numeric, CONSTRAINT positive_price CHECK (price1 > 0), CHECK (price > price1), CHECK (discounted_price > 0 AND price > discounted_price), product_no integer UNIQUE, product_no integer CONSTRAINT must_be_different UNIQUE, product_no integer REFERENCES products (product_no), -- foreign key FOREIGN KEY (b, c) REFERENCES other_table (c1, c2), product_no integer REFERENCES products ON DELETE RESTRICT, order_id integer REFERENCES orders ON DELETE CASCADE);
RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked. CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.
Modifying TableALTER TABLE products ADD COLUMN description text; --adding a column
ALTER TABLE products DROP COLUMN description CASCADE; -- drop column
-- add constrain
ALTER TABLE products ADD CHECK (name <> '');
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_id) REFERENCES product_groups;
ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77; -- add default
ALTER TABLE products RENAME COLUMN prod_no TO product_no; -- rename column
6.Partitioning
Partitioning refers to splitting what is logically one large table into smaller physical pieces. Benefits are:
- Query performance can be improved, when heavily accessed rows of table are in a single partition. The partitioning substitutes for leading columns of indexes, reducing index size and making it more likely that the heavily-used parts of the indexes fit in memory.
- When queries or updates access a large percentage of a single partition, performance can be improved by taking advantage of sequential scan of that partition instead of using an index..
- Bulk loads and deletes can be accomplished by adding or removing partitions, if that requirement is planned into the partitioning design.
- Seldom-used data can be migrated to cheaper and slower storage media.
Range Partitioning
The table is partitioned into "ranges" defined by a key column or set of columns, with no overlap
List Partitioning
The table is partitioned by explicitly listing which key values appear in each partition.
Combining Queries
The results of two queries can be combined using the set operations union, intersection, and difference.
- query1 UNION [ALL] query2 - eliminates duplicate rows from its result, in the same way as DISTINCT, unless UNION ALL is used
- query1 INTERSECT [ALL] query2 - returns all rows that are both in the result. Duplicate rows are eliminated unless INTERSECT ALL is used.
- query1 EXCEPT [ALL] query2 - returns all rows that are in the result of query1 but not in the result of query2. (This is sometimes called the difference between two queries.)
7.With Queries (Common Table Expressions)
WITH provides a way to write auxiliary statements for use in a larger query. These statements, which are often referred to as Common Table Expressions or CTEs, can be thought of as defining temporary tables that exist just for one query.
Data-Modifying Statements in WITH
You can use data-modifying statements (INSERT, UPDATE, or DELETE) in WITH. This allows you to perform several different operations in the same query. An example is:
WITH moved_rows AS ( DELETE FROM products WHERE "date" >= '2010-10-01' AND "date" < '2010-11-01' RETURNING * ) INSERT INTO products_log SELECT * FROM moved_rows;
This query effectively moves rows from products to products_log. The DELETE in WITH deletes the specified rows from products, returning their contents by means of itsRETURNING clause; and then the primary query reads that output and inserts it into products_log.
8. Data typeChapter 9. Functions and Operators
9.3. Mathematical Functions and Operatorshttp://www.postgresql.org/docs/9.1/interactive/functions-math.html
9.4. String Functions and Operators
http://www.postgresql.org/docs/9.1/interactive/functions-string.html
9.5. Binary String Functions and Operators
http://www.postgresql.org/docs/9.1/interactive/functions-binarystring.html
9.7. Pattern Matching
http://www.postgresql.org/docs/9.1/interactive/functions-matching.html
9.8. Data Type Formatting Functions
http://www.postgresql.org/docs/9.1/interactive/functions-formatting.html
9.9. Date/Time Functions and Operators
http://www.postgresql.org/docs/9.1/interactive/functions-datetime.html
9.10. Enum Support Functions
http://www.postgresql.org/docs/9.1/interactive/functions-enum.html
http://www.postgresql.org/docs/9.1/interactive/functions-geometry.html
9.12. Network Address Functions and Operators
http://www.postgresql.org/docs/9.1/interactive/functions-net.html
9.13. Text Search Functions and Operators
http://www.postgresql.org/docs/9.1/interactive/functions-textsearch.html
9.14. XML Functions
http://www.postgresql.org/docs/9.1/interactive/functions-xml.html
9.15. Sequence Manipulation Functions
http://www.postgresql.org/docs/9.1/interactive/functions-sequence.html
9.16. Conditional Expressions
Case
SELECT ... WHERE CASE WHEN x <> 0 THEN y/x > 1.5 ELSE false END;
NULLIF
9.17. Array Functions and Operators
The
NULLIF
function returns a null value if value1 equals value2; otherwise it returns value1. This can be used to perform the inverse operation of the COALESCE
example given above:SELECT NULLIF(value, '(none)')
http://www.postgresql.org/docs/9.1/interactive/functions-array.html
9.18. Aggregate Functions
http://www.postgresql.org/docs/9.1/interactive/functions-aggregate.html
9.19. Window Functions
http://www.postgresql.org/docs/9.1/interactive/functions-window.html
9.22. Set Returning Functions
This section describes functions that possibly return more than one row. http://www.postgresql.org/docs/9.1/interactive/functions-info.html
SELECT * FROM generate_series(2,4); generate_series ----------------- 2 3 4 SELECT * FROM generate_series(5,1,-2); generate_series ----------------- 5 3 1 -- this example relies on the date-plus-integer operator SELECT current_date + s.a AS dates FROM generate_series(0,14,7) AS s(a); dates ------------ 2004-02-05 2004-02-12 2004-02-19 SELECT * FROM generate_series('2008-03-01 00:00'::timestamp, '2008-03-04 12:00', '10 hours'); generate_series --------------------- 2008-03-01 00:00:00 2008-03-01 10:00:00 2008-03-01 20:00:00 2008-03-02 06:00:00 2008-03-02 16:00:00
9.23 System Information Functions
Session Information Functions
Session Information Functions
Name | Return Type | Description |
---|---|---|
current_catalog | name | name of current database (called "catalog" in the SQL standard) |
current_database() | name | name of current database |
current_query() | text | text of the currently executing query, as submitted by the client (might contain more than one statement) |
current_schema [()] | name | name of current schema |
current_schemas(boolean) | name[] | names of schemas in search path, optionally including implicit schemas |
current_user | name | user name of current execution context |
inet_client_addr() | inet | address of the remote connection |
inet_client_port() | int | port of the remote connection |
inet_server_addr() | inet | address of the local connection |
inet_server_port() | int | port of the local connection |
pg_backend_pid() | int | Process ID of the server process attached to the current session |
pg_conf_load_time() | timestamp with time zone | configuration load time |
pg_is_other_temp_schema(oid) | boolean | is schema another session's temporary schema? |
pg_listening_channels() | setof text | channel names that the session is currently listening on |
pg_my_temp_schema() | oid | OID of session's temporary schema, or 0 if none |
pg_postmaster_start_time() | timestamp with time zone | server start time |
session_user | name | session user name |
user | name | equivalent to current_user |
version() | text | PostgreSQL version information |
http://www.postgresql.org/docs/9.1/interactive/functions-admin.html