40
PostgreSQL: a comprehensive guide Informationssysteme (Information Systems) Winter 2006/07 © M. Scholl, S. Mansmann, 2006/07

PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Embed Size (px)

Citation preview

Page 1: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

PostgreSQL: a comprehensive guideInformationssysteme (Information Systems)

Winter 2006/07

© M. Scholl, S. Mansmann, 2006/07

Page 2: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Object-Relational Extensions‣ Postgres offers substantial additional power by incorporating the following

four additional basic concepts in such a way that users can easily extend the system:

✓ classes✓ inheritance✓ types✓ functions

‣ Other features provide additional power and flexibility:✓ constraints✓ triggers✓ rules✓ transaction integrity

‣ These features put Postgres into the category of databases referred to as object-relational.

2

Page 3: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Comments in SQL Scripts

‣ A comment is an arbitrary sequence of characters beginning with double dashes and extending to the end of the line, e.g.:

‣ C-style block comments are also supported, e.g.:

‣ A comment beginning with "/*" extends to the first occurrence of "*/".

-- This is a standard SQL comment

/* multi line comment */

3

Page 4: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types■ Postgres has a rich set of native data types available to users.■ Built-in data types in Postgres can be classified into the following categories:

■ Users may add new types to Postgres using the CREATE TYPE command.

■ Further info at http://www.postgresql.org/docs/8.1/interactive/datatype.html

✓ Numeric ✓ Monetary (depreciated) ✓ Binary ✓ Character ✓ Date/Time ✓ Boolean

✓ Geometric ✓ Network Addresses (new) ✓ Bit String ✓ Arrays ✓ Composite ✓ Object Identifier ✓ Pseudo-Types

4

Page 5: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: numeric

CREATE TABLE abc (a SERIAL);

is equivalent to

CREATE SEQUENCE tname_colname_seq;CREATE TABLE tname(colname INT4 DEFAULT nextval('tname_colname_seq');CREATE UNIQUE INDEX tname_colname_key on tname (colname);

Numeric types have a full set of corresponding arithmetic operators and functions.

The serial type is a special-case type (auto-increment) constructed from other existing components. It is typically used to create unique identifiers for table rows:

Numeric Type Storage Description Rangedecimal variable User-specified precision ~8000 digitsfloat4 4 bytes Variable-precision 6 decimal placesfloat8 8 bytes Variable-precision 15 decimal placesint2 2 bytes Fixed-precision -32768 to +32767int4 4 bytes Usual choice for fixed-precision -2147483648 to +2147483647int8 8 bytes Very large range fixed-precision +/- > 18 decimal placesnumeric variable User-specified precision no limitserial 4 bytes Identifer or cross-reference 0 to +2147483647

5

Page 6: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: binary■ bytea data type allows storage of binary strings.

■ A binary string is a sequence of octets (or bytes).

■ Binary strings are appropriate for storing data that the programmer thinks of as "raw bytes", whereas character strings are appropriate for storing text.

■ The SQL standard defines a different binary string type, called BLOB or BINARY LARGE OBJECT. The input format is different from bytea, but the provided functions and operators are mostly the same.

Name Storage Size Descriptionbytea 4 bytes plus the actual binary string variable-length binary string

6

Page 7: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: character

■ two primary character types: char and varchar. ■ text is more general type, without an explicit declared upper limit on the size.■ name type’s only purpose is for storage of internal catalog names.

Character Type Storage Recommendation Descriptionchar 1 byte SQL92-compatible Single characterchar(n) (4+n) bytes SQL92-compatible Fixed-length blank paddedtext (4+x) bytes Best choice Variable-lengthvarchar(n) (4+n) bytes SQL92-compatible Variable-length with limitname 32 bytes internal Thirty-one character internal type

7

Page 8: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: date/time

■ date and time input is accepted in almost any reasonable format■ date or time input needs to be enclosed into single quotes, like text strings ■ Some examples: 'January 8, 1999' '1999-01-08' '1/8/1999' '19990108' '990108' '1999.008' '99008'

Type Description Storage Earliest Latest Resolutiontimestamp both date and time 8 bytes 4713 BC AD 1465001 1 ms / 14 digitstimestamp with date and time 8 bytes 1903 AD 2037 AD 1 ms / 14 digitstime zone with time zoneinterval for time intervals 12 bytes -178000000 years 178000000 years 1 microseconddate dates only 4 bytes 4713 BC 32767 AD 1 daytime times of day only 4 bytes 00:00:00.00 23:59:59.99 1 microsecondtime with time zone times of day only 4 bytes 00:00:00.00+12 23:59:59.99-12 1 microsecond

8

Page 9: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: date/time

■ timestamp is a concatenation of a date and a time, followed by an optional AD or BC, followed by an optional time zone. Examples: 1999-01-08 04:05:06 -8:00 January 8 04:05:06 1999 PST

■ interval can be specified with the following syntax: num unit [num unit...] [direction]

where num is an integer; unit is second, minute, hour, day, week, month, year, decade, century, millennium, or abbreviations or plurals of these; direction can be ago or empty.

Example Description04:05:06.789 ISO-86014:05:06 ISO-86014:05 ISO-860140506 ISO-86014:05 AM Same as 04:054:05 PM Same as 16:05

The following are examples of valid time inputs:

9

Page 10: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: date/time

■ 'now' is resolved when the value is inserted.■ 'current' is resolved every time the value is retrieved.

SQL-compatible functions as date/time input for the corresponding data type:

CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP

Postgres also supports several special constants:

Constant Descriptioncurrent Current transaction time, deferredepoch 1970-01-01 00:00:00+00 (Unix system time zero)infinity Later than other valid times-infinity Earlier than other valid timesinvalid Illegal entrynow Current transaction time

10

Page 11: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: date/time

The SQL style has European and non-European (US) variants, which determines whether month follows day or vice versa:

Output formats can be set to one of the four styles ISO-8601, SQL (Ingres), traditional Postgres, and German, using the SQL command:

SET DATESTYLE TO German;

Examples of Postgres Date/Time Output Styles:

Style Specification Description ExampleISO ISO-8601 standard 1997-12-17 07:37:16-08SQL Traditional style 12/17/1997 07:37:16.00 PSTPostgres Original style Wed Dec 17 07:37:16 1997 PSTGerman Regional style 17.12.1997 07:37:16.00 PST

Style Specification Description ExampleEuropean day/month/year 17/12/1997 15:37:16.00 METUS month/day/year 12/17/1997 07:37:16.00 PST

11

Page 12: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: boolean

Example of using in a query:

SELECT bnr, TRUE AS with_isbn FROM book where ISBN IS NOT NULL;

■ Postgres supports bool as the SQL3 boolean type.■ bool can have one of only two states: 'true' or 'false'. ■ A third state, 'unknown', is not implemented and is not suggested in SQL3; NULL is an effective substitute. ■ bool can be used in any boolean expression.■ bool uses 1 byte of storage.

State Output InputTrue 't' TRUE, 't', 'true', 'y', 'yes', '1'False 'f' FALSE, 'f', 'false', 'n', 'no', '0'

12

Page 13: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: geometric

A rich set of functions and operators is available to perform various geometric operations such as: ✓scaling, ✓translation, ✓rotation, ✓determining intersections.

■ Geometric types represent two-dimensional spatial objects. ■ The most fundamental type, point, forms the basis for all other types.

Type Storage Representation Descriptionpoint 16 bytes (x,y) Point in spaceline 32 bytes ((x1,y1),(x2,y2)) Infinite linelseg 32 bytes ((x1,y1),(x2,y2)) Finite line segmentbox 32 bytes ((x1,y1),(x2,y2)) Rectangular boxpath 4+32n bytes ((x1,y1),...) Closed path (similar to polygon)path 4+32n bytes [(x1,y1),...] Open pathpolygon 4+32n bytes ((x1,y1),...) Polygon (similar to closed path)circle 24 bytes <(x,y),r> Circle (center and radius)

13

Page 14: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: geometric■ Examples of geometric operators:

Operator Description Example+ and - Translation box '((0,0),(1,1))' + point '(2.0,0)'* and / Scaling/rotation box '((0,0),(1,1))' * point '(2.0,0)'# Point or box of intersection '((1,-1),(-1,1))' # '((1,1),(-1,-1))'@-@ Length or circumference @-@ path '((0,0),(1,0))'@@ Center @@ circle '((0,0),10)'## Closest point point '(0,0)' ## lseg '((2,0),(0,2))'<-> Distance between circle '((0,0),1)' <-> circle '((5,0),1)'&& Overlaps? box '((0,0),(1,1))' && box '((0,0),(2,2))'<< Is strictly left of? circle '((0,0),1)' << circle '((5,0),1)'>> Is strictly right of? circle '((5,0),1)' >> circle '((0,0),1)'<<| Is strictly below? box '((0,0),(3,3))' <<| box '((3,4),(5,5))'|>> Is strictly above? box '((3,4),(5,5))' |>> box '((0,0),(3,3))'?# Intersects? lseg '((-1,0),(1,0))' ?# box '((-2,-2),(2,2))'?-| Is perpendicular? lseg '((0,0),(0,1))' ?-| lseg '((0,0),(1,0))'

14

Page 15: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: geometric■ Examples of geometric functions:

Function Return Type Description Examplearea(object) double precision area area(box '((0,0),(1,1))')center(object) point center center(box '((0,0),(1,2))')diameter(circle) double precision diameter of circle diameter(circle '((0,0),2.0)')height(box) double precision vertical size of box height(box '((0,0),(1,1))')isclosed(path) boolean a closed path? isclosed(path '((0,0),(1,1),(2,0))')isopen(path) boolean an open path? isopen(path '[(0,0),(1,1),(2,0)]')length(object) double precision length length(path '((-1,0),(1,0))')npoints(path) int number of points npoints(path '[(0,0),(1,1),(2,0)]')npoints(polygon) int number of points npoints(polygon '((1,1),(0,0))')pclose(path) path convert path to closed pclose(path '[(0,0),(1,1),(2,0)]')popen(path) path convert path to open popen(path '((0,0),(1,1),(2,0))')radius(circle) double precision radius of circle radius(circle '((0,0),2.0)')width(box) double precision horizontal size of box width(box '((0,0),(1,1))')

15

Page 16: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: network

■ cidr format for specifying classless networks is x.x.x.x/y where x.x.x.x is the network and /y is the number of bits in the netmask.■ inet has the same format but allows to leave off the bits part ( /y ) for addressing single hosts.

■ Data types to store IPv4, IPv6, and MAC addresses.■ offer input error checking and several specialized operators and functions.■ cidr stores networks in CIDR (Classless Inter-Domain Routing) notation■ inet holds, in one field, the TCP/IP address of a host including the CIDR-style subnet that it is in.

■ macaddr stores MAC addresses, i.e., Ethernet card hardware addresses

Name Storage Size Descriptioncidr 12 or 24 bytes IPv4 and IPv6 networksinet 12 or 24 bytes IPv4 and IPv6 hosts and networksmacaddr 6 bytes MAC addresses

16

Page 17: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: bit stringBit strings are strings of 1's and 0's and be used to store or visualize bit masks. There are two bit types: bit(n) and bit varying(n), where n is a positive integer. ■ bit type data must match the length n exactly; ■ bit varying data is of variable length up to the maximum length n;Bit-string constants look like regular string constants with a B (upper or lower case) immediately before the opening quote (no intervening whitespace), e.g., B'1001'.

Operator Description Example Result|| concatenation B'10001' || B'011' 10001011& bitwise AND B'10001' & B'01101' 1| bitwise OR B'10001' | B'01101' 11101# bitwise XOR B'10001' # B'01101' 11100~ bitwise NOT ~ B'10001' 1110<< bitwise shift left B'10001' << 3 1000>> bitwise shift right B'10001' >> 2 100

17

Page 18: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: arrays■ Columns of a table can be defined as variable-length multidimensional arrays. ■ Arrays of any built-in or user-defined base type can be created.■ array data type is named by appending square brackets ( []) to the data type name of the array elements.An example of using arrays:

CREATE TABLE sal_emp ( name text, pay_by_quarter integer[], schedule text[][]);

INSERT INTO sal_emp VALUES ('Bill', '{10000, 10000, 10000, 10000}', '{{"meeting", "lunch"}, {"training", "presentation"}}');

SELECT * FROM sal_emp;name | pay_by_quarter | schedule-----+--------------------------+------------------------------------------Bill | {10000,10000,10000,10000}| {{meeting,lunch},{training,presentation}}(2 rows)

18

Page 19: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: composite■ A composite type describes the structure of a row or record. ■ Values of composite types are similarly to those of simple types.

■ Composite type definition example: CREATE TYPE inventory_item AS ( name text, supplier_id integer, price numeric );

■ Using a composite type on a table: CREATE TABLE on_hand ( item inventory_item, count integer);

■ In a composite value, the field values are enclosed within parentheses and separated by commas: INSERT INTO on_hand VALUES ('("fuzzy dice",42,1.99)', 1000);

The ROW expression syntax may also be used to construct composite values: INSERT INTO on_hand VALUES (ROW('fuzzy dice', 42, 1.99), 1000);

19

Page 20: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: object identifier■ Object identifiers (OIDs) are used internally as primary keys for system tables. ■ OIDs are not added to user-created tables, unless WITH OIDS is specified when the table is created.

■ oid type is an unsigned 4-byte integer, and therefore, not large enough to provide database-wide uniqueness in large databases or even tables.■ Another system identifier type is xid, or transaction identifier (32-bit long). This is the data type of the system columns xmin and xmax.

■ A third system identifier type is cid, or command identifier (32-bit long). This is the data type of the system columns cmin and cmax.

■ A final identifier type in the system is tid, or tuple identifier (row identifier). This is the data type of the system column ctid . A tuple ID is a pair (block number, tuple index within block) that identifies the physical location of the row.

20

Page 21: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Data Types: pseudo-types■ Special-purpose entries that are collectively called pseudo-types.■ A pseudo-type cannot be used as a column data type, but it can be used to declare a function's argument or result type.■ Pseudo-types are useful when a function's behavior does not correspond to simply taking or returning a value of a specific SQL data type.

■ Overview of the existing pseudo-types:Name Descriptionany function accepts any input data type whatever.anyarray function accepts any array data typeanyelement function accepts any data typecstring function accepts or returns a null-terminated C stringinternal function accepts or returns a server-internal data typelanguage_handler returned by a procedural language call handlerrecord Identifies a function returning an unspecified row typetrigger A trigger function is declared to return triggervoid Indicates that a function returns no valueopaque An obsolete type name that served all the above purposes

21

Page 22: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Functions and Operators

✓ Logical Operators✓ Comparison Operators✓ Mathematical Functions and Operators✓ String Functions and Operators✓ Binary String Functions and Operators✓ Bit String Functions and Operators✓ Pattern Matching✓ Data Type Formatting Functions✓ Date/Time Functions and Operators✓ Geometric Functions and Operators

✓ Network Address Functions and Operators✓ Sequence Manipulation Functions✓ Conditional Expressions✓ Array Functions and Operators✓ Aggregate Functions✓ Subquery Expressions✓ Row and Array Comparisons✓ Set Returning Functions✓ System Information Functions✓ System Administration Functions

■ There is a large number of functions and operators for the built-in data types■ Users can also define their own functions and operators.■ The psql commands \df and \do show the list of all available functions / operators.■ Most of the functions and operators described here are not part of the SQL standard!

22

Page 23: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Operators: logical■ The usual logical operators are available:

AND OR NOT

■ A three-valued Boolean logic where the null value represents "unknown". ■ The operators AND and OR are commutative.

■ Observe the following truth tables:

a b a AND b a OR bTRUE TRUE TRUE TRUETRUE FALSE FALSE TRUETRUE NULL NULL TRUEFALSE FALSE FALSE FALSEFALSE NULL FALSE NULLNULL NULL NULL NULL

a NOT aTRUE FALSEFALSE TRUENULL NULL

23

Page 24: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Operators: comparison

■ Additionally, there is BETWEEN construct:

a BETWEEN x AND y is equivalent to a >= x AND a <= ya NOT BETWEEN x AND y is equivalent to a < x OR a > y

■ Constructs for checking null and boolean values: expression IS NULL expression IS NOT NULL expression IS TRUE expression IS NOT TRUE expression IS FALSE expression IS NOT FALSE expression IS UNKNOWN expression IS NOT UNKNOWN

Operator Description< less than> greater than<= less than or equal to>= greater than or equal to= equal<> or != not equal

■ Comparison operators are available for all data types where this makes sense. ■ All comparison operators are binary operators that return values of type boolean;

24

Page 25: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Operators: mathematical■ Mathematical operators are provided for many PostgreSQL types. ■ For types without common mathematical conventions (e.g., date/time types) the actual behavior of an operator will be different.

Operator Description Example Result+ addition 2 + 3 5- subtraction 37316 -1* multiplication 2 * 3 6/ division (integer division truncates results) 37290 2% modulo (remainder) 5 % 4 1^ exponentiation 2.0 ^ 3.0 8|/ square root |/ 25.0 5||/ cube root ||/ 27.0 3! factorial 5 ! 120!! factorial (prefix operator) !! 5 120@ absolute value @ -5.0 5

25

Page 26: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Functions: mathematical■ Below is just a subset of available mathematical functions (dp stands for double precision):

SQL example: SELECT round (salary, 1) FROM employee;

Function Return Type Description Example Resultabs(x) (same as x) absolute value abs(-17.4) 37362cbrt(dp) dp cube root cbrt(27.0) 3degrees(dp) dp radians to degrees degrees(0.5) 2,86479E+14exp(dp or numeric) (same as input) exponential exp(1.0) 2,71828E+14ln(dp or numeric) (same as input) natural logarithm ln(2.0) 0.693147180559945log(dp or numeric) (same as input) base 10 logarithm log(100.0) 2log(b numeric, x numeric)numeric logarithm to base b log(2.0, 64.0) 60000000000mod(y, x) (same as arguments) remainder of y/x mod(9,4) 1pi() dp π constant pi() 3,14159E+14power(a dp, b dp) dp a raised to the power of b power(9.0, 3.0) 729radians(dp) dp degrees to radians radians(45.0) 0.785398163397448random() dp random value betw. 0.0 and 1.0 random() round(v numeric, s int) numeric round to s decimal places round(42.4382, 2) 42.44sqrt(dp or numeric) (same as input) square root sqrt(2.0) 1,41421E+13

26

Page 27: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Functions: string■ Strings in this context include values of all the types character, character varying, and text.

■ SQL92 String Functions:

■ Example of using the string concatenation operator ||:

SELECT lastname || ', ' || firstname AS name FROM employee;

Function Returns Description Examplechar_length(string) int4 length of string char_length('jose')character_length(string) int4 length of string char_length('jose')lower(string) string convert string to lower case lower('TOM')octet_length(string) int4 storage length of string octet_length('jose')position(string in string) int4 location of specified substring position('o' in 'Tom')substring(string [from int] [for int])string extract specified substring substring('Tom' from 2 for 2)trim([leading|trailing|both] [string] from string)string trim characters from string trim(both 'x' from 'xTomx')upper(text) text convert text to upper case upper('tom')

27

Page 28: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Functions: Pattern MatchingLIKE string [NOT] LIKE pattern [ESCAPE escape-character]

■ '_ ' in pattern stands for (matches) any single character; ■ '% ' matches any string of zero or more characters. Examples: 'abc' LIKE 'a%' (true), 'abc' LIKE '_b' (false) ■ USE ILIKE instead of LIKE to make the match case-insensitive

SIMILAR TO string SIMILAR TO pattern [ESCAPE escape-character] string NOT SIMILAR TO pattern [ESCAPE escape-character]

■ SIMILAR TO interprets the pattern as a regular expression. ■ Example: 'abc' SIMILAR TO '%(b|d)%' (true)

substring(string from pattern for escape-character) ■ provides extraction of a substring that matches a regular expression pattern. ■ Example: substring('foobar' from '%#"o_b#"%' for '#') returns ' oob '

28

Page 29: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Functions: Formatting■ Formatting functions help convert various data types (date/time, integer, floating point, numeric) to formatted strings and convert strings to specific data types. ■ All functions follow a common calling convention: the first argument is the value to be formatted and the second argument defines the output or input format.

Function Return Type Description Exampleto_char(timestamp, text)text convert time stamp to string to_char(current_timestamp, 'HH12:MI:SS')to_char(interval, text) text convert interval to string to_char(interval '15h 2m 12s', 'HH24:MI:SS')to_char(int, text) text convert integer to string to_char(125, '999')to_char(dp, text) text convert real/dp to string to_char(125.8::real, '999D9')to_char(numeric, text) text convert numeric to string to_char(-125.8, '999D99S')to_date(text, text) date convert string to date to_date('05 Dec 2000', 'DD Mon YYYY')to_timestamp(text, text)timestamp with convert string to timestamp to_timestamp('05 Dec 2000', 'DD Mon YYYY')

time zoneto_timestamp(dp) timestamp with convert UNIX epoch to to_timestamp(200120400)

time zone timestampto_number(text, text) numeric convert string to numeric to_number('12,454.8-', '99G999D9S')

■ Full list of template Patterns for Date/Time and numeric formatting can be found at http://www.postgresql.org/docs/8.1/interactive/functions-formatting.html

29

Page 30: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Built-in Functions: date/time

■ Possible fields in extract() are day, decade, epoch, hour, microseconds, millennium, milliseconds, minute, month, quarter, second, timezone, week, year, century, etc. ■ In addition, the SQL OVERLAPS operator is supported: (start1, end1) OVERLAPS (start2, end2) (start1, length1) OVERLAPS (start2, length2)

Function Returns Description Example Resultage(timestamp, timestamp) interval age in years, months, and daysage('now', timestamp '1957-06-13') 43 years 9 mons 27 daysage(timestamp) interval Subtract from current_date age(timestamp '1957-06-13') 43 years 8 mons 3 daysdate_part(text, timestamp) float8 Get subfield (like extract) date_part('hour', timestamp '2001-02-16 20:38:40') 20date_part(text, interval) float8 Get subfield (like extract) date_part('month', interval '2 years 3 months') 3date_trunc(text, timestamp) timestamp Truncate to specified level date_trunc('hour', timestamp '2001-02-16 20:38:40')35476,83333extract(field from timestamp)float8 Get subfield extract(hour from timestamp '2001-02-16 20:38:40')20extract(field from interval)float8 Get subfield extract(month from interval '2 years 3 months') 3isfinite(timestamp) boolean Test for finite time stamp isfinite(timestamp '2001-02-16 21:28:30') trueisfinite(interval) boolean Test for finite interval isfinite(interval '4 hours') truejustify_hours(interval) interval interval presented as days justify_hours(interval '24 hours') 1 dayjustify_days(interval) interval interval presented as months justify_days(interval '30 days') 1 monthlocaltime time Time of day localtimestamp timestamp Date and time now() timestamp Current date and time timeofday() text Current date and time

30

Page 31: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Conditional Expressions■ CASE expression is a conditional expression, similar to if/else statement:

CASE WHEN condition THEN result [WHEN ...] [ELSE result] END

Example: SELECT grade, CASE WHEN grade<=2.0 THEN 'good' WHEN grade>4.0 THEN 'bad' ELSE 'ok' END FROM exams;

Result: grade | case ------+------- 2.2 | ok 4.0 | ok 1.3 | good 5.0 | bad

■ Further conditional expressions: ■ COALESCE(value [, ...]) returns the first of its arguments that is not null. ■ NULLIF(value1, value2) returns null if value1=value2; otherwise it returns value1. ■ GREATEST(value [, ...]) selects the largest value from a list of expressions. ■ LEAST(value [, ...]) selects the smallest value from a list of expressions.

31

Page 32: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Array Functions and OperatorsOperator Description Example Result= equal ARRAY[1.1,2.1,3.1]::int[] = ARRAY[1,2,3] t<> not equal ARRAY[1,2,3] <> ARRAY[1,2,4] t< less than ARRAY[1,2,3] < ARRAY[1,2,4] t> greater than ARRAY[1,4,3] > ARRAY[1,2,4] t<= less than or equal ARRAY[1,2,3] <= ARRAY[1,2,3] t>= greater than or equal ARRAY[1,4,3] >= ARRAY[1,4,3] t|| array-to-array concatenation ARRAY[1,2,3] || ARRAY[4,5,6] {1,2,3,4,5,6}|| array-to-array concatenation ARRAY[1,2,3] || ARRAY[[4,5,6],[7,8,9]] {{1,2,3},{4,5,6},{7,8,9}}|| element-to-array concatenation 3 || ARRAY[4,5,6] {3,4,5,6}|| array-to-element concatenation ARRAY[4,5,6] || 7 {4,5,6,7}

Function Returns Example Resultarray_cat (anyarray, anyarray) anyarray array_cat(ARRAY[1,2,3], ARRAY[4,5]) {1,2,3,4,5}array_append (anyarray, anyelement) anyarray array_append(ARRAY[1,2], 3) {1,2,3}array_prepend (anyelement, anyarray) anyarray array_prepend(1, ARRAY[2,3]) {1,2,3}array_dims (anyarray) text array_dims(ARRAY[[1,2,3], [4,5,6]]) [1:2][1:3]array_lower (anyarray, int) int array_lower(array_prepend(0, ARRAY[1,2,3]), 1)0array_upper (anyarray, int) int array_upper(ARRAY[1,2,3,4], 1) 4array_to_string (anyarray, text) text array_to_string(ARRAY[1, 2, 3], '~^~') 1~^~2~^~3string_to_array (text, text) text[] string_to_array('xx~^~yy~^~zz', '~^~') {xx,yy,zz}

32

Page 33: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Aggregate Functions■ Aggregate functions compute a single result value from a set of input values. ■ Note that except for COUNT, these functions return null when no rows are selected.■ bool_and and bool_or correspond to SQL aggregates every and any or some.

Function Argument Return Type Descriptionavg(expression) number numeric for integer, dp for float, the average (arithmetic mean)

or interval otherwise same as argument of all input valuesbit_and(expression) int or bit same as argument data type bitwise AND / OR of all bit_or(expression) non-null input valuesbool_and(expression) bool bool true if all input values are truebool_or(expression) bool bool true if at least one input value is truecount(*) bigint number of input valuescount(expression) any bigint number of non-null input valuesevery(expression) bool bool equivalent to bool_andmax(expression) array, numeric, same as argument type maximum/minimum value ofmin(expression) string, date/time expression across all input valuesstddev(expression) number dp for float, otherwise numeric sample standard deviationsum(expression) number bigint/numeric for integer, dp for sum of expression

float, otherwise same as argument across all input valuesvariance(expression) number dp for float, otherwise numeric sample variance

33

Page 34: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Subquery Expressions■ All subquery expression forms return boolean true or false.

EXISTS (subquery)If subquery returns at least one row, the result of EXISTS is true; if subquery returns no rows, the result is false.

expr IN (subquery)

expr NOT IN (subquery)

subquery must return exactly one column. The result of IN is true if any equal row in subquery is found. The result of NOT IN is true if only unequal rows in subquery are found.

expr op ANY (subquery)

expr op SOME (subquery)

subquery must return exactly one column. expr is evaluated and compared to each row in subquery result using operator op. The result of ANY is true if any true result is obtained. SOME is a synonym for ANY. IN is equivalent to = ANY.

expr op ALL (subquery)

subquery must return exactly one column. The result of ALL is true if all rows yield true (including the case where subquery returns no rows).NOT IN is equivalent to <> ALL.

34

Page 35: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Row and Array Comparisons■ Constructs for making multiple comparisons between groups of values are syntactically related to the subquery forms of the previous slide, but do not involve subqueries.

expr IN (value[, ...])

expr NOT IN (value[, ...])

The list in parentheses contains scalar expressions. The result of IN is true if expr result is equal to any of the scalar expressions. The result of NOT IN is true if expr result is unequal to all of the right-hand expressions.

expr op ANY (array expr)

expr op SOME (array expr)

expr is evaluated and compared to each element of the array expr using operator op. The result of ANY is true if any true result is obtained. SOME is a synonym for ANY.

expr op ALL (array expr)

expr is evaluated and compared to each element of the array expr using operator op. The result of ALL is true if all rows yield true (including the case where the array has zero elements).

35

Page 36: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Type Conversion■ SQL is a strongly typed language. ■ There are four fundamental SQL constructs requiring distinct type conversion rules:

Function callsFunctions can have one or more arguments. Since PostgreSQL permits function overloading, the parser must select the right function based on the data types of the supplied arguments.

Operators Like functions, operators can be overloaded, and so the same problem of selecting the right operator exists.

Value StorageThe expressions in the SQL INSERT and UPDATE statements must be matched up with, and perhaps converted to, the types of the target columns.

UNION, CASE, and related constructs

To merge subresults into a unified single set of columns, the types of the subresults of each clause must be matched up and converted to a uniform set. The same holds for ARRAY constructs, and for the GREATEST and LEAST functions.

36

Page 37: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Type Conversion■ PostgreSQL divides lexical elements into only 5 fundamental categories: 1) integers 2) non-integer numbers 3) strings, identifiers 4) key words. ■ Constants of most non-numeric types are first classified as strings. ■ The SQL language definition allows specifying type names with strings, and this mechanism can be used to specify the correct type explicitly. For example, the query has two literal constants, of type text and point:

SELECT text 'Origin' AS label, point '(0,0)' AS coordinate;

label | coordinate --------+--------------- Origin | (0,0)

■ One can also use a function, such as CAST(), round(), substr(): SELECT CAST(2.5 AS int); /* returns 3*/ SELECT round(2.5555, 2); /* returns 2.6*/

37

Page 38: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Inheritance■ PostgreSQL implements table inheritance which can be useful for database designers. Let's start with an example: CREATE TABLE cities ( name text, population float, altitude int);

CREATE TABLE capitals ( state char(2)) INHERITS (cities);

■ The capitals table inherits all the columns of its parent table cities, and also has an extra column state.■ A table can inherit from one or multiple tables, and a query can reference either 1) all rows of a table, or 2) all rows of a table plus all of its descendant tables (default).■ SELECT, UPDATE and DELETE syntax supports the ONLY keyword meaning that the statement should apply only to the table itself, and not any tables below in the inheritance hierarchy.

38

Page 39: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Inheritance■ Compare the following two queries:

SELECT name, altitude FROM cities WHERE altitude > 500; -- returns cities including capitals

SELECT name, altitude FROM ONLY cities WHERE altitude > 500; -- returns cities without capitals

■ However, INSERT and COPY always insert into exactly the table specified (no propagation or redirection!)■ Primary and foreign key constraints are not inherited!■ Inheritance can only be defined in the CREATE TABLE statement and can not be removed other than by dropping the table.■ To remove a table and all of its descendants, use DROP CASCADE option.■ Table access permissions are not automatically inherited.

39

Page 40: PostgreSQL - Uni Konstanz · triggers rules ... Postgres has a rich set of native data types available to users. ... numeric variable User-specified precision no limit

Sources

☞ PostgreSQL 8.1.5 Documentation at

http://www.postgresql.org/docs/8.1/interactive/

☞ PostgreSQL User's Guide at

http://www.cs.helsinki.fi/u/laine/postgresql/user/user.htm

40