PostgreSQL Join Examples


This section contains the CREATE and INSERT code to run the examples from “The Join Operator” in a PostgreSQL database.

CREATE TABLE sales (
  sale_id       NUMERIC NOT NULL,
  employee_id   NUMERIC NOT NULL,
  subsidiary_id NUMERIC NOT NULL,
  sale_date     DATE    NOT NULL,
  eur_value     NUMERIC(17,2) NOT NULL,
  product_id    NUMERIC NOT NULL,
  quantity      NUMERIC NOT NULL,
  junk          CHAR(200),
  CONSTRAINT sales_pk     
     PRIMARY KEY (sale_id),
  CONSTRAINT sales_emp_fk 
     FOREIGN KEY          (subsidiary_id, employee_id)
      REFERENCES employees(subsidiary_id, employee_id)
);

SELECT SETSEED(0);

INSERT INTO sales (sale_id
                 , subsidiary_id, employee_id
                 , sale_date, eur_value
                 , product_id, quantity
                 , junk)
SELECT row_number() OVER (), data.*
  FROM (
       SELECT e.subsidiary_id, e.employee_id
            , (CURRENT_DATE - (RANDOM()*3650)::int) sale_date
            , (RANDOM()*100000)::int/100 eur_value
            , RANDOM()*25::int + 1 product_id
            , RANDOM()*5::int + 1 quantity
            , 'junk'
         FROM employees e
            , GENERATE_SERIES(1, 1800) gen
        WHERE MOD(employee_id, 7) = 4
          AND gen < employee_id / 5
        ORDER BY sale_date
       ) data
 WHERE TO_CHAR(sale_date, 'D') <> '1';


ANALYZE sales;

Notes:

  • The rows are inserted chronologically to reflect a natural table growth.

  • Only a small fraction of employees have sales at all.

About the Author

Photo of Markus Winand
Markus Winand tunes developers for high SQL performance. He also published the book SQL Performance Explained and offers in-house training as well as remote coaching at http://winand.at/

Recent Questions at Ask.Use-The-Index-Luke.com

1
vote
1
answer
52
views

How to query for "previous page" with keyset pagination?

5 hours ago alextsg 16
pagination postgresql
0
votes
0
answers
80
views
2
votes
1
answer
158
views

Table Names in Plural Form

Jul 31 at 16:43 simas 36
table