⚡0 XP🔥0

Views, Indexes and Window Functions

Lesson 9 of 10 ⏱ 5 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs SQL

Save queries as views, speed up searches with indexes (and read query plans), and use window functions - ROW_NUMBER, RANK, DENSE_RANK, running totals, LAG/LEAD and PARTITION BY.

Views - saved queries#

A view is a named query. You select from it like a table, but it runs its query each time, so it always shows current data. Views hide complex joins, give users a simplified (or restricted) picture of the data, and keep reports consistent.

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Note

A normal view stores no data. PostgreSQL and Oracle also have materialized views, which store the result for speed and must be refreshed.

Indexes - making lookups fast#

Without an index, finding WHERE email = '...' means scanning every row (like reading a whole book to find one word). An index is a sorted structure (usually a B-tree) that lets the database jump straight to matching rows - like the index at the back of a book.

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

The first plan says SCAN students (read everything); after the index it says SEARCH students USING INDEX idx_students_city. With 30 rows you will not notice; with 30 million rows it is the difference between minutes and milliseconds.

Index on... Good idea when
primary keys always (created automatically)
foreign keys joins use them constantly
columns in frequent WHERE, ORDER BY, JOIN e.g. email, city, created_at
UNIQUE columns created automatically to enforce uniqueness
Common Mistake

Indexes are not free: each one uses storage and slows down INSERT, UPDATE and DELETE, because the index must be updated too. Add them for real query patterns, not on every column.

हिंदी में समझें

Index किताब के पीछे वाली विषय-सूची (index) जैसा है - पूरा data पढ़े बिना सीधे सही जगह पहुँचा देता है। जिन columns पर बार-बार search, join या sort होता है, उन पर index बनाइए। पर हर column पर index बनाना ठीक नहीं - insert/update धीमे हो जाते हैं।

Window functions#

A window function computes a value over a set of rows related to the current row - without collapsing them like GROUP BY does. The syntax is function() OVER (PARTITION BY ... ORDER BY ...).

Ranking: ROW_NUMBER, RANK, DENSE_RANK#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Nisha and Aditi both have 9.47: RANK gives both 1 and skips 2; DENSE_RANK does not skip; ROW_NUMBER always counts 1, 2, 3...

PARTITION BY - restart the calculation for each group#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

"Top N per group" is one of the most asked SQL interview questions - and this CTE + ROW_NUMBER() pattern is the standard answer.

Aggregates as window functions#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

OVER () with nothing inside means "the whole result".

Running totals and moving averages#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

LAG and LEAD - compare with the previous or next row#

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
Function Gives
ROW_NUMBER() 1, 2, 3... (no ties)
RANK() ties share a rank, then a gap
DENSE_RANK() ties share a rank, no gap
NTILE(n) splits rows into n buckets (quartiles...)
SUM/AVG/COUNT(...) OVER group totals or running totals on every row
LAG(col) / LEAD(col) value from the previous / next row
FIRST_VALUE / LAST_VALUE first / last value in the window

Summary#

  • Views save queries under a name; they simplify and secure access.
  • Indexes speed up WHERE/JOIN/ORDER BY on the indexed columns; check plans with EXPLAIN.
  • Window functions (... OVER (PARTITION BY ... ORDER BY ...)) rank, total and compare rows while keeping every row.
  • "Top N per group" = CTE + ROW_NUMBER() OVER (PARTITION BY ...).

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Rank students within each department

Show dept_id, name, cgpa and dept_rank (use RANK() over each department, highest CGPA first) for students with a department. Order by dept_id, then dept_rank.

Database: college (see the tables in this lesson)
2

Running total of fees by admission date

Show admission_date, name, fee and running_total (sum of fees from the earliest admission up to this row), ordered by admission_date then student_id.

Database: college (see the tables in this lesson)

Quick Quiz

Q1.

What is a view?

Q2.

An index mainly speeds up...

Q3.

For marks 95, 90, 90, 85, what does RANK() give?

Q4.

How does a window function differ from GROUP BY?