0
0
PostgreSQLquery~5 mins

Scalar subqueries in PostgreSQL - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a scalar subquery in SQL?
A scalar subquery is a subquery that returns exactly one value (one row and one column). It can be used wherever a single value is expected, like in SELECT, WHERE, or SET clauses.
Click to reveal answer
beginner
Can a scalar subquery return multiple rows or columns?
No. A scalar subquery must return exactly one row and one column. Returning more than one row or column causes an error.
Click to reveal answer
intermediate
How do scalar subqueries differ from regular subqueries?
Scalar subqueries return a single value, while regular subqueries can return multiple rows and columns. Scalar subqueries are often used as expressions in SQL statements.
Click to reveal answer
intermediate
Example: What does this scalar subquery do?<br>
SELECT name, (SELECT MAX(score) FROM exams WHERE exams.student_id = students.id) AS max_score FROM students;
This query lists each student's name and their highest exam score. The scalar subquery finds the maximum score for each student by matching student IDs.
Click to reveal answer
beginner
Where can scalar subqueries be used in SQL statements?
Scalar subqueries can be used in SELECT lists, WHERE clauses, HAVING clauses, and SET clauses, anywhere a single value is expected.
Click to reveal answer
What does a scalar subquery return?
AMultiple rows and columns
BExactly one value (one row, one column)
COnly multiple rows
DOnly multiple columns
Which SQL clause can contain a scalar subquery?
ACREATE TABLE
BFROM clause
CSELECT list
DALTER TABLE
What happens if a scalar subquery returns more than one row?
AAn error occurs
BThe extra rows are ignored
COnly the first row is used
DThe query runs normally
In this query, what is the role of the scalar subquery?<br>
SELECT product_name, (SELECT AVG(price) FROM products) AS avg_price FROM products;
ACalculate average price once for all rows
BCalculate average price per product
CReturn multiple prices
DFilter products by price
Which of these is a valid use of a scalar subquery?
AINSERT INTO products VALUES (SELECT * FROM old_products)
BFROM (SELECT * FROM products)
CSELECT * FROM (SELECT * FROM products)
DWHERE price > (SELECT MAX(price) FROM products)
Explain what a scalar subquery is and give an example of where you might use it.
Think about a subquery that returns a single number or value to use in a condition or calculation.
You got /3 concepts.
    What error occurs if a scalar subquery returns more than one row? How can you avoid this?
    Consider how to limit the subquery result to a single value.
    You got /3 concepts.