Subqueries Flashcards

1
Q

Show the ‘department’ column from both the employees table and the departments table

A
SELECT d.department, e.department
FROM employees AS e, departments AS d
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

T/F: You can only specify tables in a FROM clause

A

False, you can nest other subqueries in place of a table, e.g:
~~~
SELECT department
FROM (SELECT * FROM my_table)
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why does this fail?:
~~~
SELECT *
FROM (SELECT * FROM employees WHERE salary > 150000)
~~~

A

Because in PostgreSQL, you need to provide an alias to the source query. To fix it, do this:
~~~
SELECT *
FROM (SELECT * FROM employees WHERE salary > 150000) AS my_table
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

T/F: When creating a subquery in a WHERE clause, you need to provide an alias

A

False, unlike subqueries in FROM clauses, you don’t provide an alias (it will fail if you do)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What will be returned from this query?
~~~
SELECT first_name, last_name, (SELECT first_name FROM employees LIMIT 1)
FROM employees
~~~

A

SELECT first_name FROM employees returns the first_name column, so LIMIT 1 will return only the first value of this column. So, the end result is a table of first names, last names, AND the first of the first name column repeated for each row.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does this WHERE clause check for?
~~~
WHERE region_id > ANY (
SELECT region_id FROM regions WHERE country = ‘United States’
)
~~~

A

It checks if region_id is greater than ANY of the returned values from the subquery

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does this WHERE clause check for?
~~~
WHERE region_id > ALL (
SELECT region_id FROM regions WHERE country = ‘United States’
)
~~~

A

It checks if region_id is greater than ALL of the returned values from the subquery

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

T/F: Subqueries execute before the outer query

A

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

T/F: If a subquery within a WHERE clause returns null, the outer query will also return a null value

A

False, the outer query won’t return any row

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a scalar subquery?

A

A subquery that only returns one value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What does this WHERE clause check for?
~~~
WHERE EXISTS (
SELECT region_id FROM regions WHERE country = ‘United States’
)
~~~

A

It checks if any values are returned from the inner query

How well did you know this?
1
Not at all
2
3
4
5
Perfectly