28. Sequence Products by Price
Beginner Mode
Objective
Given a table named products, you need to compute a new column named neighbor_product. This column should contain the product of the prices of the immediate previous and next products based on the ascending order of prices. If there is no previous or next product, treat the missing price as 0.
Write a SQL query to achieve this. Your query should return the product name, price, and the calculated neighbor_product for each product, ordered by price in ascending order.
Additional information
The products table:
| Column | Type | Description |
|---|---|---|
| id | integer | A unique identifier for each product |
| product_name | string | The name of the product |
| price | integer | The price of the product |
- Constraints:
- Each product will have a unique price.
- There will be at least one product in the table.
- Special remarks:
- Use SQL window functions to access the previous and next prices in the sorted list.
- Consider using
COALESCEto handle cases where the previous or next price is missing.
Examples
Example 1:
Output:
Input:
| products | ||
|---|---|---|
| id | price | product_name |
| 1 | 1200 | Laptop |
| 2 | 800 | Smartphone |
| 3 | 300 | Headphones |
| 4 | 500 | Tablet |
| 5 | 400 | Smartwatch |
| neighbor_product | price | product_name |
|---|---|---|
| 0 | 300 | Headphones |
| 150000 | 400 | Smartwatch |
| 320000 | 500 | Tablet |
| 600000 | 800 | Smartphone |
| 0 | 1200 | Laptop |
Code Environment
Sign in or try as guest to run your code.
Essential
SQL 0/33
Spark 0/20
Snowflake 0/22
Python 0/24
Need more practice in this area? Explore more questions →
GoDaddy
Revolut
Accenture
Adobe
Google
LinkedIn
Samsung
Datadog
Wix
Dropbox
Meta
OpenAI
Hulu
Uber
X
DoorDash
Anthropic
Amazon
ActivisionBlizzard
Vercel
Crypto.Com
Zscaler
DeutscheBank
Apple
GitLab
BMW
PayPal
Snowflake
AMD
Twilio
Atlassian
JPMorgan
NVIDIA
IBM
Databricks
Coinbase
Cisco
Robinhood
Twitter
Microsoft
Palantir
Netflix
VMware
Cloudflare
Stripe
Lyft
Salesforce
GitHub
Bloomberg
Airbnb
Walmart
SAP
HashiCorp
Instacart
Mastercard
Intel
Visa
Tesla