🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Data Science & Analytics › SQL and PostgreSQL for Data Analytics › Lesson 2
TEC-DATA85-04 · Lesson 2 · 10 clock hours · lab

Installing PostgreSQL and Writing First Queries

Objective. Students install PostgreSQL, create a database, and execute correct SELECT, WHERE, ORDER BY, and LIMIT queries against a provided sample dataset.

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

What Is PostgreSQL and Why Does It Matter for Data Analytics?

PostgreSQL is a free, open-source relational database management system (RDBMS) with a strong reputation for standards compliance, reliability, and advanced data types. Many employers in data analytics use PostgreSQL or a cloud variant of it (such as Amazon Aurora or Google Cloud SQL). Learning it prepares you for the Google Data Analytics Certificate, CompTIA Data+, IBM Data Science Professional, and Microsoft PL-300 environments, all of which expect you to read and write SQL fluently.

A relational database organizes data into tables made of rows and columns. Every table has a defined structure called a schema, which names each column and declares its data type (for example, `INTEGER`, `TEXT`, or `DATE`). SQL—Structured Query Language—is the standard language for asking questions of, and making changes to, those tables.

Installing PostgreSQL Safely on a Workstation VM

You are working inside a virtual machine (VM), not on your host computer. This is intentional: VMs provide an isolated environment so that a misconfigured database service cannot affect your host OS or other students' machines on the network.

Before you begin any installation:

After the installer finishes, open a terminal and run:

```

psql -U postgres -c "SELECT version();"

```

A successful response prints the PostgreSQL version string. If you see an error, stop and raise your hand—do not move forward until the service is confirmed running. Your instructor will inspect each machine at this checkpoint.

pgAdmin 4: The Graphical Tool

pgAdmin 4 is the official web-based GUI for PostgreSQL. It runs in your browser (pointed at `localhost`) and lets you browse database objects, write queries in an editor, and view results in a table. Use it alongside the `psql` command-line tool—professional analysts switch between the two depending on the task. The command line is faster for scripting and bulk data loads; pgAdmin is clearer for exploring an unfamiliar schema.

Creating a Database and Loading Data

Before you can query data, you need a database to hold it. Inside `psql`:

```sql

CREATE DATABASE library_checkouts;

\c library_checkouts

```

The `\c` meta-command connects you to that database. Your instructor will provide a `CREATE TABLE` script that defines the schema for the library-checkout records. Run it, then load the CSV with `\copy`:

```

\copy checkouts FROM '/path/to/library_checkouts.csv' CSV HEADER;

```

`\copy` runs on the client side—it reads the file from your local machine rather than requiring the file to be on the server. After the load completes, always verify the row count:

```sql

SELECT COUNT(*) FROM checkouts;

```

The result should match the row count printed on the CSV's README. If it does not, stop and consult your instructor before writing any analysis queries—bad input data produces bad results.

The Core SELECT Statement

The four clauses you will practice today form the backbone of analytical querying:

SELECT names the columns (or expressions) you want to see.

FROM names the table.

WHERE filters rows before they are returned.

ORDER BY sorts the result set.

LIMIT caps the number of rows returned.

General form:

```sql

SELECT column1, column2

FROM table_name

WHERE condition

Order BY column1 DESC

LIMIT n;

```

PostgreSQL evaluates these clauses in a logical order that differs from the written order: FROM → WHERE → SELECT → ORDER BY → LIMIT. Understanding this order helps you predict what each clause can and cannot reference.

Working Through the Query Sprint

For each worksheet challenge, follow this discipline:

1. Read the question carefully and identify which columns you need.

2. Write the query in your `.sql` file with a comment line (`-- Challenge 3`) above it.

3. Run it in pgAdmin or `psql` and inspect the first several rows for reasonableness.

4. Save the file before moving to the next challenge.

This habit—comment, write, run, inspect, save—mirrors professional workflow and makes it easy for your instructor to review your work.

Data Integrity and Lab Notebook Records

Record every important step in your lab notebook: the PostgreSQL version installed, the row count after the load, and any error messages with their solutions. Good documentation is a professional habit and will help you when you sit certification exams that ask about troubleshooting scenarios.

Key terms9

Relational Database Management System (RDBMS)Software that stores data in tables of rows and columns and uses SQL as its query language; PostgreSQL is a widely used open-source example.
SchemaThe defined structure of a database table: the names of its columns and the data type of each column.
psqlThe official command-line client for PostgreSQL; used to connect to a database, run SQL statements, and execute meta-commands such as \copy and \c.
\copyA psql meta-command that loads data from a file on the client machine into a PostgreSQL table; preferred over the server-side COPY command in lab environments.
SELECT statementThe SQL command used to retrieve data from one or more tables; combined with FROM, WHERE, ORDER BY, and LIMIT to shape the result set.
WHERE clauseA part of a SELECT statement that filters rows by a condition; only rows where the condition evaluates to true are included in the result.
ORDER BY clauseA part of a SELECT statement that sorts the returned rows by one or more columns, either ascending (ASC, the default) or descending (DESC).
LIMIT clauseA PostgreSQL clause that restricts the number of rows returned by a query; commonly used with ORDER BY to retrieve a ranked top-N list.
Port 5432The default TCP port on which PostgreSQL listens for connections; should be restricted to localhost in a lab environment for security.
In class: Guided install: students install PostgreSQL on their workstation VM, initialize a cluster, and verify the service is running using psql and pgAdmin; instructor checks each machine before the class moves on. · Data load: students use the psql \\copy command to load a 50,000-row CSV of public library checkout records into a pre-defined table, verifying row count with SELECT COUNT(*). · Query sprint: students complete ten structured query challenges (e.g., 'List the ten most-checked-out titles in 2023') from a printed worksheet, saving each query in a .sql file.
Materials: PostgreSQL 16 installer, pgAdmin 4, sample library-checkouts CSV (public domain), query worksheet, student lab notebooks
Check: Instructor reviews the ten .sql files; all ten queries must return the correct result set (verified against an answer key) for a pass—students with fewer than eight correct receive targeted re-instruction before the next lesson.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Data integrity and data preparation
1. After loading the library-checkouts CSV, a student runs SELECT COUNT(*) FROM checkouts and gets 47,000 rows instead of the expected 50,000. What is the most appropriate immediate action?
SQL fundamentals
2. Which SQL clause filters rows in a SELECT query so that only rows meeting a specified condition are returned?
SQL fundamentals
3. A student wants to list the ten titles with the highest checkout count in 2023, from highest to lowest. Which query structure is correct?
Data security and governance
4. Why is the PostgreSQL lab database service configured to accept connections only from localhost (127.0.0.1) and not from external network addresses?
Database tools and environment
5. What does the psql meta-command \c library_checkouts do?
SQL fundamentals
6. A student uses ORDER BY checkout_date ASC in a query. In which order will the results appear?
Professional data analytics practices
7. Which of the following best describes the purpose of saving each query challenge in a separate .sql file during the query sprint?
SQL fundamentals
8. A student's WHERE clause reads: WHERE checkout_year = '2023'. The checkout_year column is defined as INTEGER in the schema. What is the most likely result in PostgreSQL?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.