Bird
Raised Fist0
PostgreSQLquery~30 mins

SELECT with PostgreSQL-specific features - Mini Project: Build & Apply

Choose your learning style10 modes available
Using PostgreSQL-Specific SELECT Features
📖 Scenario: You are managing a small bookstore database. You want to practice using PostgreSQL-specific features in SELECT queries to get useful information about books and authors.
🎯 Goal: Build a series of PostgreSQL SELECT queries that use PostgreSQL-specific features like RETURNING, FILTER, and DISTINCT ON to retrieve and manipulate bookstore data.
📋 What You'll Learn
Create a table called books with columns id, title, author, price, and published_year.
Insert sample data into the books table.
Write a SELECT query using DISTINCT ON to get the first book by each author ordered by published year.
Write a SELECT query using FILTER to count books published after 2010.
Write an INSERT statement using RETURNING to add a new book and get its details.
💡 Why This Matters
🌍 Real World
Bookstores and many other businesses use PostgreSQL to store and query their data efficiently. Using PostgreSQL-specific features helps write simpler and more powerful queries.
💼 Career
Knowing PostgreSQL-specific SELECT features is valuable for database developers and analysts working with PostgreSQL databases to optimize queries and handle complex data retrieval.
Progress0 / 4 steps
1
Create the books table and insert sample data
Create a table called books with columns id as serial primary key, title as text, author as text, price as numeric, and published_year as integer. Then insert these exact rows into books: (1, 'The Alchemist', 'Paulo Coelho', 10.99, 1988), (2, 'Brida', 'Paulo Coelho', 12.50, 1990), (3, '1984', 'George Orwell', 15.00, 1949), (4, 'Animal Farm', 'George Orwell', 9.99, 1945), (5, 'Clean Code', 'Robert C. Martin', 33.99, 2008).
PostgreSQL
Hint

Use CREATE TABLE with the specified columns and types. Use INSERT INTO books with the exact rows.

2
Set up a variable for the year threshold
Create a variable called year_threshold and set it to 2010. This will be used to filter books published after this year.
PostgreSQL
Hint

Use the PostgreSQL psql command \set to create a variable.

3
Select the first book by each author using DISTINCT ON
Write a SELECT query that uses DISTINCT ON (author) to get the first book by each author ordered by published_year ascending. Select author, title, and published_year.
PostgreSQL
Hint

Use DISTINCT ON (author) and order by author and published_year ascending.

4
Count books published after 2010 using FILTER and insert a new book with RETURNING
Write a SELECT query that counts how many books have published_year greater than the variable :year_threshold using COUNT(*) FILTER (WHERE published_year > :year_threshold). Then write an INSERT statement to add a new book with title 'The Pragmatic Programmer', author 'Andrew Hunt', price 42.00, and published_year 1999, and use RETURNING * to get the inserted row details.
PostgreSQL
Hint

Use COUNT(*) FILTER (WHERE ...) to count conditionally. Use INSERT INTO ... RETURNING * to insert and get the new row.

Practice

(1/5)
1. What does the LIMIT clause do in a PostgreSQL SELECT query?
easy
A. It combines rows from two tables.
B. It restricts the number of rows returned by the query.
C. It removes duplicate rows from the result.
D. It sorts the rows in ascending order.

Solution

  1. Step 1: Understand the purpose of LIMIT

    The LIMIT clause is used to specify the maximum number of rows to return from a query result.
  2. Step 2: Compare with other options

    Sorting is done by ORDER BY, removing duplicates by DISTINCT, and combining tables by JOIN, so these are not correct.
  3. Final Answer:

    It restricts the number of rows returned by the query. -> Option B
  4. Quick Check:

    LIMIT = restrict rows [OK]
Hint: LIMIT caps rows returned, like a page size [OK]
Common Mistakes:
  • Confusing LIMIT with ORDER BY
  • Thinking LIMIT removes duplicates
  • Mixing LIMIT with JOIN functionality
2. Which of the following is the correct syntax to select distinct city names from a table called customers?
easy
A. SELECT city FROM DISTINCT customers;
B. SELECT city DISTINCT FROM customers;
C. SELECT DISTINCT city FROM customers;
D. SELECT city FROM customers DISTINCT;

Solution

  1. Step 1: Recall correct DISTINCT syntax

    In PostgreSQL, DISTINCT comes immediately after SELECT and before the column list.
  2. Step 2: Validate each option

    SELECT DISTINCT city FROM customers; correctly places DISTINCT after SELECT. Options A, B, and D misuse DISTINCT placement causing syntax errors.
  3. Final Answer:

    SELECT DISTINCT city FROM customers; -> Option C
  4. Quick Check:

    SELECT DISTINCT = correct syntax [OK]
Hint: DISTINCT always follows SELECT keyword [OK]
Common Mistakes:
  • Placing DISTINCT after column names
  • Using DISTINCT after FROM clause
  • Misordering keywords causing syntax errors
3. Given the table products with columns id, name, and price, what will this query return?
SELECT name FROM products ORDER BY price DESC LIMIT 2;
medium
A. The two products with the lowest prices.
B. An error because LIMIT cannot be used with ORDER BY.
C. All products sorted by price descending.
D. The two products with the highest prices.

Solution

  1. Step 1: Understand ORDER BY with DESC

    ORDER BY price DESC sorts products from highest to lowest price.
  2. Step 2: Apply LIMIT 2

    LIMIT 2 restricts the output to only the first two rows after sorting, so the two most expensive products.
  3. Final Answer:

    The two products with the highest prices. -> Option D
  4. Quick Check:

    ORDER BY DESC + LIMIT = top rows [OK]
Hint: ORDER BY DESC + LIMIT picks top items [OK]
Common Mistakes:
  • Thinking LIMIT returns lowest prices
  • Believing LIMIT causes syntax error with ORDER BY
  • Ignoring DESC means descending order
4. Identify the error in this PostgreSQL query:
SELECT DISTINCT name, price FROM products LIMIT;
medium
A. LIMIT requires a number to specify how many rows to return.
B. DISTINCT cannot be used with multiple columns.
C. SELECT must include WHERE clause when using LIMIT.
D. The table name is missing.

Solution

  1. Step 1: Check LIMIT usage

    LIMIT must be followed by a number indicating how many rows to return; here it is missing.
  2. Step 2: Validate other parts

    DISTINCT can be used with multiple columns, WHERE is optional, and table name is present as products.
  3. Final Answer:

    LIMIT requires a number to specify how many rows to return. -> Option A
  4. Quick Check:

    LIMIT needs a number [OK]
Hint: Always put a number after LIMIT [OK]
Common Mistakes:
  • Omitting number after LIMIT
  • Thinking DISTINCT can't use multiple columns
  • Assuming WHERE is mandatory with LIMIT
5. You want to get the third and fourth highest salaries from the employees table with column salary. Which query correctly achieves this in PostgreSQL?
hard
A. SELECT salary FROM employees ORDER BY salary DESC LIMIT 2 OFFSET 2;
B. SELECT salary FROM employees ORDER BY salary ASC LIMIT 2 OFFSET 3;
C. SELECT DISTINCT salary FROM employees LIMIT 2 OFFSET 3 ORDER BY salary DESC;
D. SELECT salary FROM employees LIMIT 2 OFFSET 2 ORDER BY salary DESC;

Solution

  1. Step 1: Understand OFFSET and LIMIT

    OFFSET 2 skips the first two highest salaries, LIMIT 2 returns the next two rows.
  2. Step 2: Check ORDER BY direction

    ORDER BY salary DESC sorts salaries from highest to lowest, so OFFSET 2 skips top two highest.
  3. Step 3: Validate options

    SELECT salary FROM employees ORDER BY salary DESC LIMIT 2 OFFSET 2; correctly orders DESC, uses LIMIT 2 and OFFSET 2. SELECT salary FROM employees ORDER BY salary ASC LIMIT 2 OFFSET 3; orders ASC (wrong direction), C misplaces ORDER BY, D places ORDER BY after LIMIT (syntax error).
  4. Final Answer:

    SELECT salary FROM employees ORDER BY salary DESC LIMIT 2 OFFSET 2; -> Option A
  5. Quick Check:

    OFFSET skips rows, LIMIT picks next [OK]
Hint: Use OFFSET to skip, LIMIT to pick rows [OK]
Common Mistakes:
  • Using ASC instead of DESC for highest values
  • Placing ORDER BY after LIMIT
  • Confusing OFFSET number with row count
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard