Single answer

Some orders have no discount, stored as NULL. Run this script in psql. Which three values does the final SELECT return?

CREATE TEMP TABLE orders (id int, discount numeric);
INSERT INTO orders VALUES (1, 10), (2, NULL), (3, 20), (4, NULL);
SELECT COUNT(*), COUNT(discount), AVG(discount) FROM orders;
Single answer

A support desk counts the tickets that are not closed. One ticket has no status yet. What does the query return?

CREATE TEMP TABLE tickets (id int, status text);
INSERT INTO tickets VALUES (1, 'open'), (2, 'closed'), (3, NULL), (4, 'open');
SELECT COUNT(*) FROM tickets WHERE status <> 'closed';
Single answer

A shop excludes banned customers with NOT IN. The banned list contains a NULL left by a bad import. What does the query return?

CREATE TEMP TABLE customers (id int);
CREATE TEMP TABLE banned (customer_id int);
INSERT INTO customers VALUES (1), (2), (3);
INSERT INTO banned VALUES (2), (NULL);
SELECT COUNT(*) FROM customers WHERE id NOT IN (SELECT customer_id FROM banned);
Single answer

A report sums refunds from a table that has no rows yet. Which three values does the query return?

CREATE TEMP TABLE refunds (amount numeric);
SELECT SUM(amount), COALESCE(SUM(amount), 0), COUNT(amount) FROM refunds;
Single answer

Some employees have no department yet. What does this query return?

CREATE TEMP TABLE staff (name text, dept text);
INSERT INTO staff VALUES ('Ana', 'IT'), ('Dan', NULL), ('Eva', NULL), ('Ion', 'IT'), ('Mia', 'HR');
SELECT dept, COUNT(*) FROM staff GROUP BY dept ORDER BY dept NULLS LAST;
Single answer

True or false: in PostgreSQL, SELECT NULL IS DISTINCT FROM NULL; returns false.

Single answer

What does this query return for the three columns a, b and c?

SELECT (NULL AND FALSE) AS a, (NULL OR TRUE) AS b, (NULL AND TRUE) AS c;
Single answer

A blog lists every author with the number of published posts, using a LEFT JOIN so authors without posts appear too. What does the query return?

CREATE TEMP TABLE authors (id int, name text);
CREATE TEMP TABLE posts (author_id int, published boolean);
INSERT INTO authors VALUES (1, 'Ana'), (2, 'Dan'), (3, 'Eva');
INSERT INTO posts VALUES (1, true), (1, false), (2, false);
SELECT a.name, COUNT(p.author_id)
FROM authors a
LEFT JOIN posts p ON p.author_id = a.id
WHERE p.published = true
GROUP BY a.name
ORDER BY a.name;
Multiple answers

A ratings table has two scores and two NULLs. Which of these aggregates ignore the NULL values in the column? Select all that apply.

CREATE TEMP TABLE ratings (score int);
INSERT INTO ratings VALUES (4), (NULL), (2), (NULL);
SELECT COUNT(*), COUNT(score), AVG(score), MAX(score) FROM ratings;
Single answer

A race result table has a runner who did not finish, stored with NULL seconds. In which order does PostgreSQL return the runners?

CREATE TEMP TABLE runs (runner text, seconds int);
INSERT INTO runs VALUES ('Ana', 310), ('Dan', NULL), ('Eva', 295);
SELECT runner FROM runs ORDER BY seconds;