bhylu.com

Advertisements

SQL Min()

MIN finds the smallest non-NULL input value. It is useful for a lowest price or earliest date, but it does not automatically return the whole row that supplied that value.

Understand the idea

The first SELECT returns the lowest price. The second finds every product at that price using a scalar subquery. This preserves ties rather than guessing one product name next to an aggregate. A subquery is a query inside another query; here it supplies one value that the outer comparison can use.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

SELECT MIN(price_cents) AS lowest_cents FROM products;

SELECT name, price_cents
FROM products
WHERE price_cents = (SELECT MIN(price_cents) FROM products)
ORDER BY product_id;

Read the result

The minimum is 250 cents, and Pocket notebook has that price. If another product had the same price, the second result would include both products.

Try one change

Use MIN(ordered_at) to find the earliest sample order date. The dates are consistently stored in ISO year-month-day form.