Skip to content

Instantly share code, notes, and snippets.

@joallard
Created March 20, 2018 20:40
Show Gist options
  • Save joallard/df50bd0dca1402f9ab30727092ec2cae to your computer and use it in GitHub Desktop.
Save joallard/df50bd0dca1402f9ab30727092ec2cae to your computer and use it in GitHub Desktop.
Postgres Cheat Sheet

Postgres Stuff Cheat Sheet

Regex

Match

Use the ~ operator.

9.7.3. POSIX Regular Expressions

Table 9-12. Regular Expression Match Operators

Operator Description Example
~ Matches regular expression, case sensitive 'thomas' ~ '.*thomas.*'
~* Matches regular expression, case insensitive 'thomas' ~* '.*Thomas.*'
!~ Does not match regular expression, case sensitive 'thomas' !~ '.*Thomas.*'
!~* Does not match regular expression, case insensitive 'thomas' !~* '.*vadim.*'

String

Presence

For when your stringish column might contain the empty string as well as nulls.

string string = '' string = '' is false string = '' is not false
Original string String is empty We are sure the string is not empty (empty is false) 'String is empty' is something other than 'surely false'
'a' false true false
'' true false true
null null false true

String is present: string = '' is false

String is blank: string = '' is not false

Split

string_to_array(anyarray, delimiter [, nullstring])

Array

Compact

Ruby array.compact!

PG array_remove(array, null)

Length

array_length(array, 1)

Join

Ruby array.join(delimiter)

PgSQL array_to_string(array, delimiter)

JSON

Fetch

json->'key' (returns JSON)

json->>'key' (returns text)

The -> operator returns a json result. Casting it to text leaves it in a json reprsentation.

The ->> operator returns a text result. Use that instead.

test=> SELECT '{"car": "going"}'::jsonb -> 'car';
 ?column? 
----------
 "going"
(1 row)

test=> SELECT '{"car": "going"}'::jsonb ->> 'car';
 ?column? 
----------
 going
(1 row)

Answer from Craig Ringer on Stackoverflow: "Remove double quotes from the return of a function in PostgreSQL"

Indexes

Create

CREATE INDEX tbl_col_idx ON table_name (column_name);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment