Skip to content

Instantly share code, notes, and snippets.

@julianhyde
Created August 20, 2024 02:58
Show Gist options
  • Save julianhyde/70609f4de92ccabec41b9a9df0689d23 to your computer and use it in GitHub Desktop.
Save julianhyde/70609f4de92ccabec41b9a9df0689d23 to your computer and use it in GitHub Desktop.
Query that uses the "SCOTT" schema (tables EMP, DEPT, BONUS, SALGRADE, DUMMY) as CTEs, in Postgres SQL
WITH dummy (dummy) AS (VALUES
(0)
), emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) AS (VALUES
(7369, 'SMITH', 'CLERK', 7902, DATE '1980-12-17', 800.00, null, 20),
(7499, 'ALLEN', 'SALESMAN', 7698, DATE '1981-02-20', 1600.00, 300.00, 30),
(7521, 'WARD', 'SALESMAN', 7698, DATE '1981-02-22', 1250.00, 500.00, 30),
(7566, 'JONES', 'MANAGER', 7839, DATE '1981-02-04', 2975.00, null, 20),
(7654, 'MARTIN', 'SALESMAN', 7698, DATE '1981-09-28', 1250.00, 1400.00, 30),
(7698, 'BLAKE', 'MANAGER', 7839, DATE '1981-01-05', 2850.00, null, 30),
(7782, 'CLARK', 'MANAGER', 7839, DATE '1981-06-09', 2450.00, null, 10),
(7788, 'SCOTT', 'ANALYST', 7566, DATE '1987-04-19', 3000.00, null, 20),
(7839, 'KING', 'PRESIDENT', null, DATE '1981-11-17', 5000.00, null, 10),
(7844, 'TURNER', 'SALESMAN', 7698, DATE '1981-09-08', 1500.00, 0.00, 30),
(7876, 'ADAMS', 'CLERK', 7788, DATE '1987-05-23', 1100.00, null, 20),
(7900, 'JAMES', 'CLERK', 7698, DATE '1981-12-03', 950.00, null, 30),
(7902, 'FORD', 'ANALYST', 7566, DATE '1981-12-03', 3000.00, null, 20),
(7934, 'MILLER', 'CLERK', 7782, DATE '1982-01-23', 1300.00, null, 10)
), dept (deptno, dname, loc) AS (VALUES
(10, 'ACCOUNTING', 'NEW YORK'),
(20, 'RESEARCH', 'DALLAS'),
(30, 'SALES', 'CHICAGO'),
(40, 'OPERATIONS', 'BOSTON')
), bonus AS (SELECT *
FROM (VALUES
('xxxxxxxxxx', 'xxxxxxxxx', 2345.67, 1234.56)) AS t (ename, job, sal, comm)
WHERE 1 = 0
), salgrade (grade, losal, hisal) AS (VALUES
(1, 700, 1200),
(2, 1201, 1400),
(3, 1401, 2000),
(4, 2001, 3000),
(5, 3001, 9999)
)
SELECT count(*)
FROM emp NATURAL JOIN dept;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment