Choosing Rows, Columns, and Order

Single-table queries in SQL let you turn one stored table into a focused result, such as an inventory list or a rental report. A single-table query retrieves information from one table without combining it with another. You use SQL to state which columns you want, which rows qualify, and how the result should be ordered. The retrieval statements here leave the stored data unchanged.

Choose the returned columns

The basic statement names output columns after SELECT and the source table after FROM. Optional WHERE and ORDER BY clauses add filtering and sorting.


SQL
SELECT item_id, price
FROM inventory
WHERE stock > 0
ORDER BY price ASC, item_id ASC;


This statement returns two columns from inventory: item_id and price. It uses stock to decide which rows qualify, even though stock is absent from the output. The order of expressions after SELECT determines the order of output columns.


SELECT * requests every column. Naming columns explicitly makes the intended output clearer and avoids returning unrelated information. An expression can also calculate an output value: SELECT item_id, price * stock AS inventory_value FROM inventory; returns each item's total inventory value. Here, AS assigns an output label; it does not rename a stored column. If price is in dollars per item and stock is an item count, the calculated value is in dollars.

Keep qualifying rows

A predicate is a condition tested for each source row. The WHERE clause retains rows according to this governing rule:


A row is retained  ⟺  its WHERE condition evaluates to TRUE.\text{A row is retained} \iff \text{its WHERE condition evaluates to TRUE}.


Comparisons include =, <>, <, <=, >, and >=. Write text values in single quotes, as in category = 'Camera'. Numeric values generally appear without quotes. Boundary wording matters: at most 20 includes 20, whereas less than 20 excludes it.


Condition

Rows retained

price < 20

Rows priced below 20

price <= 20

Rows priced at or below 20

stock > 0 AND price <= 20

Rows satisfying both comparisons

stock > 0 OR price <= 20

Rows satisfying at least one comparison


AND combines requirements that must both hold. OR allows either requirement, including cases where both hold. SQL evaluates AND before OR, so use parentheses to express the intended grouping clearly. For example, (category = 'Camera' OR category = 'Audio') AND stock > 0 requires positive stock for either category.



A comparison involving NULL normally produces UNKNOWN. WHERE retains only true conditions, so false and unknown outcomes are both excluded.

Control result order

ORDER BY price ASC sorts prices from lowest to highest; DESC reverses that direction. Ascending order is the default when a direction is omitted. Each direction applies to its own expression.


For ORDER BY price DESC, item_id ASC, first compare prices. Only when prices tie do you compare item identifiers. If those identifiers are unique, they resolve every remaining tie. Without ORDER BY, SQL does not guarantee a particular row order, even if repeated runs appear consistent.


Four connected boxes show the roles of FROM, WHERE, SELECT, and ORDER BY in reasoning about a query.



What to remember

  • SELECT chooses output columns and expressions; FROM identifies the source table.
  • WHERE retains rows whose condition is true; parentheses clarify combined conditions.
  • IS NULL tests for missing values.
  • ORDER BY controls row order, with later expressions resolving earlier ties.

Example: Preparing an Equipment Rental List

An equipment desk stores the following complete data in rentals. Each identifier is unique. Daily rates are in USD per day, and available = 1 means the item can be rented today.


rental_id

category

daily_rate

available

101

Camera

42

1

102

Camera

35

1

103

Camera

50

0

104

Audio

28

1

105

Camera

42

1

106

Camera

30

1


The desk needs available cameras costing at most 42 USD per day. It wants the highest daily rate first, with smaller identifiers first when rates tie.


A calculated column is an output column produced by an expression rather than copied directly from one stored column. You will also calculate a discounted rate without changing the stored rates.


Example: Prepare the rental list and evaluate a promotional rate using the same source table.


a) Which rental identifiers satisfy all three filtering requirements, and how many rows qualify?


First test category = 'Camera'. There are ________ camera rows; rental 104 fails this requirement because it is audio equipment.


Next test available = 1. Rental ________ is unavailable, so it cannot appear in today's list. The remaining cameras have daily rates of 42, 35, 42, and 30 USD per day, each satisfying daily_rate <= 42.


The filtering clause is WHERE category = 'Camera' AND available = 1 AND daily_rate <= 42.


The qualifying identifiers are 101, 102, 105, and 106, giving 4 rows. Equality is included because the request says at most 42 USD per day.


b) Write the query returning rental_id and daily_rate in the requested order, and state the ordered identifiers.


Use SELECT rental_id, daily_rate FROM rentals to choose the two output columns and their source. Append the filtering clause from part a.


The highest retained daily rate is ________, shared by rentals 101 and 105. The identifier rule places rental ________ before rental 105. The remaining rates are 35 and 30 USD per day.


Apply the identifier order only within a daily-rate tie. The complete query is SELECT rental_id, daily_rate FROM rentals WHERE category = 'Camera' AND available = 1 AND daily_rate <= 42 ORDER BY daily_rate DESC, rental_id ASC;.


The ordered identifiers are 101, 105, 102, 106, with daily rates 42, 42, 35, 30 USD per day, respectively.


c) A promotion reduces every qualifying daily rate by 10%. Give the output expression named discounted_rate and calculate its value for rental 101, to two decimal places in USD per day.


A 10% reduction leaves the multiplier ________, since the customer pays 100% minus 10% of the original rate. Rental 101 has an original rate of ________.


The calculated output expression is daily_rate * 0.90 AS discounted_rate. For rental 101:


discounted rate=original rate×(1−discount fraction)=(42 USD/day)(1−0.10)=(42 USD/day)(0.90)=37.80 USD/day.\begin{aligned} \text{discounted rate} &= \text{original rate}\times(1-\text{discount fraction})\\ &= (42\ \text{USD/day})(1-0.10)\\ &= (42\ \text{USD/day})(0.90)\\ &= 37.80\ \text{USD/day}. \end{aligned}


The output expression is daily_rate * 0.90 AS discounted_rate, and rental 101's discounted rate is 37.80 USD per day. This expression calculates a result value; the stored daily rate remains 42 USD per day.

A campus shop stores product_id, product_name, price, and stock in products. Which query returns only product names and prices for products with positive stock?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A warehouse stores uppercase product codes in the products table. You need every code beginning with LAB, including LAB itself, LAB7, and LABKIT. Complete the SQL predicate by entering the four-letter standard SQL wildcard operator between the column name and the supplied pattern.


product_code 'LAB%'

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A streaming service stores video_id, genre, duration_minutes, and available in videos. The value available = 1 means a video can currently be watched. Return available videos that are documentaries, shorter than 80 minutes, or both.


The statement begins with SELECT video_id FROM videos. Complete its filtering condition using the two missing logical operators:


WHERE (genre = 'Documentary' duration_minutes < 80) available = 1;

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice