Postgres – Casts e Converts

Function Return Type Description Example
to_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(double precision, text) text convert real/double precision 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_number(text, text) numeric convert string to numeric to_number('12,454.8-', '99G999D9S')
to_timestamp(text, text) timestamp with time zone convert string to time stamp to_timestamp('05 Dec 2000', 'DD Mon YYYY')
to_timestamp(double precision) timestamp with time zone convert UNIX epoch to time stamp to_timestamp(200120400)

Precisa fazer um between entre datas que estão em varchar no formato brasileiro?

select * from tabela where to_date(data,'DD/MM/YYYY') between to_date('23/05/2010','DD/MM/YYYY') and to_date('22/06/2010','DD/MM/YYYY')

Conversão Explícita de Tipos (CAST)

CAST ( expressão AS tipo ) AS apelido; — Sintaxe SQL ANSI
Outra forma:
Tipo ( expressão );
Exemplo:
SELECT DATE ’10/05/2002′ – DATE ’10/05/2001′; — Retorna a quantidade de dias – -entre as duas datas
Para este tipo de conversão devemos:

Usar float8 ao invés de double precision;

Usar entre aspas alguns tipos como interval, time e timestamp
Obs.: aplicações portáveis devem evitar esta forma de conversão e em seu lugar usar o CAST explicitamente.
A função CAST() é utilizada para converter explicitamente tipos de dados em outros.

SELECT CAST(2 AS double precision) ^ CAST(3 AS double precision) AS “exp”;

SELECT ~ CAST(’20′ AS int8) AS “negativo”; – Retorna -21

SELECT round(CAST (4 AS numeric), 4); – Retorna 4.0000

SELECT substr(CAST (1234 AS text), 3);

SELECT 1 AS “real” UNION SELECT CAST(’2.2′ AS REAL);
Funções Diversas

SELECT CURRENT_DATABASE();

SELECT CURRENT_SCHEMA();

SELECT CURRENT_SCHEMA(boolean);

SELECT CURRENT_USER;

SELECT SESSION_USER;

SELECT VERSION();
SELECT CURRENT_SETTING(‘DATESTYLE’);

SELECT HAS_TABLE_PRIVILEGE(‘usuario’,'tabela’,'privilegio’);

SELECT HAS_TABLE_PRIVILEGE(‘postgres’,'nulos’,'insert’); – - Retorna: t

SELECT HAS_DATABASE_PRIVILEGE(‘postgres’,'testes’,'create’); – - Retorna: t

SELECT HAS_SCHEMA_PRIVILEGE(‘postgres’,'public’,'create’); – - Retorna: t
SELECT relname FROM pg_class WHERE pg_table_is_visible(oid);
Arrays

SELECT ARRAY[1.1,2.2,3.3]::INT[] = ARRAY[1,2,3];

SELECT ARRAY[1,2,3] = ARRAY[1,2,8];

SELECT ARRAY[1,3,5] || ARRAY[2,4,6];

SELECT 0 || ARRAY[2,4,6];
Array de char com 48 posições e cada uma com 2:

campo char(2) [48]
Funções Geométricos

area(objeto) – - area(box ‘((0,0), (1,1))’);

center(objeto) – - center(box ‘((0,0), (1,2))’);

diameter(circulo double) – - diameter(circle ‘((0,0), 2.0)’);

height(box) – - height(box ‘((0,0), (1,1))’);

length(objeto) – - length(path ‘((-1,0), (1,0))’);

radius(circle) – - radius(circle ‘((0,0), 2.0)’);

width(box) – - width(box ‘((0,0), (1,1))’);
Funções para Redes

Funções cidr e inet

host(inet) – - host(’192.168.1.5/24′) – - 192.168.1.5

masklen(inet) – - masklen(’192.168.1.5/24′) – - 24

netmask(inet) – - netmask(’192.168.1.5/24′) – - 255.255.255.0

network(inet) – - network(’192.168.1.5/24′) – - 192.168.1.0/24
Função macaddr

trunt(macaddr) – - trunc(maraddr ’12:34:34:56:78:90:ab’) – - 12:34:56:00:00:00
Funções de Informação do Sistema

current_database()

current_schema()

current_schemas(boolean)

current_user()

inet_client_addr()

inet_client_port()

inet_server_addr()

inet_server_port()

pg_postmaster_start_time()

version()

has_table_privilege(user, table, privilege) – dá privilégio ao user na tabela

has_table_privilege(table, privilege) – dá privilégio ao usuário atual na tabela

has_database_privilege(user, database, privilege) – dá privilégio ao user no banco

has_function_privilege(user, function, privilege) – dá privilégio ao user na função

has_language_privilege(user, language, privilege) – dá privilégio ao user na linguagem

has_schema_privilege(user, schema, privilege) – dá privilégio ao user no esquema

has_tablespace_privilege(user, tablespace, privilege) – dá privilégio ao user no tablespace
current_setting(nome) – valor atual da configuração

set_config(nome, novovalor, is_local) – seta parâmetro de retorna novo valor

pg_start_backup(label text)

pg_stop_backup()

pg_column_size(qualquer)

pg_tablespace_size(nome)

pg_database_size(nome)

pg_relation_size(nome)

pg_total_relation_size(nome)

pg_size_pretty(bigint)

pg_ls_dir(diretorio)

pg_read_file(arquivo text, offset bigint, tamanho bigint)

pg_stat_file(arquivo text)

No comments yet.