Sunday, January 11, 2026

Next Article (Part 2): SQL Mastery for Beginners

Your first article built a strong foundation: what databases are, why we use them, core concepts (tables, keys, relationships), and basic SQL actions. The best next step is to become confident in writing real queries and understanding how SQL thinks. This Part 2 focuses on the most common skills beginners need to pass labs and start building projects: filtering, pattern matching, handling missing values, grouping, aggregates, joins (deeper), subqueries, and good query habits.

1. The SQL Mindset: How to Think When Writing Queries

Beginners often think SQL is “memorizing commands.” In reality, SQL is about answering questions using data. Every SQL query is a response to a question like:

  • “Which students are in BSIT?”
  • “How many students are enrolled in Database Systems?”
  • “Show each student’s courses and grades.”
  • “Which students are not enrolled in any course?”

A simple process you can follow every time:

  1. Understand the question. What is being asked?
  2. Identify the tables needed. Where is the data stored?
  3. Start simple. Write a basic SELECT * and confirm the tables contain what you think.
  4. Add conditions. Use WHERE, then ORDER BY.
  5. Combine tables only when needed. Add JOIN step-by-step.
  6. Test your results. Check if the answer makes sense.

SQL is also “set-based,” meaning it works with groups of rows at once (not one row at a time like many programming languages). This is why GROUP BY and aggregates are so powerful.

2. Setup: Reuse the Same School Database

We will reuse the same schema from Part 1 so you can practice consistently. If you already created these tables, you can skip to the next section.

2.1 Create Tables


CREATE TABLE Students (
    student_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name  VARCHAR(50),
    program    VARCHAR(20),
    year_level INT
);

CREATE TABLE Courses (
    course_id   INT PRIMARY KEY,
    course_name VARCHAR(100),
    credits     INT
);

CREATE TABLE Enrollments (
    enrollment_id INT PRIMARY KEY,
    student_id    INT,
    course_id     INT,
    grade         VARCHAR(2),
    FOREIGN KEY (student_id) REFERENCES Students(student_id),
    FOREIGN KEY (course_id)  REFERENCES Courses(course_id)
);

2.2 Insert Sample Data


INSERT INTO Students (student_id, first_name, last_name, program, year_level) VALUES
(1001, 'Maria', 'Santos', 'BSIT', 1),
(1002, 'Juan',  'Cruz',   'BSIT', 2),
(1003, 'Ana',   'Reyes',  'BSCS', 1),
(1004, 'Mark',  'Dela Cruz', 'BSIT', 1),
(1005, 'Liza',  'Garcia', 'BSBA', 2);

INSERT INTO Courses (course_id, course_name, credits) VALUES
(1, 'Database Systems', 3),
(2, 'Programming 1',    3),
(3, 'Web Development',  3),
(4, 'Networking 1',     3);

INSERT INTO Enrollments (enrollment_id, student_id, course_id, grade) VALUES
(1, 1001, 1, 'A'),
(2, 1001, 2, 'B'),
(3, 1002, 1, 'B'),
(4, 1003, 3, 'A'),
(5, 1004, 1, 'C'),
(6, 1004, 4, 'B');

Notice that student 1005 (Liza) has no enrollments yet. This is intentional so you can practice LEFT JOIN and “missing data” queries.

3. SELECT Deep Dive: Columns, Aliases, and Expressions

3.1 Selecting only what you need

Beginners often use SELECT * all the time. It’s okay for learning, but in real work you should select only the needed columns.


SELECT student_id, first_name, last_name
FROM Students;

3.2 Aliases: making output readable

Aliases rename columns in the output. This helps when you are creating reports.


SELECT
  student_id AS id,
  first_name AS given_name,
  last_name  AS family_name
FROM Students;

3.3 Expressions: create computed values

You can create new values from existing columns. Example: a simple full name display. Different databases have different concatenation methods. Here are common patterns:

MySQL:


SELECT CONCAT(first_name, ' ', last_name) AS full_name
FROM Students;

PostgreSQL / SQLite:


SELECT first_name || ' ' || last_name AS full_name
FROM Students;

If you’re unsure which one works in your lab environment, test both. This is a normal beginner situation.

4. Filtering Correctly: WHERE, AND/OR, BETWEEN, IN

4.1 WHERE: the most used keyword after SELECT


SELECT *
FROM Students
WHERE program = 'BSIT';

4.2 AND vs OR (common logic mistake)

AND means all conditions must be true.
OR means at least one condition must be true.

Example: BSIT students in year level 1:


SELECT *
FROM Students
WHERE program = 'BSIT'
  AND year_level = 1;

If you mistakenly use OR here, you would also get: students who are year 1 but not BSIT, and BSIT students who are not year 1.

4.3 BETWEEN (ranges)


SELECT *
FROM Students
WHERE year_level BETWEEN 1 AND 2;

4.4 IN (multiple possible values)


SELECT *
FROM Students
WHERE program IN ('BSIT', 'BSCS');

5. Pattern Matching and Missing Values: LIKE and NULL

5.1 LIKE (searching text patterns)

Use LIKE when you want “matches that look like this,” not exact matches.

Students with last name starting with “De”:


SELECT *
FROM Students
WHERE last_name LIKE 'De%';

% means “any characters.” So 'De%' means “De + anything after it.”

5.2 NULL: the value that means “missing”

NULL does not mean zero. It does not mean empty string. It means “no value / unknown.” This is extremely important because many beginners write: WHERE column = NULL and wonder why it returns no results.

Correct way:


SELECT *
FROM Enrollments
WHERE grade IS NULL;

Correct way for “not null”:


SELECT *
FROM Enrollments
WHERE grade IS NOT NULL;

6. Summaries: COUNT, SUM, AVG, MIN, MAX

Aggregates summarize many rows into one result.

6.1 COUNT: how many rows?


SELECT COUNT(*) AS total_students
FROM Students;

6.2 AVG: average of numeric values

Our sample grades are letters. So let’s average course credits instead.


SELECT AVG(credits) AS avg_credits
FROM Courses;

6.3 MIN and MAX


SELECT MIN(year_level) AS min_year, MAX(year_level) AS max_year
FROM Students;

7. GROUP BY and HAVING (Most Common Reporting Lab Topic)

Many lab activities ask “how many” or “total per group.” When you see phrases like: “per course,” “per student,” “per program,” you probably need GROUP BY.

7.1 Count students per program


SELECT program, COUNT(*) AS total_students
FROM Students
GROUP BY program
ORDER BY total_students DESC;

Read it like this: “Group students by program, and count how many students are in each program.”

7.2 Count enrollments per course


SELECT c.course_name, COUNT(e.enrollment_id) AS total_enrolled
FROM Courses c
LEFT JOIN Enrollments e ON c.course_id = e.course_id
GROUP BY c.course_name
ORDER BY total_enrolled DESC;

We used LEFT JOIN because we want to include courses even if no one is enrolled yet.

7.3 HAVING: filter after grouping

Use WHERE to filter rows before grouping. Use HAVING to filter groups after grouping.

Show only programs with at least 2 students:


SELECT program, COUNT(*) AS total_students
FROM Students
GROUP BY program
HAVING COUNT(*) >= 2;

8. JOINs Explained Clearly (INNER, LEFT, and Common Mistakes)

JOIN is one of the most important topics in databases. You use JOIN when the answer needs data from more than one table.

8.1 INNER JOIN: only matching rows

If a student has no enrollment, INNER JOIN will not show that student in the result.


SELECT
  s.student_id,
  s.first_name,
  s.last_name,
  c.course_name,
  e.grade
FROM Enrollments e
JOIN Students s ON e.student_id = s.student_id
JOIN Courses  c ON e.course_id  = c.course_id
ORDER BY s.student_id, c.course_name;

8.2 LEFT JOIN: keep all rows from the left table

LEFT JOIN is used when you want to keep everything from the main table, even if there’s no match in the other table. This is perfect for questions like: “Show all students, even those not enrolled yet.”


SELECT
  s.student_id,
  s.first_name,
  s.last_name,
  c.course_name,
  e.grade
FROM Students s
LEFT JOIN Enrollments e ON e.student_id = s.student_id
LEFT JOIN Courses c ON c.course_id = e.course_id
ORDER BY s.student_id;

In this output, students with no enrollments will show NULL for course_name and grade.

8.3 Common JOIN mistake: missing or wrong ON condition

If you forget the ON condition or join on the wrong columns, you can create a “cartesian product” (too many rows) and the results will look wrong.

Bad example (do not do this):


SELECT *
FROM Students s
JOIN Courses c;

The above will match every student with every course, which is not what we want.

9. Subqueries: Queries Inside Queries (Beginner-Friendly)

A subquery is simply a query inside another query. It helps when:

  • You want to filter using a list produced by another query.
  • You want to compare values to a computed value (like average credits).

9.1 Find students who are enrolled in “Database Systems”

Step 1: Find the course_id of “Database Systems”.
Step 2: Find enrollments that match that course_id.
Step 3: Find students who match those enrollments.


SELECT *
FROM Students
WHERE student_id IN (
  SELECT student_id
  FROM Enrollments
  WHERE course_id IN (
    SELECT course_id
    FROM Courses
    WHERE course_name = 'Database Systems'
  )
);

This looks long, but it’s readable if you think in steps. Later you can also write it using JOINs (often faster and clearer), but subqueries are still important to know.

9.2 Find courses with no enrollments


SELECT *
FROM Courses
WHERE course_id NOT IN (
  SELECT course_id
  FROM Enrollments
);

If you want an alternative approach, you can use LEFT JOIN and check for NULL:


SELECT c.*
FROM Courses c
LEFT JOIN Enrollments e ON e.course_id = c.course_id
WHERE e.course_id IS NULL;

10. Practical Habits: Naming, Testing, and Debugging Queries

10.1 Good naming habits

A beginner-friendly naming rule:

  • Tables: plural nouns (Students, Courses, Enrollments)
  • Primary keys: table name + _id (student_id, course_id)
  • Foreign keys match the referenced primary key name (student_id, course_id)

10.2 Debugging habit: run the pieces

When a JOIN query looks wrong, test it in parts:

  1. Run SELECT * FROM Students;
  2. Run SELECT * FROM Enrollments;
  3. Run the JOIN with only one join first (Students + Enrollments)
  4. Add Courses only after the first join works

10.3 Always verify with a small known case

Example: If you know Maria (1001) is enrolled in 2 courses, your query that counts her courses should return 2. If it returns 4, you likely duplicated rows with a join or grouped incorrectly.

11. Practice Labs (With Expected Outputs and Hints)

These practice questions are designed to match typical classroom/lab tasks. Try to answer them without copying solutions. If you get stuck, write your attempt and then fix it.

Lab A: Simple filtering

  1. List all BSIT students.
  2. List all students whose last name starts with “C”.
  3. List all students in year level 1 or 2, sorted by last_name.

Lab B: JOIN practice

  1. Show each enrollment with student full name, course name, and grade.
  2. Show all students even if not enrolled (course and grade can be NULL).
  3. Show all courses even if nobody is enrolled yet.

Lab C: GROUP BY practice

  1. Count students per program.
  2. Count how many students are enrolled per course.
  3. Show only courses with at least 2 enrollments (use HAVING).

Lab D: “Find missing” (classic lab problem)

Question: List students who are not enrolled in any course.

Hint: Use LEFT JOIN from Students to Enrollments and check for NULL in Enrollments.

12. Mini Project: Build a Simple “School Report” Feature

A good beginner milestone is being able to produce useful “reports.” Here are three practical reports you can generate with SQL.

12.1 Report 1: Student Enrollment List

Goal: show student name + course name + grade for all enrollments.


SELECT
  s.student_id,
  s.first_name,
  s.last_name,
  c.course_name,
  e.grade
FROM Enrollments e
JOIN Students s ON s.student_id = e.student_id
JOIN Courses c ON c.course_id = e.course_id
ORDER BY s.last_name, s.first_name, c.course_name;

12.2 Report 2: Students with number of courses

Goal: show every student and how many courses they are taking (including zero).


SELECT
  s.student_id,
  s.first_name,
  s.last_name,
  COUNT(e.course_id) AS num_courses
FROM Students s
LEFT JOIN Enrollments e ON e.student_id = s.student_id
GROUP BY s.student_id, s.first_name, s.last_name
ORDER BY num_courses DESC, s.last_name;

12.3 Report 3: Course popularity

Goal: show each course and the number of enrollments.


SELECT
  c.course_id,
  c.course_name,
  COUNT(e.enrollment_id) AS total_enrolled
FROM Courses c
LEFT JOIN Enrollments e ON e.course_id = c.course_id
GROUP BY c.course_id, c.course_name
ORDER BY total_enrolled DESC, c.course_name;

If you can write and explain these three reports, you are already ahead of many beginners. These are the exact patterns used in many real systems (school systems, HR systems, store systems).

13. What to Learn Next (Part 3 Preview)

After Part 2, a beginner is usually ready for Part 3 topics that move from “writing queries” to “designing and protecting data correctly.”

Recommended Part 3: Database Design and Data Integrity (Beginner to Intermediate)

  • How to choose correct primary keys (natural vs surrogate keys)
  • Composite keys and junction tables (many-to-many done right)
  • Normalization (1NF, 2NF, 3NF) with simple examples
  • Constraints in real projects (UNIQUE, NOT NULL, CHECK)
  • Cascading rules (ON DELETE CASCADE, ON UPDATE CASCADE) and when to avoid them
  • Transactions in practice (COMMIT/ROLLBACK) and why they matter
  • Intro to performance: indexes, query plans (conceptual)

If you want, tell me which DBMS your student uses in lab (MySQL, PostgreSQL, SQLite, SQL Server). I can adjust the SQL syntax (especially for string concatenation and date functions) so every query works exactly in her environment.

1. What is a Database?

1.1 Data vs. Information

Before you can understand databases, you need to be clear about data and information.

Data: Raw facts, not yet organized or meaningful by themselves.
Examples:
2026-01-11
Juan
BSIT
95

Information: Data that has been organized so that it means something.
Examples:
“Juan (BSIT student) scored 95 in Database Systems on 2026-01-11.”
“Student 202312345, named Maria, is enrolled in BSIT, year 1.”

A database stores data in such a way that it is easy to turn it into useful information.

1.2 Simple Definition of a Database

A database is:
An organized collection of related data that can be easily stored, searched, updated, and managed by a computer.

Think of a database as:
A very smart, very organized digital filing cabinet.
Each “folder” (table) in the cabinet stores one kind of thing (students, courses, orders, etc.).

1.3 Real-Life Examples of Databases

You already use systems that depend on databases every day:

  • School system
    Stores: students, teachers, subjects, grades, schedules.
  • Banking system
    Stores: customers, accounts, balances, transactions.
  • Online shopping site (e.g., Lazada, Shopee)
    Stores: products, sellers, buyers, orders, payments.
  • Social media (e.g., Facebook, Instagram)
    Stores: users, posts, comments, likes, messages.

In each of these:
The app you see is only the front-end.
The database in the back stores all the important data.

1.4 Database vs. DBMS

Two important terms:

  • Database
    The actual data itself (like the content of the cabinet).
  • Database Management System (DBMS)
    The software that creates, stores, manages, and retrieves data in the database.

Common DBMS examples:
MySQL, PostgreSQL, SQL Server, Oracle, SQLite

You do not usually “talk” directly to the raw database; you talk to the DBMS using a language called SQL.

1.5 Quick Self-Check

Try answering in your own words:

  1. What is the difference between data and information?
  2. What is the role of the DBMS?
  3. Name one system you use daily that definitely has a database behind it.

If you struggle, reread the section and summarize to yourself in 2–3 sentences.

2. Why Do We Need Databases?

2.1 Limits of Spreadsheets

Spreadsheets are great for:

  • Small lists
  • Simple calculations
  • Individual work

But they have problems when:

  • Many people use the same data at the same time.
  • Data becomes large (thousands or millions of rows).
  • You need relations between different things (students, courses, grades).
  • You need security (not everyone should see everything).
  • You need reliability (no accidental deletion of everything).

2.2 What Databases Are Good At

Databases are designed to handle:

  1. Multiple tables and relationships
    Example: School system — Students, Courses, Teachers, Enrollments — all connected through keys and relationships.
  2. Many users at once
    Many students registering at the same time. Multiple staff updating information.
  3. Data consistency and rules
    Student ID must be unique.
    Grades must be between 0 and 100 (or A–F).
    You cannot enroll a student who does not exist.
  4. Security and permissions
    A student can only see their own grades.
    An instructor can edit grades for their own classes only.
    An admin may see everything.
  5. Speed
    Quickly search for data, even in huge databases.
    Example: Search “all BSIT students in year 2 with GPA > 2.0”.

2.3 Databases vs Files

You could try to store everything in simple files (CSV, text files, etc.). Problems with only using files:

  • Harder to enforce rules.
  • No built-in security or permissions.
  • No efficient way to join many related files.
  • More difficult to handle large amounts of data safely.

Databases solve these issues by:

  • Having a schema (structure and rules).
  • Providing transactions (safe groups of operations).
  • Allowing concurrent access while maintaining consistency.

2.4 Mini Exercise

Imagine a small library at school managed with only an Excel file:
Columns: BookTitle, Author, BorrowerName, BorrowDate, ReturnDate.

Think:

  1. What problems might appear if 3 librarians edit this at the same time?
  2. What happens if a book title is spelled differently in different rows?
  3. How would you find all books borrowed by one particular student?

Now imagine the same system using a database with:
Books table, Members table, Loans table.
How is it easier to manage? Talk through it with a classmate or write a short explanation.

3. Types of Databases

3.1 Relational Databases (Most Common in Schools and Business)

Data is stored in tables (rows and columns).
Tables are related using keys (primary keys and foreign keys).
You use SQL to work with the data.

Examples: MySQL, PostgreSQL, SQL Server, Oracle, SQLite

You will mostly study this type in your IT course.

3.2 NoSQL Databases (Non-Relational)

“NoSQL” means “Not Only SQL.” They are often used when:

  • Data is not easily represented as tables.
  • You need to scale to very large, distributed systems.

Common types:

  • Document databases
    Store data as documents (often JSON-like). Flexible structure; each document can be a bit different.
    Example: MongoDB.
  • Key-Value stores
    Very simple: each piece of data has a key and a value.
    Example: Redis.
  • Column-family stores
    Designed for large-scale, distributed storage.
    Example: Cassandra.
  • Graph databases
    Focus on relationships between entities (nodes and edges).
    Example: Neo4j; often used for social networks, recommendation systems.

As a beginner, it’s enough to:
Know they exist.
Understand they are used for specific needs (flexible data, huge scale, complex relationships).

3.3 In-Memory Databases

Keep data primarily in RAM (memory) instead of disk.
Very fast, but data may be lost if not persisted.
Used for caching and fast lookups.
Example: Redis (often used as both cache and key-value store).

3.4 Relational vs NoSQL (Beginner-Level View)

Relational NoSQL
Structured, consistent, tables and relationships.
Strong rules and consistency.
Best when data fits well into rows and columns (school systems, banking).
Flexible structure.
Can be easier to scale across many servers.
Often used in modern web apps, big data, logs, etc.

In most IT/CS curricula, you learn relational databases + SQL first. Later, you can explore NoSQL as another tool.

3.5 Quick Reflection

Ask yourself:

  1. If you build a school enrollment system, which type of database would you use first? Why?
  2. If you build a chat app handling millions of messages per minute, would you consider NoSQL? Why?

Write 3–4 sentences justifying your choice.

4. Key Database Concepts

4.1 Tables, Rows, and Columns

A table is like a very structured spreadsheet:

  • Rows (records): individual entries.
  • Columns (fields/attributes): types of information.

Example: Students table.

student_id first_name last_name program year_level
1001 Maria Santos BSIT 1
1002 Juan Cruz BSIT 2

Here:
Each row is one student.
Each column is one attribute of that student.

4.2 Data Types

Each column has a data type that defines what kind of data can be stored.

Common ones:

  • INT – whole numbers (like 1, 2, 100).
  • DECIMAL(p, s) – decimal numbers with precision.
  • VARCHAR(n) – variable-length text up to n characters.
  • CHAR(n) – fixed-length text.
  • DATE – dates.
  • TIME – times.
  • DATETIME / TIMESTAMP – date and time together.
  • BOOLEAN – true/false (often stored as 1/0).

Example: Courses table.

Column Type Example
course_id INT 101
name VARCHAR(100) Database Systems
credits INT 3

Choosing correct data types:
Saves storage.
Improves performance.
Prevents invalid data (like letters in a numeric field).

4.3 Primary Keys

A primary key (PK):

  • Uniquely identifies each row in a table.
  • Cannot be NULL.
  • Often a single column like student_id or an auto-incrementing ID.

Example:


CREATE TABLE Students (
    student_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name  VARCHAR(50),
    program    VARCHAR(20),
    year_level INT
);

Why primary keys matter:
Without them, you cannot reliably say which row is which.
They are used to create relationships with other tables.

4.4 Foreign Keys and Relationships

A foreign key (FK):

  • A column that refers to the primary key of another table.
  • It creates a relationship between tables.
  • It enforces referential integrity (e.g., you cannot enroll a non-existent student).

Example tables:


CREATE TABLE Courses (
    course_id   INT PRIMARY KEY,
    course_name VARCHAR(100),
    credits     INT
);

CREATE TABLE Enrollments (
    enrollment_id INT PRIMARY KEY,
    student_id    INT,
    course_id     INT,
    grade         VARCHAR(2),
    FOREIGN KEY (student_id) REFERENCES Students(student_id),
    FOREIGN KEY (course_id)  REFERENCES Courses(course_id)
);

Here:
Enrollments.student_idStudents.student_id
Enrollments.course_idCourses.course_id

4.5 Types of Relationships

  1. One-to-One (1:1)
    One row in Table A is related to at most one row in Table B.
    Example: Person and Passport (assuming exactly one passport per person).
  2. One-to-Many (1:N)
    One row in Table A can be related to many rows in Table B.
    Example: Teacher to Class (one teacher can teach many classes).
  3. Many-to-Many (M:N)
    Many rows in A can relate to many rows in B.
    Example: Students and Courses.
    This is usually implemented with a third table (like Enrollments).

4.6 Normalization (Basic Idea)

Normalization is about designing tables to reduce redundant data and update problems.

Very simplified:
Each piece of information should be stored in one place.
Break large, messy tables into smaller, related tables.

Bad design example:

EnrollmentsBad
student_id | student_name | course_id | course_name | grade

Problems:
Student name repeated many times.
Course name repeated many times.
If you change a course name, you must update many rows.

Better design:

Students(student_id, first_name, last_name, ...)
Courses(course_id, course_name, ...)
Enrollments(enrollment_id, student_id, course_id, grade)

4.7 Constraints

Constraints enforce rules on data:

  • PRIMARY KEY – uniqueness and not null.
  • FOREIGN KEY – ensures referenced data exists.
  • UNIQUE – no duplicate values in a column.
  • NOT NULL – value must be provided.
  • CHECK – custom conditions (e.g., grade between 0 and 100).

Example:


CREATE TABLE Students (
    student_id INT PRIMARY KEY,
    first_name VARCHAR(50) NOT NULL,
    last_name  VARCHAR(50) NOT NULL,
    year_level INT CHECK (year_level BETWEEN 1 AND 4)
);

4.8 Quick Questions to Test Your Understanding

  1. In your own words, what is a foreign key?
  2. Why is it bad to store student names repeatedly in an enrollment table?
  3. Design three tables for a “library” system and list their primary keys.

Write your answers and compare them with classmates or ask your instructor/GPT to review.

5. Introduction to SQL

SQL = Structured Query Language
It is the standard language to talk to relational databases.

With SQL you can:

  • Create tables.
  • Insert data.
  • Read (query) data.
  • Update data.
  • Delete data.

5.1 SQL Categories

  • DDL – Data Definition Language
    Defines structure (tables, columns, constraints).
    Commands: CREATE, ALTER, DROP.
  • DML – Data Manipulation Language
    Works with the actual data (rows).
    Commands: INSERT, SELECT, UPDATE, DELETE.
  • DCL/TCL – Data/Transaction Control (more advanced)
    Permissions, transactions, commit, rollback.
    Commands: GRANT, REVOKE, COMMIT, ROLLBACK.

For beginners, focus mainly on:
CREATE TABLE, INSERT, SELECT, UPDATE, DELETE.

5.2 Creating Tables (DDL)

Example for a simple school database:


CREATE TABLE Students (
    student_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name  VARCHAR(50),
    program    VARCHAR(20),
    year_level INT
);

CREATE TABLE Courses (
    course_id   INT PRIMARY KEY,
    course_name VARCHAR(100),
    credits     INT
);

CREATE TABLE Enrollments (
    enrollment_id INT PRIMARY KEY,
    student_id    INT,
    course_id     INT,
    grade         VARCHAR(2),
    FOREIGN KEY (student_id) REFERENCES Students(student_id),
    FOREIGN KEY (course_id)  REFERENCES Courses(course_id)
);

5.3 Inserting Data (INSERT)


INSERT INTO Students (student_id, first_name, last_name, program, year_level)
VALUES (1001, 'Maria', 'Santos', 'BSIT', 1);

INSERT INTO Students (student_id, first_name, last_name, program, year_level)
VALUES
(1002, 'Juan', 'Cruz', 'BSIT', 2),
(1003, 'Ana',  'Reyes', 'BSCS', 1);

You can insert:
One row at a time.
Multiple rows in one statement.

5.4 Reading Data (SELECT)

Read all columns and rows:

SELECT * FROM Students;

Read specific columns:

SELECT first_name, last_name, program
FROM Students;

Filter with WHERE:

SELECT *
FROM Students
WHERE program = 'BSIT';

SELECT *
FROM Students
WHERE year_level = 1;

Sort with ORDER BY:

SELECT *
FROM Students
ORDER BY last_name ASC;   -- ascending (A–Z)

SELECT *
FROM Students
ORDER BY year_level DESC; -- descending (4–1)

5.5 Updating Data (UPDATE)

UPDATE Students
SET year_level = 2
WHERE student_id = 1001;

Important: Always include a WHERE clause.
Without WHERE, you will update every row!

5.6 Deleting Data (DELETE)

DELETE FROM Students
WHERE student_id = 1003;

Again: Without WHERE, all rows will be deleted!

5.7 Joining Tables

To combine data from multiple tables, use JOIN.

Example question:
“List each student with course names and their grades.”


SELECT
    s.first_name,
    s.last_name,
    c.course_name,
    e.grade
FROM Enrollments e
JOIN Students s ON e.student_id = s.student_id
JOIN Courses  c ON e.course_id  = c.course_id;

Here:
Enrollments connects Students and Courses.
We “join” them on their key columns.

5.8 Practice Prompts

Try to write SQL for:

  1. Insert a new student with ID 1004, name “Mark Dela Cruz”, BSIT year 1.
  2. List all BSIT students, sorted by last name.
  3. Show the first name, last name, course name, and grade of all enrollments.

If you get stuck, break the task into small steps:
1. First query just Students.
2. Then Courses.
3. Then Enrollments.
4. Then add the JOINs.

6. Hands-On Practice Guide

6.1 Setting Up an Environment

You have a few options:

  • Install a DBMS locally (MySQL, PostgreSQL, or SQLite).
  • Use an online SQL sandbox (search “online SQL editor” or “db fiddle”).
  • Use tools like “DB Browser for SQLite” for a simple, lightweight database.

For beginners, online sandboxes are often easiest:
No installation.
You can focus on SQL rather than setup issues.

6.2 Step 1: Create a Simple Database Schema

Use these tables as your starting point:


CREATE TABLE Students (
    student_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name  VARCHAR(50),
    program    VARCHAR(20),
    year_level INT
);

CREATE TABLE Courses (
    course_id   INT PRIMARY KEY,
    course_name VARCHAR(100),
    credits     INT
);

CREATE TABLE Enrollments (
    enrollment_id INT PRIMARY KEY,
    student_id    INT,
    course_id     INT,
    grade         VARCHAR(2),
    FOREIGN KEY (student_id) REFERENCES Students(student_id),
    FOREIGN KEY (course_id)  REFERENCES Courses(course_id)
);

Run these statements in your SQL environment.

6.3 Step 2: Insert Sample Data


INSERT INTO Students (student_id, first_name, last_name, program, year_level) VALUES
(1001, 'Maria', 'Santos', 'BSIT', 1),
(1002, 'Juan',  'Cruz',   'BSIT', 2),
(1003, 'Ana',   'Reyes',  'BSCS', 1);

INSERT INTO Courses (course_id, course_name, credits) VALUES
(1, 'Database Systems', 3),
(2, 'Programming 1',    3),
(3, 'Web Development',  3);

INSERT INTO Enrollments (enrollment_id, student_id, course_id, grade) VALUES
(1, 1001, 1, 'A'),
(2, 1001, 2, 'B'),
(3, 1002, 1, 'B'),
(4, 1003, 3, 'A');

Check that data is inserted:

SELECT * FROM Students;
SELECT * FROM Courses;
SELECT * FROM Enrollments;

6.4 Step 3: Practice Basic SELECT

Questions to answer using SQL:

  1. Show all students.
  2. Show all courses.
  3. Show all enrollments with their grades.

Write your own queries, then run them. Example:

SELECT * FROM Students;
SELECT course_id, course_name FROM Courses;
SELECT student_id, course_id, grade FROM Enrollments;

6.5 Step 4: Practice Filters and Sorting

Try:

  • All BSIT students.
  • All students in year 1.
  • All students ordered by program then last name.

Examples:


SELECT *
FROM Students
WHERE program = 'BSIT';

SELECT *
FROM Students
WHERE year_level = 1;

SELECT *
FROM Students
ORDER BY program, last_name;

6.6 Step 5: Practice JOINs

Write queries to:

  1. Show each enrollment with student name, course name, and grade.
  2. Show all courses taken by “Maria Santos”.

Example:


SELECT
    s.first_name,
    s.last_name,
    c.course_name,
    e.grade
FROM Enrollments e
JOIN Students s ON e.student_id = s.student_id
JOIN Courses  c ON e.course_id  = c.course_id;

SELECT
    s.first_name,
    s.last_name,
    c.course_name,
    e.grade
FROM Enrollments e
JOIN Students s ON e.student_id = s.student_id
JOIN Courses  c ON e.course_id  = c.course_id
WHERE s.first_name = 'Maria'
  AND s.last_name  = 'Santos';

6.7 Step 6: Modify Data

Try:

  1. Change Maria’s year level to 2.
  2. Change Juan’s grade in Database Systems to 'A'.
  3. Delete Ana’s enrollment.

Examples:


UPDATE Students
SET year_level = 2
WHERE student_id = 1001;

UPDATE Enrollments
SET grade = 'A'
WHERE student_id = 1002
  AND course_id  = 1;

DELETE FROM Enrollments
WHERE enrollment_id = 4;

Re-run SELECT queries to see changes.

6.8 Make It a Routine

Practice idea:
30–45 minutes per session.
Each session:
1. Review concepts (5–10 minutes).
2. Write and run SQL (20–30 minutes).
3. Reflect or fix errors (5–10 minutes).

You learn databases mainly by doing, not by just reading.

7. Common Lab Activities Explained

7.1 Lab: Design an ER Diagram

Task:
Given a scenario (e.g., “university enrollment system”), identify:
Entities (Student, Course, Instructor, Enrollment, etc.).
Attributes (student_id, name, etc.).
Relationships (Student–Enrollment–Course).

Approach:

  1. Read the scenario carefully.
  2. Underline nouns → possible entities.
  3. For each entity, list attributes.
  4. Identify relationships:
    Does one student enroll in many courses?
    Does one course have many students?
  5. Draw the ERD:
    Boxes for entities.
    Lines for relationships.
    Indicate cardinality (1:1, 1:N, M:N).

7.2 Lab: Convert ERD to Tables

Task: Given an ERD, create CREATE TABLE statements.

Steps:

  1. For each entity:
    Create a table.
    Choose a primary key.
    List columns with data types.
  2. For each relationship:
    If 1:N: put a foreign key in the N side.
    If M:N: create a new table with two foreign keys.

Example:
ERD: Student (1) — (∞) Enrollment (∞) — (1) Course
Becomes:
Students table
Courses table
Enrollments table with student_id, course_id as FKs.

7.3 Lab: Create Tables in SQL

Typical tasks:
Create tables with primary and foreign keys.
Add constraints like NOT NULL, UNIQUE, and CHECK.

Tips:
Start simple; add constraints step by step.
If you get errors, check spelling and references.

7.4 Lab: Insert and Query Data

Tasks:
Insert multiple rows into tables.
Write SELECT queries with:
WHERE, ORDER BY, JOINs, simple conditions (AND, OR, comparison operators).

Tips:
Start with SELECT * FROM table; to understand the data.
Add filters one by one.
Test your query logic with a small data set.

7.5 Lab: Update and Delete

Tasks:
Modify existing records using UPDATE.
Remove records using DELETE.

Warnings:
Always use WHERE.
Run SELECT first to see which rows will be affected.

7.6 Lab: Simple Reports

Tasks:
“List all students with their total number of enrolled courses.”
“List courses and how many students are enrolled in each one.”

These require:
JOINs, GROUP BY, aggregate functions (COUNT, AVG, SUM).

Example:


SELECT
    s.student_id,
    s.first_name,
    s.last_name,
    COUNT(e.course_id) AS num_courses
FROM Students s
LEFT JOIN Enrollments e ON s.student_id = e.student_id
GROUP BY s.student_id, s.first_name, s.last_name;

7.7 How to Use GPT in Labs (Without Cheating Yourself)

When your instructor says “use GPT,” treat it as a tutor, not a solution generator.

Good use:
“Explain why my foreign key constraint is failing.”
“Help me understand this error message.”

Bad use:
“Write my entire lab answer for me.” (You will not learn.)

Strategy:

  1. Try to solve first.
  2. When stuck, show GPT:
    Your attempt.
    The error.
    The goal.
  3. Ask for explanation, not just final code.

8. Advanced Concepts

8.1 Indexes

Indexes make data retrieval faster, like an index in a book.
Usually built on columns frequently used in WHERE or JOIN.
Primary keys are often indexed automatically.

Example:

CREATE INDEX idx_students_program
ON Students(program);

Effect:
Queries like WHERE program = 'BSIT' become faster (especially on large tables).
Downside: Slightly slower INSERT/UPDATE because indexes must be updated.

8.2 Transactions and ACID

A transaction is a group of SQL operations that should be treated as a single unit.

ACID properties:

  • Atomicity: All or nothing.
  • Consistency: Database rules are never broken.
  • Isolation: Concurrent transactions don’t interfere incorrectly.
  • Durability: Once committed, changes persist even after a crash.

Example (pseudocode):


BEGIN;

UPDATE Accounts SET balance = balance - 500 WHERE account_id = 1;
UPDATE Accounts SET balance = balance + 500 WHERE account_id = 2;

COMMIT;

If something fails after the first UPDATE, the transaction can be rolled back, preventing half-finished changes.

8.3 Views

A view is a virtual table based on a query.
Looks like a table.
Does not store data itself (usually).
Simplifies complex queries.
Can hide certain columns for security.

Example:


CREATE VIEW StudentGrades AS
SELECT
    s.student_id,
    s.first_name,
    s.last_name,
    c.course_name,
    e.grade
FROM Enrollments e
JOIN Students s ON e.student_id = s.student_id
JOIN Courses  c ON e.course_id  = c.course_id;

Then:

SELECT * FROM StudentGrades WHERE last_name = 'Santos';

8.4 Stored Procedures and Functions (Brief)

Stored Procedure: A saved SQL program inside the database.
Function: Similar to procedures, can return a value and be used in SQL expressions.

They:
Encapsulate complex logic.
Can improve performance in some cases.
Are often used in larger systems.

As a beginner, it is enough to know they exist.

8.5 Security Basics

Databases often manage:
Users, Roles, Permissions (who can do what).

Example actions:
Granting a user permission to read but not write.
Restricting access to sensitive tables (e.g., salaries).

SQL examples (conceptual):


GRANT SELECT ON Students TO student_user;
REVOKE UPDATE ON Students FROM student_user;

8.6 Backup and Recovery

Real systems must:
Regularly back up data to prevent loss.
Have a plan to restore data after failure.

You may not do this in basic labs, but it is crucial in real-world applications.

9. Common Errors & Solutions

You will make mistakes; that is normal. What matters is learning to fix them.

9.1 Syntax Errors

Examples:
Missing comma.
Using wrong keyword.
Unmatched parentheses.

Error messages:
“You have an error in your SQL syntax near …” (MySQL)
“Syntax error at or near…” (PostgreSQL)

How to fix:

  1. Read the error carefully; note the line number.
  2. Check for:
    Missing ,
    Extra or missing (
    Misspelled keywords (SELEC instead of SELECT).

9.2 Wrong Table or Column Names

Example:

SELECT firstname FROM Students;

But the column is first_name.

Fix:
Check the actual table definition (DESCRIBE Students; or \d Students; depending on DB).
Use correct names.

9.3 Foreign Key Constraint Fails

Error example:
“Cannot add or update a child row: a foreign key constraint fails.”

Causes:
You are inserting into a child table using a foreign key that does not exist in the parent table.

Example:


INSERT INTO Enrollments (enrollment_id, student_id, course_id, grade)
VALUES (10, 9999, 1, 'A');  -- student 9999 does not exist

Fix:
Insert the parent row first (Students row for 9999) or use an existing student_id.

9.4 Data Type Mismatch

Examples:
Inserting text into an integer column.
Date in wrong format.

Example:


INSERT INTO Students (student_id, first_name)
VALUES ('abc', 'Maria');  -- student_id expects INT

Fix:
Check column types.
Convert data to correct type.

9.5 Logical Errors (Query Runs but Is Wrong)

Query runs without error, but result is not what you expected.

Example:


-- Intention: Students in year 1 and BSIT
SELECT * FROM Students
WHERE year_level = 1 OR program = 'BSIT';   -- should be AND

Fix:
Rethink the logic.
Test with small test data.
Add conditions step by step.

9.6 Forgetting WHERE in UPDATE/DELETE

Example:


UPDATE Students SET year_level = 2;  -- changes all students!
DELETE FROM Students;                 -- deletes all students!

Fix:
Always double-check for WHERE.
You can first run a SELECT with the same WHERE to see affected rows:


SELECT * FROM Students WHERE year_level = 1;
UPDATE Students SET year_level = 2 WHERE year_level = 1;

9.7 General Debugging Strategy

  1. Read the error fully.
  2. Check table and column names.
  3. Simplify the query:
    Remove joins or conditions; add them back gradually.
  4. Print out sample data with SELECT * FROM table;.
  5. If still stuck, ask for help:
    Show full query.
    Show table structure.
    Show exact error message.

10. Career Path & Next Steps

Databases are everywhere in IT. Understanding them opens many doors.

10.1 Roles Related to Databases

  • Database Administrator (DBA)
    Manages the database servers.
    Focus: performance, security, backups, availability.
  • Backend Developer
    Builds the server-side of applications.
    Uses SQL to store and retrieve data.
  • Data Engineer
    Designs and builds data pipelines.
    Works with databases, big data tools, ETL processes.
  • Business Intelligence (BI) Developer / Analyst
    Creates reports and dashboards.
    Uses SQL to analyze company data.
  • Full-Stack Developer
    Works on both front-end and back-end.
    Needs at least basic SQL and database knowledge.

10.2 Skills to Build After This Guide

Once you understand fundamentals:

  1. Go deeper into SQL:
    Joins, subqueries, group functions, window functions (later).
  2. Practice database design:
    More complex ERDs.
    Normalization up to 3NF.
  3. Learn one DBMS well:
    MySQL or PostgreSQL are good choices.
  4. Connect databases with code:
    Using Java, C#, Python, PHP, or JavaScript.

10.3 Building a Simple Portfolio

Project ideas:

  • Student Enrollment System:
    Tables: Students, Courses, Enrollments, Instructors.
  • Library Management System:
    Tables: Books, Members, Loans.
  • Simple Online Store:
    Tables: Products, Customers, Orders, OrderItems.

For each:
Design ERD.
Create tables in SQL.
Insert sample data.
Write meaningful queries (reports).
If possible, build a small web or desktop interface that uses your database.

10.4 Using This as a Learning Path

Suggested order:

  1. Read sections 1–5 slowly.
  2. Do the Hands-On Practice (section 6).
  3. Review Common Lab Activities (section 7) while doing your school labs.
  4. When you hit errors, jump to section 9.
  5. Once comfortable, read section 8 (Advanced) and experiment.
  6. Use section 10 to plan further learning and projects.

11. Premium Resources

Here “premium” means high-quality resources (many are free).

11.1 Documentation and Tutorials

Official docs are always valuable:

Beginner tutorials:

11.2 Interactive Practice Sites

11.3 Video Courses / Playlists

Look for:
“SQL for Beginners”, “Relational Databases for Beginners” on:

  • YouTube (many full free courses)
  • freeCodeCamp (long-form free courses)
  • Khan Academy (intro to SQL)

Pick one series and follow it step by step, practicing as you go.

11.4 Books (For Deeper Study)

Beginner-friendly:

  • “Sams Teach Yourself SQL in 10 Minutes” by Ben Forta
  • “Learning SQL” by Alan Beaulieu

More advanced/theoretical:

  • “Database System Concepts” (Silberschatz, Korth, Sudarshan)

You do not need the advanced books right away, but they are good references later.

11.5 How to Use Resources Effectively

  1. Don’t just watch or read—type the SQL yourself.
  2. Take notes:
    New commands
    Examples
    Mistakes you made and how you fixed them
  3. Teach a classmate or explain to yourself out loud:
    If you can explain it, you really understand it.

Friday, November 21, 2014

ACT 113 Syllabus


I.             Course Name                     : Ethics in Information Technology
                                      
                                         
II.           Course Code                       : ACT 113

III.          Course Description            : This course will cover ethical issues regarding legal, privacy and intellectual property rights concerns and their application to information technology. It will give an overview of the subject aimed at raising students’ awareness about ethics in Information Technology and in research. It will include case studies to target specific IT fields such as ethics in business and in the workplace. 

IV.         Course Credit                    : 3 units lecture

V.           Contact Hours/Semester  : 54 lecture hours

VI.         Placement                          : 1st  Year, 1st  Semester

VII.       Course Objectives              : At the end of this course, students shall

be able to:
1.   Describe and evaluate consequences of computing on individuals, organizations and society;
2.   Critically analyze situations of computer use and technology and policy proposals and
3.   Discuss philosophical frameworks of ethics.

VIII.     COURSE REQUIREMENTS        


A.   Written Requirements

1.   Compilation of class activities
2.   Learning log

IX.        TEACHING METHODOLOGIES

1.   Lecture Discussion
2.   Group Dynamics

X.          EVALUATION PARAMETERS

1.   Classroom

1.1 Class Standing ---------------------------------------------------------2/3

1.1.1   Quizzes --------------------------------------------90%
1.1.2   Group Work and other activities-------------10%
1.2 Long Term Examination-----------------------------------------------1/3

            Final MG                                : PL+TMG/2=FMG

            Final Term Grade                 : FMG+TFG/2

XI.        Course Outline

Lesson No.
Topic/Content
Time Frame/
No. of Hours






Lesson 1


Lesson 2









Lesson 3




Lesson 4
Lesson 5

Lesson 6
Lesson 7



Lesson 8


Prelim

I.             Ethics

A.   What is Ethics

1.   Definition
2.   The Importance of Integrity

    B.  Ethics in the Business World
          1. Why Fostering Good Business Ethics is
              Important
          2.Improving Corporate Ethics
          3.When Good Ethics Result in Short
             Term Losses
          4.Creating an Ethical Work Environment
          5.Ethical Decision Making
        
    
C.Ethics in Information Technology

II.           Ethics for IT Professionals and IT Users

A.   IT Professionals
B.   The Ethical Behavior of IT Professionals
C.   Ethical Professional Malpractice
D.  IT Users

III.         Computer and Internet Crime

A.   IT Security Incidents: A Worsening Problem
B.   Reducing Vulnerabilities







1


2









1




1
1

1
1



2

3.5




Lesson 9


Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17





Lesson 18

Lesson 19
Lesson 20
Lesson 21
Lesson 22
 Midterm

I.             Privacy

A.   Privacy Protection and the Law

B.   Key Privacy and Anonymity Issues
1.   Governmental Electronic Surveillance
2.   Data Encryption
3.   Identity Theft
4.   Consumer Profiling
5.   Treating Consumer Data Responsibly
6.   Workplace Monitoring
7.   Spamming
8.   Advanced Surveillance Technology

II.           Freedom of Expression

A.   Freedom of Expression: Key Issues

1.   Controlling Access to Information on the Internet
2.   Anonymity
3.   National Security Letters
4.   Defamation and Hate Speech
5.   Pornography





1


1
1
1
1
1
1
1
1





1

1
1
1
1.5




Lesson 23







Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28



Lesson 29
Lesson 30
 Semi Final
 
III.         Intellectual Property

A.   Definition

1.   Copyrights
2.   Patents
3.   Trade Secret Laws

B.   Key Intellectual Property Issues

1.Plagiarism
2.Reverse Engineering
3.Open Source Code
4.Competitive Intelligence
5. Cybersquatting

IV.         Software Development

A.   Strategies to Engineer Quality Software
B.   Key Issues in Software Development






1








1
1
1
1
1


3.5
3.5




Lesson 31




Lesson 32




Lesson 33




Lesson 34
Lesson 35

Lesson 36
Final

V.           Employer/Employee Issues

A.   Use of Non Traditional Workers
1.   Contingent Workers
2.   H-1B Workers
3.   Offshore Outsourcing

B.   Whistle-Blowing

VI.         The Impact of Information Technology on the Quality of Life

A.   The Impact of IT on the Standard of Living and Productivity

B.   The Impact of IT on Healthcare Costs

1.   Electronic Health Records
2.   Use of Mobile and Wireless Technology
3.   Telemedicine





2




2




2




2
2

3.5


REFERENCES
Books
  Reynolds, G. (2009). Ethics in Information Technology.
  Philippines:  MG Reprographics, Inc.
 

REMINDERS:
1.   Submission of all course requirements should be on time.
2.   Complete attendance is a must.

Prepared by:

CENDRYL F. MOLINA