Syntax & Queries

Update

Returning data after updating

Return the updated data with:

UPDATE table_name
SET ...
WHERE ...
RETURNING *
;

Insert

on conflict

Specify conflict keys on insert, and when data already exists, choose what to do.

INSERT INTO table_name (col1)
VALUES (...)
ON CONFLICT (col1)
DO NOTHING
;

Joins

using

Use USING instead of ON when the joining column name is the same in them.

cross

In a CROSS JOIN query, the result (also known as Cartesian product) lines up each row in the left table with each row in the right table to present all possible combinations of rows.

If table1 has n rows and table2 has m rows, the result will have n * m rows.

natural

A NATURAL JOIN is a join that creates an implicit join based on the same column names in the joined tables.

circle-info

If not specified it will use INNER.

Sorting

order by

Order null values along with regular data. NULLS FIRST will place NULL values before other values.

Aggregates

group by

Groups rows by columns.

circle-exclamation

rollup

ROLLUP will give summarize rows for the given aggregate function, (e.g. AVG). So it will return the averages aggregated by col_name in each row, but it will also give a new row with the average of all the groups.

Providing more than one column in ROLLUP will also produce this new total averages by the aggregation of the two columns and for aggregating for one column.

cube

CUBE allows you to generate combinations of multiple grouping sets.

grouping sets

GROUPING SETS is similar to CUBE but you specify the groups yourself, instead of letting postgres make a combination of them.

filter

You can use FILTER (WHERE ...) to filter data specifically to each aggregate function.

count

circle-info

When using Count to count a particular column, have in mind that null values of this column are not counted.

Use Count(*) then, to count the rows.

having

Filter a set of groups.

circle-exclamation

Utility functions

greatest

Pick the highest out of a list of values.

least

Pick the lowest out of a list of values.

case

To use ifs in a select statement.

circle-info

If ELSE is not used, a null value will be returned if none of the conditions were met.

split_part()

Splits the string value by a delimiter and returns the desired position.

trim()

circle-info

If not specified, the default character is space.

TRIM removes the longest string that contains a specific character from a string.

LTRIM removes all characters from the beginning of a string.

RTRIM removes all characters from the end of a string.

BRIM is the combination of LTRIM and RTRIM.

pad()

circle-info

If not specified, the default character is space.

LPAD pads a string on the left to a specified length with a sequence of characters.

RPAD pads a string on the right to a specified length with a sequence of characters.

repeat()

Repeats a string a spefied number of times.

Operators

posix regular expressions

Provide powerful means for pattern matching compared to LIKE or SIMILAR TO.

Postgresl supports 4 operators for posix regular expressions (also know as tilde operator ~).

~ returns true or false depending on whether or not a regular expression can match a string or a part thereof.

  • ~: matches regular expression (case sensitive)

  • ~*: matches regular expression (case insensitive)

  • !~: does not match regular expression (case sensitive)

  • !~*: does not match regular expression (case insensitive)

regexp_matches

REGEXP_MATCHES function matches a regular expression against a string and returns matched substrings.

regexp_replace

REGEXP_REPLACE function replaces strings that match a regular expression.

regexp_split_to_table

REGEXP_SPLIT_TO_TABLE will split delimited text into rows.

regexp_split_to_array

REGEXP_SPLIT_TO_ARRAY will split delimited text into arrays.

concatenation

Use ||, CONCAT or CONCAT_WS to concatenate strings like:

circle-info

CONCAT_WS will handle not putting the "separator" if there is only one value or none.

And it also ignores NULL values to be concatenated.

inclusion

@>, <@ and && are some inclusion operators, that usually check if something is in the other thing, or if something overlaps with another thing, etc.

Text Search Engines

Using data types like tsvector and tsquery, Postgres gives us powerful ways for full text searches on large amounts of text.

  • tsvector: Text to be searched and stored in optimized format.

  • tsquery: Represent the search query terms and operations.

tsvector

It reduces text to a sorted list of "lexemes" (words without the variations created by suffixes), which are units of meaning in language.

circle-exclamation
circle-info

Use GIN index for tsvector is needed.

Create tsvector columns

to_tsvector

TO_TSVECTOR creates a list of tokens for a given string, returning:

  • Every token as a lexeme, with

  • pointers (the position in the document), and

  • where words that carry little meaning, such as articles (the) and conjunctions (and, or) are conveniently omitted

  • orders the words alphabetically, and number following each colon indicates its position in original text.

to_tsquery

TO_TSQUERY accepts a list of words that will be checked against the normalizaed vector we created with to_tsvector.

ts_rank

TS_RANK to rank query results.

Last updated