icon Join with us for Oracle DBA Training Live Session ENROLL NOW

Building a Recommendation System with SQL Window Functions in PostgreSQL

Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Breadcrumb Abstract Shape
Building a recommendation system using PostgreSQL SQL Window Functions to analyze customer behavior, rank products, and generate personalized recommendations.
  • 19 Nov, 2026
  • 0 Comments
  • 14 Mins Read

Building a Recommendation System with SQL Window Functions in PostgreSQL

Building a Recommendation System with SQL Window Functions in Postgres

Recommendation systems are an important part of modern applications. Platforms like Netflix, Amazon, YouTube, and Spotify use recommendation engines to suggest movies, products, videos, and music based on user preferences and previous activities.

Have you ever wondered how an application identifies which products a customer might purchase next or which content a user is most likely to watch?

Behind many recommendation systems, databases play an important role in storing user activity, analyzing historical data, identifying patterns, and generating personalized suggestions.

While recommendation systems are often associated with Python, machine learning, and artificial intelligence, PostgreSQL can also handle many recommendation-related tasks using its powerful SQL capabilities.

One particularly useful feature is SQL Window Functions in PostgreSQL.

Window functions allow developers to analyze user activity, rank products, calculate purchase frequencies, identify popular items, and generate personalized recommendations without requiring complex application-level logic.

In this blog, we will explore how to build a basic recommendation system using PostgreSQL Window Functions with a practical, real-world example.

1. What Is a Recommendation System?

A recommendation system is a software mechanism that analyzes user behavior, preferences, and historical interactions to suggest relevant products, services, or content.

For example:

  • An e-commerce platform recommends products based on previous purchases.

  • A streaming platform suggests movies based on viewing history.

  • A music application recommends songs based on listening patterns.

  • An online learning platform suggests courses based on previously completed courses.

The main objective is to provide relevant suggestions that improve user engagement and customer experience.

Types of Recommendation Systems

There are several approaches to building recommendation systems.

1. Collaborative Filtering

Collaborative filtering recommends items based on the behavior of similar users.

For example, if User A and User B purchased similar products, the system may recommend products purchased by User B to User A.

2. Content-Based Filtering

Content-based filtering recommends items based on their characteristics and a user’s previous preferences.

For example, if a customer frequently purchases laptops, the application might recommend laptop accessories.

3. Popularity-Based Recommendation

This approach recommends products or content based on overall popularity.

For example, an e-commerce application may display the top 10 most-purchased products.

4. Hybrid Recommendation System

A hybrid system combines multiple recommendation techniques to generate more relevant suggestions.

For this tutorial, we will focus on building a basic recommendation engine using SQL Window Functions in PostgreSQL.

2. Why Use PostgreSQL Window Functions?

PostgreSQL provides several powerful SQL features for analyzing relational data. Window functions are particularly useful when recommendation logic requires ranking, comparison, and aggregation.

Unlike regular aggregate functions, window functions calculate results across a set of related rows without combining those rows into a single output row.

For example, suppose an e-commerce application stores thousands of customer purchases.

You may want to identify:

  • The top 5 products purchased by each customer.

  • The most popular products in each category.

  • Products frequently purchased together.

  • The latest purchases made by every customer.

  • Products that a customer has not purchased but other similar customers frequently buy.

PostgreSQL window functions can help implement these requirements directly in SQL.

Important Window Functions

Window Function Purpose
ROW_NUMBER() Assigns a unique sequential number to each row
RANK() Assigns ranking while leaving gaps after ties
DENSE_RANK() Assigns ranking without gaps
LAG() Accesses a previous row’s value
LEAD() Accesses a subsequent row’s value
NTILE() Divides rows into approximately equal groups
SUM() OVER() Calculates a running or partition-based total
COUNT() OVER() Calculates counts without collapsing rows

These functions are useful for analyzing customer behavior and generating product recommendations.

3. Understanding the Project: E-Commerce Recommendation System

Let’s build a practical recommendation system for an e-commerce application.

Imagine an online shopping platform where customers purchase products from different categories.

The application stores customer information, product information, and purchase history.

Our objective is to analyze this information and recommend products based on customer purchasing behavior.

Database Structure

We will create three tables:

  1. Customers

  2. Products

  3. Orders

Typed Query Builders: Kysely vs. Drizzle

Step 1: Create the Customers Table

CREATE TABLE customers (
    customer_id SERIAL PRIMARY KEY,
    customer_name VARCHAR(100),
    city VARCHAR(100)
);

Insert sample customer records:

INSERT INTO customers (customer_name, city)
VALUES
('Rahul', 'Pune'),
('Priya', 'Mumbai'),
('Amit', 'Nashik'),
('Sneha', 'Pune'),
('Vikram', 'Mumbai');

Step 2: Create the Products Table

CREATE TABLE products (
    product_id SERIAL PRIMARY KEY,
    product_name VARCHAR(100),
    category VARCHAR(100),
    price NUMERIC(10,2)
);

Insert sample products:

INSERT INTO products
(product_name, category, price)
VALUES
('Laptop', 'Electronics', 55000),
('Mobile', 'Electronics', 25000),
('Headphones', 'Electronics', 3000),
('Keyboard', 'Accessories', 1500),
('Mouse', 'Accessories', 800),
('Monitor', 'Electronics', 12000),
('Smart Watch', 'Wearables', 5000);

Step 3: Create the Orders Table

This table stores customer purchase information.

CREATE TABLE orders (
    order_id SERIAL PRIMARY KEY,
    customer_id INT REFERENCES customers(customer_id),
    product_id INT REFERENCES products(product_id),
    quantity INT,
    order_date DATE
);

Insert sample order records:

INSERT INTO orders
(customer_id, product_id, quantity, order_date)
VALUES
(1, 1, 1, '2026-01-10'),
(1, 2, 1, '2026-01-12'),
(1, 3, 2, '2026-01-15'),
(2, 1, 1, '2026-01-11'),
(2, 3, 1, '2026-01-14'),
(2, 6, 1, '2026-01-18'),
(3, 2, 2, '2026-01-12'),
(3, 4, 1, '2026-01-17'),
(4, 1, 1, '2026-01-19'),
(4, 2, 1, '2026-01-20'),
(5, 3, 2, '2026-01-21'),
(5, 5, 1, '2026-01-22');

Now, we have a basic e-commerce database containing customers, products, and purchase history.

Let’s start building the recommendation logic.

4. Build a Personalized Recommendation Using ROW_NUMBER()

One of the most useful window functions for recommendation systems is ROW_NUMBER().

It assigns a unique sequential number to each row within a specified partition.

Suppose we want to identify the most frequently purchased products by each customer.

We can calculate the total quantity purchased by every customer for each product and rank the products based on purchase quantity.

SQL Query

WITH customer_product_sales AS (
    SELECT
        o.customer_id,
        p.product_id,
        p.product_name,
        SUM(o.quantity) AS total_quantity
    FROM orders o
    JOIN products p
        ON o.product_id = p.product_id
    GROUP BY
        o.customer_id,
        p.product_id,
        p.product_name
),
ranked_products AS (
    SELECT
        customer_id,
        product_name,
        total_quantity,
        ROW_NUMBER() OVER (
            PARTITION BY customer_id
            ORDER BY total_quantity DESC, product_name
        ) AS product_rank
    FROM customer_product_sales
)
SELECT *
FROM ranked_products
WHERE product_rank <= 3;

How Does This Query Work?

Let’s understand the query step by step.

First: customer_product_sales

This CTE calculates how many units of each product each customer purchased.

Second: ROW_NUMBER()

The window function ranks products separately for every customer.

The PARTITION BY customer_id clause ensures that ranking starts again for each customer.

Third: ORDER BY

Products with higher purchase quantities receive better rankings.

**Finally: WHERE product_rank

This approach is useful when an application wants to understand individual customer purchasing preferences.

5. Recommend Popular Products Using DENSE_RANK()

Another common recommendation strategy is identifying popular products.

For example, an e-commerce platform may want to display the top-selling products to all customers.

We can use DENSE_RANK() to rank products based on their total sales quantity.

SQL Query

WITH product_sales AS (
    SELECT
        p.product_id,
        p.product_name,
        p.category,
        SUM(o.quantity) AS total_sold
    FROM orders o
    JOIN products p
        ON o.product_id = p.product_id
    GROUP BY
        p.product_id,
        p.product_name,
        p.category
)
SELECT
    product_name,
    category,
    total_sold,
    DENSE_RANK() OVER (
        ORDER BY total_sold DESC
    ) AS sales_rank
FROM product_sales;

Understanding DENSE_RANK()

The DENSE_RANK() function assigns the same rank to rows with equal values.

For example:

Product Total Sold Rank
Laptop 3 1
Mobile 3 1
Headphones 6 1
Keyboard 1 2

The actual rankings depend on the inserted sample data.

Unlike ROW_NUMBER(), DENSE_RANK() allows multiple products to share the same ranking.

This is useful when products have equal popularity and the recommendation system should consider them equally.

6. Recommend Products Based on Similar Customer Behavior

Now let’s explore a more interesting recommendation technique.

Suppose Rahul purchases a laptop and a mobile phone.

Priya also purchases a laptop and headphones.

The application can identify customers who purchased similar products and recommend products they purchased that Rahul has not purchased.

This is a simplified form of collaborative filtering.

Step 1: Identify Similar Customers

We can find customers who purchased at least one product in common with a target customer.

SELECT DISTINCT
    o1.customer_id AS target_customer,
    o2.customer_id AS similar_customer
FROM orders o1
JOIN orders o2
    ON o1.product_id = o2.product_id
WHERE o1.customer_id = 1
AND o2.customer_id <> 1;

This query identifies customers who purchased products also purchased by customer 1.

Step 2: Recommend Products Purchased by Similar Customers

Now we can identify products purchased by similar customers but not purchased by Rahul.

WITH similar_customers AS (
    SELECT DISTINCT
        o2.customer_id
    FROM orders o1
    JOIN orders o2
        ON o1.product_id = o2.product_id
    WHERE o1.customer_id = 1
      AND o2.customer_id <> 1
),
recommendations AS (
    SELECT
        o.customer_id,
        p.product_id,
        p.product_name,
        SUM(o.quantity) AS recommendation_score
    FROM orders o
    JOIN similar_customers sc
        ON o.customer_id = sc.customer_id
    JOIN products p
        ON o.product_id = p.product_id
    WHERE NOT EXISTS (
        SELECT 1
        FROM orders existing
        WHERE existing.customer_id = 1
          AND existing.product_id = o.product_id
    )
    GROUP BY
        o.customer_id,
        p.product_id,
        p.product_name
)
SELECT
    product_id,
    product_name,
    SUM(recommendation_score) AS total_score
FROM recommendations
GROUP BY product_id, product_name
ORDER BY total_score DESC;

What Is Happening Here?

  • First, we identify customers who share purchasing interests with Rahul.

  • Next, we collect products purchased by those customers.

  • Then, we exclude products Rahul has already purchased.

  • Finally, we calculate recommendation scores and sort products by popularity among similar customers.

This gives us a basic collaborative filtering recommendation model using SQL.

Important: This is a simplified similarity approach. A production recommendation engine would usually use stronger similarity calculations, such as Jaccard similarity or cosine similarity, and normalize scores to avoid favoring customers with large purchase histories.

7. Use LAG() to Analyze Customer Purchase Behavior

Understanding customer purchase patterns is another important part of recommendation systems.

The LAG() function allows us to access a value from a previous row without performing a self-join.

For example, we can identify the previous purchase date for every customer.

SQL Query

SELECT
    customer_id,
    order_id,
    order_date,
    LAG(order_date) OVER (
        PARTITION BY customer_id
        ORDER BY order_date
    ) AS previous_purchase_date
FROM orders;

Why Is This Useful?

With this query, we can analyze:

  • How frequently customers purchase products.

  • How much time passes between purchases.

  • Whether customers are purchasing more frequently.

  • When customers might be ready to purchase again.

We can also calculate the number of days between consecutive purchases.

SELECT
    customer_id,
    order_date,
    LAG(order_date) OVER (
        PARTITION BY customer_id
        ORDER BY order_date
    ) AS previous_purchase_date,
    order_date -
    LAG(order_date) OVER (
        PARTITION BY customer_id
        ORDER BY order_date
    ) AS days_between_purchases
FROM orders;

This information can support personalized notifications and product recommendations.

For example, an application may remind customers to reorder products they purchase regularly.

8. Use NTILE() to Segment Customers

Not every customer has the same purchasing behavior.

Some customers purchase frequently, while others make occasional purchases.

PostgreSQL provides the NTILE() window function to divide rows into approximately equal groups.

We can use this function to segment customers based on their total spending.

SQL Query

WITH customer_spending AS (
    SELECT
        c.customer_id,
        c.customer_name,
        SUM(o.quantity * p.price) AS total_spending
    FROM customers c
    JOIN orders o
        ON c.customer_id = o.customer_id
    JOIN products p
        ON o.product_id = p.product_id
    GROUP BY
        c.customer_id,
        c.customer_name
)
SELECT
    customer_id,
    customer_name,
    total_spending,
    NTILE(4) OVER (
        ORDER BY total_spending DESC
    ) AS customer_segment
FROM customer_spending;

Understanding the Results

NTILE(4) divides customers into four approximately equal groups.

For example:

Segment Customer Category
1 Highest spending
2 High spending
3 Moderate spending
4 Lower spending

This segmentation can help businesses create different recommendation strategies.

  • High-spending customers may receive premium product suggestions.

  • Moderate-spending customers may receive complementary product recommendations.

  • Lower-spending customers may receive affordable product suggestions.

Keep in mind that these are relative spending groups, not fixed customer-value thresholds.

9. Recommend Products Frequently Purchased Together

Another useful recommendation technique is product association analysis.

For example, customers who purchase laptops may also purchase keyboards, mice, and headphones.

This is commonly known as a market basket analysis approach.

We can identify products purchased together by comparing different products within the same order.

For this example, our existing orders table contains one product per order. Therefore, we will use customer-level co-purchase behavior as a simplified demonstration.

SQL Query

SELECT
    p1.product_name AS product_a,
    p2.product_name AS product_b,
    COUNT(DISTINCT o1.customer_id) AS customers_purchased_both
FROM orders o1
JOIN orders o2
    ON o1.customer_id = o2.customer_id
   AND o1.product_id < o2.product_id
JOIN products p1
    ON o1.product_id = p1.product_id
JOIN products p2
    ON o2.product_id = p2.product_id
GROUP BY
    p1.product_name,
    p2.product_name
ORDER BY customers_purchased_both DESC;

This query identifies product combinations purchased by the same customers.

For accurate market basket analysis, a real application should associate multiple products with the same transaction or shopping basket. The example above measures customer-level co-purchase, which may include purchases made on different dates.

10. Improve Recommendation Query Performance in PostgreSQL

As an application grows, the number of customers, products, and orders can increase significantly.

Recommendation queries may become expensive when they process millions of records.

Database performance optimization is therefore essential.

Here are some practical ways to improve query performance.

1. Create Appropriate Indexes

Indexes can help PostgreSQL retrieve relevant records efficiently.

CREATE INDEX idx_orders_customer
ON orders(customer_id);

CREATE INDEX idx_orders_product
ON orders(product_id);

CREATE INDEX idx_orders_customer_product
ON orders(customer_id, product_id);

The composite index can be particularly useful for queries filtering by both customer and product.

However, indexes should be designed based on actual query patterns. Too many indexes can increase storage requirements and slow down INSERT, UPDATE, and DELETE operations.

2. Use EXPLAIN ANALYZE

PostgreSQL provides EXPLAIN ANALYZE to examine how a query executes.

EXPLAIN ANALYZE
SELECT
    customer_id,
    product_id,
    SUM(quantity)
FROM orders
GROUP BY customer_id, product_id;

It helps database developers understand:

  • Sequential scans.

  • Index scans.

  • Execution time.

  • Join operations.

  • Sort operations.

  • Estimated versus actual row counts.

This information helps identify performance bottlenecks in recommendation queries.

3. Avoid Unnecessary Sorting

Window functions often require sorting data based on the PARTITION BY and ORDER BY clauses.

For large datasets, sorting can consume significant memory and processing resources.

Use appropriate indexes, filter unnecessary records early, and avoid calculating rankings for data that is not required.

4. Use Materialized Views for Repeated Calculations

If recommendation queries involve expensive aggregations, materialized views can help reduce repeated calculations.

For example:

CREATE MATERIALIZED VIEW product_sales_summary AS
SELECT
    product_id,
    SUM(quantity) AS total_sold
FROM orders
GROUP BY product_id;

Refresh the materialized view when updated results are needed:

REFRESH MATERIALIZED VIEW product_sales_summary;

This can improve read performance for frequently accessed recommendation data, although the view must be refreshed to reflect changes in the underlying tables.

11. Real-World Applications of PostgreSQL Recommendation Systems

SQL-based recommendation systems can support many different business applications.

Personalization in eCommerce: A 2026 practical guide

E-Commerce Applications

Recommend products based on customer purchases, browsing history, and popular product combinations.

Online Learning Platforms

Suggest courses based on previously completed courses, learning interests, and student activity.

Streaming Platforms

Identify popular content and recommend videos based on viewing history.

Banking and Financial Applications

Analyze customer transaction patterns to identify relevant financial products and services.

Retail Applications

Identify frequently purchased products and generate cross-selling recommendations.

12. Best Practices for Building Recommendation Systems in PostgreSQL

When implementing recommendation logic in a real production environment, keep the following practices in mind:

1. Understand your data: Analyze customer behavior and product interactions before designing recommendation queries.

2. Use the correct window function: Choose between ROW_NUMBER(), RANK(), and DENSE_RANK() based on your ranking requirements.

3. Optimize SQL queries: Use appropriate indexes and analyze execution plans.

4. Avoid recommending purchased products: Exclude products that customers have already purchased when generating new-product suggestions.

5. Consider recommendation freshness: Customer interests change over time, so recent activity should often receive more importance.

6. Handle insufficient data: New users and new products may have limited interaction history. Popularity-based recommendations can help address this cold-start problem.

7. Monitor query performance: Use PostgreSQL monitoring tools and query analysis techniques to identify slow recommendation queries.

8. Use machine learning when needed: For complex recommendations involving millions of users and products, combine SQL-based processing with machine learning models.

13. Conclusion

Building a recommendation system does not always require complex machine learning algorithms or external technologies. PostgreSQL provides powerful SQL capabilities that can help developers analyze customer behavior, identify purchasing patterns, rank products, and generate personalized recommendations.

By using window functions such as ROW_NUMBER(), DENSE_RANK(), LAG(), and NTILE(), developers can implement useful recommendation logic directly within the database.

We also explored how collaborative filtering concepts, product association analysis, indexing, EXPLAIN ANALYZE, and materialized views can support recommendation system development.

For PostgreSQL DBAs and developers, understanding these advanced SQL techniques is valuable because real-world database applications require more than simply storing and retrieving records. They also require efficient data analysis and meaningful insights.

The key takeaway: PostgreSQL Window Functions can transform ordinary purchase records into valuable business insights and intelligent product recommendations.

Learn PostgreSQL with Learnomate Technologies

Want to improve your PostgreSQL skills and work on practical database administration scenarios?

Learnomate Technologies provides learning opportunities for aspiring PostgreSQL DBAs and database professionals through practical training, hands-on exercises, and real-world database concepts.

Explore PostgreSQL concepts, SQL performance tuning, database administration, backup and recovery, indexing, and advanced query optimization to strengthen your technical expertise.

lets talk - learnomate helpdesk

Book a Free Demo

lets talk - learnomate helpdesk

Book a Free Demo