First Impressions

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
Asked in
Oracle

Problem

Only the first three characters of a product's name fit in the compact listing's label slot. From the products table, return each product's ID alongside that three-character prefix, in product ID order.

Just the first three characters. That is all.

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 200 rows
product_idname_prefix
1001Bas
1050Del
1099Pro
1148Ult
1197Ess

Worked solution and explanation

What this really tests

Let's be honest: there is no algorithmic trap here. This is a one-line string extraction wearing a product-analytics costume, and anyone who knows SUBSTR can write it. What an interviewer actually clocks on a warm-up like this is whether you get the argument order right on the first pass and whether you remember that SQL string indexing starts at 1, not 0. Reach for a zero or a two as the start position and you hand back the wrong characters; drop product_id from the SELECT and the shape is wrong. On an easy question, a clean first attempt is the entire signal.


Break it down

Step 1: Extract the first three characters

SUBSTR(product_name, 1, 3) takes three characters starting at position 1. The 1 is the part people fluff: SQL is 1-indexed, so 1 gives you the first character, not the second. Alias it to name_prefix so the output column matches what was asked.

Step 2: Order by product_id

ORDER BY product_id returns the rows in ascending ID order. It is the only ordering requirement, and forgetting it leaves the row order at the engine's discretion, which will not match the expected output.


The solution

Product ID with its three-character name prefix
SELECT product_id, SUBSTR(product_name, 1, 3) AS name_prefix
FROM products
ORDER BY product_id

Common follow-up questions