User Tools

Site Tools


postgresqlfunctions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
postgresqlfunctions [2024/03/08 10:10] z0hpvkpostgresqlfunctions [2025/03/08 22:24] (current) – external edit 127.0.0.1
Line 1: Line 1:
-===== SQL and pl/pgsql =====+===== SQL and PL/pgSQL =====
  
 ==== JSON ==== ==== JSON ====
-https://cdn.sanity.io/files/sczeoy4w/production/065818a8cd88cd048137368e5710ec35c0361185.pdf+[[https://cdn.sanity.io/files/sczeoy4w/production/065818a8cd88cd048137368e5710ec35c0361185.pdf|| JSON Cheat Sheet]]
  
 ==== Arrays ==== ==== Arrays ====
 +
 +Arrays can be displayed as ''ARRAY[1,2,3]'' or ''{1,2,3}''.\\
  
 === Operators === === Operators ===
Line 64: Line 66:
 ALTER TABLE name_basics ALTER primaryprofession TYPE text[]  ALTER TABLE name_basics ALTER primaryprofession TYPE text[] 
                         USING string_to_array(primaryprofession, ',');                          USING string_to_array(primaryprofession, ','); 
 +</code>
 +
 +==== Hierarchical Data ====
 +<code SQL>
 +WITH RECURSIVE t1(n) AS (
 +  VALUES (0)
 +  UNION ALL
 +  SELECT n+1 FROM t1 WHERE n < 5)
 +SELECT * FROM t1;
 +</code>
 +
 +<code SQL>
 +CREATE TABLE family (key int, parent_key int, name text);
 +INSERT INTO family VALUES (1, null, 'Grandad');
 +INSERT INTO family VALUES (2, 1, 'Dad');
 +INSERT INTO family VALUES (3, 2, 'Tracy');
 +INSERT INTO family VALUES (4, 2, 'Ian');
 +INSERT INTO family VALUES (5, 3, 'Michaela');
 +INSERT INTO family VALUES (6, 3, 'Joshua');
 +INSERT INTO family VALUES (7, 5, 'Freya');
 +INSERT INTO family VALUES (8, 1, 'Colin');
 +INSERT INTO family VALUES (9, 8, 'Mark');
 +INSERT INTO family VALUES (10, 8, 'Simon');
 +</code>
 +
 +<code SQL>
 +WITH RECURSIVE a AS (
 +  SELECT key, parent_key, name, 1::integer level, ARRAY[key] path, ' ' indent,
 +         CASE WHEN EXISTS (SELECT 1 FROM family f2 WHERE f2.parent_key = f1.key )
 +       THEN 0 ELSE 1 END is_leaf
 +  FROM   family f1
 +  WHERE  parent_key IS NULL
 +  UNION ALL
 +  SELECT b.key, b.parent_key, a.indent || b.name, a.level +1, array_append(a.path, b.key), a.indent || ' ',
 +         CASE WHEN EXISTS (SELECT 1 FROM family f2 WHERE f2.parent_key = b.key )
 +       THEN 0 ELSE 1 END is_leaf
 +  FROM   family b
 +  JOIN   a ON a.key = b.parent_key )
 +SELECT key, parent_key, name, level, path, is_leaf FROM a ORDER BY path;
 </code> </code>
  
postgresqlfunctions.1709892649.txt.gz · Last modified: 2025/03/08 22:23 (external edit)