Postgres Snippets

Get size of a table SELECT pg_size_pretty(pg_total_relation_size('schemaname.tablename')); Select unique combination of fields / tuples SELECT DISTINCT ON(field1, field2) field1, field2 FROM thetable Select rows where a combination of fields is not unique SELECT columnA, columnB, count(*) AS count FROM thetable GROUP BY columnA, columnB HAVING count(*) > 1 Search for rows with array containing value Assuming, the field appointments has the type date[] SELECT * FROM mtable WHERE appointments @> ARRAY['2023-09-19'::date] ...

March 1, 2010 · 8 min · 1655 words · Micha Kops

SQL Snippets

Count unique / all values SELECT COUNT(DISTINCT <FIELDNAME>), COUNT(ALL <FIELDNAME>) FROM <TABLE>; Partially anonymize e-mail addresses UPDATE <TABLE_NAME> SET <EMAIL_FIELD>= INSERT( <EMAIL_FIELD>, POSITION('@' IN <EMAIL_FIELD>), 100, CONCAT(FLOOR(1 + (RAND() * 100)),'@hascode.com')) WHERE POSITION('@' IN <EMAIL_FIELD>)>0; Find duplicate entries SELECT COUNT(*), <FIELDNAME> FROM <TABLENAME> GROUP BY <FIELDNAME> HAVING COUNT(*)>1; MySQL Fix Zero Dates for Data Imports Error: ERROR 1067 (42000) at line 1234: Invalid default value for ‘datefield’ In newer MySQL Versions zero in date or zero dates are forbidden .. check this with: ...

March 1, 2010 · 1 min · 150 words · Micha Kops