High-Value Electronics

An easy SQL interview practice problem on DataDriven. Write the query and run it against a real database, with instant feedback.

Domain
SQL
Difficulty
easy
Seniority
L3

Problem

In products, plenty of electronics are listed that are not currently on hand. Of the electronics that are in stock, show the name and price of the five most expensive, highest price first.

The five priciest electronics.

Tables

products

Columns: product_id INTEGER, product_name TEXT, category TEXT, price REAL, rating REAL, in_stock INTEGER

products: 10 of 200 rows
product_idproduct_namecategorypriceratingin_stock
1001Basic Device 1XBooks17.522.71
1050Deluxe Bundle 2XClothing25.054.41
1099Pro Unit 3XHome & Kitchen32.582.11
1148Ultra Tool 4XCollectibles40.113.81
1197Essential Set 5XToys47.641.51
1246Classic System 6XBeauty03.21
1295Smart Gadget 7XAutomotive62.74.90
1344Eco Kit 8XGarden70.232.61
1393Turbo Pack 9XMusic77.764.30
1442Premium Widget 10XElectronics85.2921

Expected output

First 5 of 5 rows
product_nameprice
Basic Set v1001859.72
Basic Set v801674.32
Basic Set v701581.62
Basic Set v601488.92
Basic Set v501396.22

Worked solution and explanation

What this really is

This is a two-condition filter followed by a sorted cut, wearing a shopping costume. Everyone gets the category right. What separates candidates is whether 'in stock' registers as a requirement or slides past as scenery. On this seed some of the most expensive electronics are not on hand, so a query that filters on category alone gives one of them a top-five spot and quietly drops a real on-hand item off the bottom.

Step 1: Keep only rows that pass both conditions

Put category = 'Electronics' and in_stock = 1 in the same WHERE, joined with AND. Both must hold for a row to survive. An OR here would pull in every in-stock book and every out-of-stock gadget.

Step 2: Sort by price from highest down

ORDER BY price DESC puts the costliest survivors first. The prompt asks for the most expensive, and the preview reads top to bottom from the highest price, so the direction is not optional.

Step 3: Cut at five, after the sort

LIMIT 5 runs after the sort, so it keeps the top five rather than whichever five the scan reached first. Project only product_name and price: the preview shows two columns, and a SELECT * returns six.

On-hand electronics, priciest five
SELECT product_name, price
FROM products
WHERE category = 'Electronics'
  AND in_stock = 1
ORDER BY price DESC
LIMIT 5
Category only
WHERE category = 'Electronics' with the same sort and cap. Looks right, runs clean, and lets an out-of-stock item take a slot near the top.
Category and stock
WHERE category = 'Electronics' AND in_stock = 1. The out-of-stock item is gone before the sort, so all five slots go to items that can actually be stocked.

Common follow-up questions