Copy schema table in postgres

CREATE TABLE new_table_name (LIKE old_table_name INCLUDING ALL);
2 ноября 2021, 11:33

Get estimated count rows

explain (format json) select * from tbl
28 апреля 2021, 17:38

Generate date ranges in postgresql

SELECT d::date
FROM generate_series(
  timestamp without time zone '2021-01-01',
  timestamp without time zone '2021-02-01',
  '1 day'
) AS gs(d);

19 января 2021, 12:33

Knex join with subquery

knex(
  knex('A').where('A.id',1).as('t1')
).leftJoin(
  knex('B').where('B.id', 2).as('t2'), 
  't1.c', 
  't2.d'
)
15 января 2021, 10:33

Postgresql reset sequence

SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false)

or 

SELECT
	setval(pg_get_serial_sequence('tbl', 'id'), COALESCE(max(id) + 1, 1), FALSE)
FROM
	tbl;
19 декабря 2020, 20:04

Show enum types in postgress

select enum_range(null::my_type)
16 сентября 2020, 18:20

Update multiple rows with one query in postgresql

CREATE TABLE table1 ( 
	"id" Integer NOT NULL,
	"a" Text NOT NULL,
	"b" Text NOT NULL );
insert into table1 values  
(1, 'a', 'b'),
(2, 'a', 'b')
update table1 as t set 
  a = data.a,
  b = data.b
from (values
  (1, 'a1', 'b1'),
  (2, 'a2', 'b2')
) as data(id, a, b)
where t.id = data.id
29 августа 2020, 21:41

Difference between ROW_NUBER(), RANK(), DENSE_RANK() in postgresql

WITH T(StyleID, ID)
     AS (SELECT 1,1 UNION ALL
         SELECT 1,1 UNION ALL
         SELECT 1,1 UNION ALL
         SELECT 1,2)
SELECT *,
       RANK() OVER(PARTITION BY StyleID ORDER BY ID)       AS 'RANK',
       ROW_NUMBER() OVER(PARTITION BY StyleID ORDER BY ID) AS 'ROW_NUMBER',
       DENSE_RANK() OVER(PARTITION BY StyleID ORDER BY ID) AS 'DENSE_RANK'
FROM   T  
Returns

StyleID     ID       RANK      ROW_NUMBER      DENSE_RANK
----------- -------- --------- --------------- ----------
1           1        1         1               1
1           1        1         2               1
1           1        1         3               1
1           2        4         4               2
6 августа 2020, 20:48