Skip to main content
April 2, 2026Dan Rodney/9 min read

Coding Exercise in PostgreSQL

Master PostgreSQL Query Writing Through Interactive Practice

Live Coding Exercise Structure

This session combines demonstration with hands-on practice. You'll observe the coding process, then complete exercises to reinforce your understanding.

Setting Up Your PostgreSQL Environment

1

Open Exercise File

Navigate to the numbered class files and select the appropriate exercise file (starting with 1.1.0)

2

Connect to Database

Click the database platter icon and select your server to establish an active connection

3

Verify Connection

Confirm code hinting appears and no 'active connection' errors occur when running queries

Database Connection Safety Protocol

DBeaver requires manual server selection for each new file as a safeguard. This prevents accidental connections to wrong servers, ensuring query accuracy over speed.

Core SELECT Statement Components

Column Selection

Choose specific columns or use asterisk for all. Order matters and determines result set layout.

Table Reference

FROM clause specifies the source table. Use database browser to view available tables and columns.

Result Set Control

The output is a custom result set, not a direct database view. You control column order and repetition.

Column Selection Methods

FeatureAsterisk (*)Specific Columns
SyntaxSELECT *SELECT title, price
FlexibilityShows all columnsCustom selection
PerformancePotentially slowerOptimized
ReadabilityQuick overviewClear intent
Recommended: Use specific columns for production queries, asterisk for exploration

Column Position vs Name Ordering

Pros
Position numbers (1, 2, 3) are faster to type
Useful for quick ad-hoc queries
Common in legacy code
Cons
Breaks when column order changes
Less readable and maintainable
Error-prone during query modifications
Requires mental mapping of positions

Building Effective Queries

1

Start with FROM

Specify your table first to enable code hinting for available columns

2

Select Columns

Use code hints to avoid typos. Choose specific columns rather than asterisk when possible

3

Add Filters and Sorting

Apply WHERE, ORDER BY, and LIMIT clauses in the correct sequence

Query Structure Best Practice

Put each SQL keyword on its own line for complex queries. This improves readability and makes debugging easier as queries grow in complexity.

SQL Clause Written Order

SELECT
1
DISTINCT
2
FROM
3
WHERE
4
ORDER BY
5
LIMIT
6

Query Validation Checklist

0/5
The worst thing in SQL is to be fast, but wrong. I don't care how fast you are if you're giving me a wrong answer.
Emphasizing the importance of accuracy over speed in database operations

This lesson is a preview from our SQL Course Online (includes software) and SQL Certification Online (includes software & exam). Enroll in a course for detailed lessons, live instructor support, and project-based training.

Now let's put these concepts into practice with a comprehensive live coding demonstration. Following this walkthrough, you'll complete structured exercises designed to reinforce your understanding—though the initial exercise focuses primarily on file setup and database connectivity.

I'll begin by closing unnecessary files and opening a prepared code example that demonstrates key SQL fundamentals. Don't worry about memorizing every syntax detail immediately—mastery comes through practice and repetition, not rote memorization.

Let's open the first exercise file from our structured curriculum. These files follow numerical ordering for logical progression, starting with exercise 1.0. While solution files exist for reference, we'll work exclusively with the practice files during this session—the exercise instructions will specify which files to use for each activity.

Here's how our learning structure works: Each file begins with warmup exercises and reference materials at the top, which I'll demonstrate step-by-step to ensure you understand the underlying mechanics. Below that, you'll find practical challenges—these are your opportunities to apply what you've learned independently. This hands-on approach helps you assess your comprehension and build confidence in writing SQL queries from scratch.

Notice something important when I begin typing code—there's no autocomplete or code hinting appearing. This absence of intelligent assistance is your first clue that something's wrong with our setup.

When I attempt to execute this query, the system returns "no active connection." This error occurs because while you can see the database server listed in the left panel, simply opening a file doesn't automatically establish which database that file should connect to. This is actually a crucial safety feature, not a bug.

Consider a real-world scenario where you're managing multiple database environments—perhaps a live production server alongside a testing database. When developing and testing queries, especially resource-intensive ones, you never want to accidentally run experimental code against your production system. That could degrade performance for actual users or, worse, corrupt live data.

The system requires explicit connection selection to prevent these costly mistakes. Notice in the interface how it displays "active data source is not available" and shows no catalog or schema information. Even though only one database appears in our current setup, the software enforces conscious connection choices as a best practice.

You might wonder why the system doesn't automatically connect to the obvious choice, but consider enterprise environments where multiple client databases, testing environments, and production systems coexist. Requiring explicit selection prevents accidentally querying the wrong dataset—a mistake that could lead to incorrect business decisions based on wrong data.

Initially, this safety protocol frustrated me as an unnecessary step. However, I've come to appreciate it as essential protection against one of SQL's most dangerous pitfalls: fast but incorrect results. Speed means nothing if your analysis is based on wrong data, and automatic connections to incorrect servers could easily produce misleading results.

This intentional friction ensures accuracy over convenience—a fundamental principle in professional data work. Notice the database connection icon in the toolbar. Clicking this opens the server selection dialog, where you can choose your target database (likely still named "company_data" unless you've customized it).

Double-clicking your server selection automatically connects to the default database, enabling query execution and restoring code hinting functionality.

Now that we've established proper connection, this query executes successfully, and intelligent code completion returns as we type. The absence of code hinting serves as a reliable diagnostic tool—it immediately signals that you haven't selected the appropriate server connection.

DBeaver remembers these associations for future sessions. Once you save a file with its database connection established, the software will automatically reconnect to that same server when you reopen the file. However, any new file requires this initial connection step until the association is saved.

When creating new scripts directly from the server interface, the connection inherits automatically since you're working within that server's context. But externally opened files—like the exercise files we're providing—always require explicit connection setup on first use.


Let's examine this basic query structure. The SELECT * FROM products statement retrieves every column and row from the products table. While this provides complete visibility into your data, most practical queries require more selectivity. You can reference available columns either by examining the result set below or by browsing the database schema in the left navigation panel—this dual-view approach facilitates efficient query development.

For more targeted results, specify individual columns by name. If I want only the title column, I simply replace the asterisk with "title". For multiple columns like title and price, separate them with commas. The order you specify determines the column arrangement in your result set—putting price before title would reverse their display order.

Understanding result sets is crucial: This tabular output below represents data generated by your query, not a direct view into the database itself. You have complete control over what appears in this result set. For example, I can create a result set containing arbitrary values like "hello" (in quotes because it's a string literal) or numbers like 1, 2, 3.

These values don't exist in any database table—I'm simply instructing SQL to display them in the result set. While most queries extract actual database information, this flexibility allows for calculated fields, constants, and other dynamic content in your output.

This control extends to column ordering and repetition. You're not constrained by the physical arrangement within database tables—reorder columns as needed for your analysis. You can even display the same column multiple times, which proves invaluable when working with wide datasets in tools like Excel, where you might want key identifiers repeated on both sides of a large spreadsheet to avoid constant scrolling.

For instance, with a users table containing many columns, I could display all columns using the asterisk, then add the name column again at the end for easy reference: SELECT *, name FROM users. This gives me complete data visibility while keeping the crucial identifier readily accessible.

This revelation often surprises newcomers who assume it's an either/or choice between SELECT * and specific column lists. You can combine both approaches—use the asterisk for comprehensive data access, then append specific columns for enhanced usability.

Column selection handles the horizontal dimension of your result set, but what about controlling rows? By default, SELECT * FROM products returns every row in the table. With our current 52 products, this remains manageable, but larger datasets require more restraint.

The LIMIT clause restricts row count—LIMIT 10 returns only the first ten rows. This proves essential for initial data exploration and performance optimization with large datasets, preventing accidental retrieval of millions of records.

Note the PostgreSQL-specific syntax in our examples. When you encounter SQL Server alternatives in the materials, focus exclusively on the PostgreSQL versions for our current environment.

Beyond limiting results, you'll frequently need to control row ordering. The ORDER BY clause sorts results by specified columns—ORDER BY price arranges products from lowest to highest price (ascending order by default). This ascending behavior follows intuitive patterns: 1, 2, 3 for numbers; A, B, C for text; oldest to newest for dates.

You can reference sort columns by name (ORDER BY price) or by position number in your result set. If selecting title and price in that order, title becomes column 1 and price becomes column 2, allowing ORDER BY 2 as shorthand for ordering by price.

However, I strongly recommend using column names rather than numbers. Position-based ordering becomes fragile when you reorder columns—if price moves to the first position, ORDER BY 2 would now sort by title instead of price, potentially breaking your query logic. Name-based ordering remains consistent regardless of column arrangement.

While numeric shortcuts save minimal typing, they create maintenance headaches and reduce code readability. You may encounter position-based ordering in legacy code, so understanding the concept helps with code comprehension even if you don't use it yourself.


The default ascending order covers most use cases, so you rarely need to specify ASC explicitly. For reverse ordering, add DESC (descending) to flip the sort—ORDER BY price DESC shows highest prices first. These represent your only two ordering options: ascending or descending.

I prefer building queries strategically by specifying the FROM clause first, then returning to add column selections. This approach enables code hinting as you type column names, preventing typos and ensuring accuracy. Intelligent autocomplete significantly reduces syntax errors—accept suggestions with Tab to maintain coding efficiency.

When examining single columns like tags, you'll often notice duplicate values. The DISTINCT keyword eliminates these duplicates, showing each unique value only once. Combined with ORDER BY, DISTINCT creates clean, alphabetized lists perfect for data exploration and validation.

Remember that SQL enforces strict syntax ordering—you must arrange clauses in the prescribed sequence defined by the language structure. This isn't arbitrary; it's how the SQL parser interprets and executes your instructions.

Mastering this clause ordering takes practice, but reference materials accelerate learning. Each exercise file includes our "Written and Execution Order" reference—a comprehensive two-page PDF covering both the sequence for writing queries and how SQL processes them internally. For now, focus on the writing order: SELECT (with optional DISTINCT), FROM, ORDER BY, then LIMIT.

These components must appear in this exact sequence. Having correct keywords isn't sufficient—incorrect ordering will cause query failures regardless of accurate syntax elsewhere. This structured approach distinguishes SQL as a declarative language where order matters as much as content.

Your next step involves completing the practical challenges below. These exercises ask you to write specific queries—like "view the entire users table"—using the concepts we've just covered. This hands-on practice solidifies your understanding and reveals areas needing additional focus.

After you complete these challenges, we'll reconvene to review solutions and address any questions. This iterative approach of demonstration, practice, and review ensures comprehensive skill development.

Exercise 1C corresponds to the introductory material in your reference book, focusing primarily on file setup and database connection procedures. Future exercises will concentrate on SQL development rather than configuration, but this foundational setup remains crucial for all subsequent work.

The warmup section contains commented code—lines preceded by double dashes (--) that SQL ignores during execution. These comments preserve example code for reference while preventing accidental execution. You'll type functional versions of these queries in the practice area below.

This hands-on typing practice is essential for skill development. Muscle memory and mental patterns develop through repetition, so resist the temptation to copy and paste. Each time you type SQL syntax manually, you're building the neural pathways that will make future query development intuitive and efficient.

Let's begin with Exercise 1C and establish your development environment properly.

Key Takeaways

1DBeaver requires manual server selection for new files as a safety protocol to prevent wrong database connections
2SQL clauses must be written in a specific order: SELECT, DISTINCT, FROM, WHERE, ORDER BY, LIMIT
3Result sets are custom views you create, not direct database representations - you control column order and repetition
4Use specific column names rather than position numbers for maintainable, readable queries
5Code hinting availability indicates proper database connection - absence suggests connection issues
6The DISTINCT keyword eliminates duplicate rows from query results
7ORDER BY defaults to ascending order; add DESC for descending sort
8Starting queries with FROM clause enables code hinting for available columns and reduces typos

RELATED ARTICLES