postgresources – Telegram
#query

Don't use BETWEEN (especially with timestamps)

SELECT * FROM blah WHERE timestampcol BETWEEN '2018-06-01' AND '2018-06-08'


This will include results where the timestamp is exactly 2018-06-08 00:00:00.000000, but not timestamps later in that same day

SELECT * FROM blah WHERE timestampcol >= '2018-06-01' AND timestampcol < '2018-06-08'


BETWEEN is safe for discrete quantities like integers or dates, as long as you remember that both ends of the range are included in the result. But it's a bad habit to get into.
#query

When dealing with NULL values in SQL, you have to use things like IS NULL or IS NOT NULL in your predicates:

SELECT * FROM people WHERE age IS NOT NULL;

But did you know that Postgres supports a shorter (though non-standard) approach if you want to save some characters?

SELECT * FROM people WHERE age NOTNULL;

There's also ISNULL for the IS NULL case, although the numbers of characters saved is somewhat reduced ;-)

And if you've ever wondered why you can't just go age = NULL or age != NULL, this is because NULL is defined to be an 'unknown' value and the SQL standard dictates that you can't compare an 'unknown' value with another.
#query

Want to quickly see how big a database is? You can do it in a single query:

SELECT pg_size_pretty(pg_database_size('n2'));

select pg_size_pretty(pg_database_size('n2'));

pg_size_pretty
----------------
446 MB
(1 row)
#type

create type dimensions as (
width integer,
height integer,
depth integer
);

create table moving_boxes (
id serial primary key,
dims dimensions not null
);

insert into moving_boxes (dims) values (row(3,4,5)::dimensions);
#query #size

> select pg_database_size('hr_hotels');
pg_database_size
------------------
8249516

> select pg_relation_size('reservations');
pg_relation_size
------------------
1531904

> select pg_size_pretty(pg_relation_size('users_pkey'));
pg_size_pretty
----------------
240 kB