← Back to SQL, page 16

sql-0301 · Easy fresher

What does an empty OVER () compute, and how does adding ORDER BY inside it change SUM?

OVER () makes the whole result set one partition with an unordered frame, so SUM(x) OVER () is the grand total on every row. Adding ORDER BY switches the default frame to 'from the start up to the current row and its peers', so the same SUM becomes a running total.

Full answer
sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
sql
SELECT day, amount,
       SUM(amount) OVER ()             AS total,
       SUM(amount) OVER (ORDER BY day) AS running
FROM daily_sales ORDER BY day;
dayamounttotalrunning
2026-03-01120700120
2026-03-0280700200
2026-03-03150700350
2026-03-0590700440
2026-03-0660700500
2026-03-09200700700

The total column is 700 everywhere. The running column grows row by row, because ORDER BY inside OVER changes the frame, not just the order.

This is the most common source of surprise with window functions: adding ORDER BY to get a "nicer" window silently changes the numbers. When you want the grand total, leave the window empty or say ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.

sql
CREATE TABLE daily_sales (
  day    TEXT PRIMARY KEY,
  amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
  ('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
  ('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);

SELECT day, amount,
       SUM(amount) OVER ()             AS total,
       SUM(amount) OVER (ORDER BY day) AS running
FROM daily_sales ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • OVER () is one partition, whole-set frame
  • SUM OVER () gives the grand total per row
  • ORDER BY in OVER changes the default frame
  • Write the frame explicitly when in doubt

Common mistakes

  • Adding ORDER BY to OVER () and getting running totals by accident
  • Thinking ORDER BY inside OVER only affects output order

Follow-ups

  • What is the default frame with ORDER BY?
  • How would you show share of total per row?

Tips

  • Show both columns side by side