Interview Questions/SQL/Order Gaps - Products with Inactivity Exceeding 7 Days

Order Gaps - Products with Inactivity Exceeding 7 Days

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a table of product orders. Each row records a product and the date an order was placed. Write a SQL query to find all consecutive order pairs for each product where the gap between them is strictly greater than 7 days. For each such gap return the product_id, the date of the order before the gap (gap_start), the date of the order after the gap (gap_end), and the gap length in days (gap_days). Return results ordered by product_id then gap_start. Table: ProductOrders

Column NameTypeDescription
idINTPrimary key
product_idINTProduct identifier
order_dateDATEDate the order was placed

Database Schema (Inferred)

ProductOrders

Column NameExample Value
id1
product_id101
order_date2023-01-01

Example

ProductOrders

idproduct_idorder_date
11012023-01-01
21012023-01-05
31012023-01-20
41012023-01-22
52022023-02-01
62022023-02-03
73032023-03-01
83032023-03-15
93032023-03-16

Output

product_idgap_startgap_endgap_days
1012023-01-052023-01-2015
3032023-03-012023-03-1514

Explanation:

Use LAG() to get the previous order date per product, compute the day difference, then filter for gaps > 7. Product 202 only has a 2-day gap so it is excluded.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

ProductOrders

idproduct_idorder_date
11012023-01-01
21012023-01-05
31012023-01-20
41012023-01-22
52022023-02-01
62022023-02-03
73032023-03-01
83032023-03-15
93032023-03-16

Output

product_idgap_startgap_endgap_days
1012023-01-052023-01-2015
3032023-03-012023-03-1514