SQL Database Course
SQL Tutorial - Full Database Course for Beginners
This guide compiles everything needed to get started with SQL and relational databases. The material covers database fundamentals, SQL language basics, installation, table creation, data manipulation, queries, functions, joins, triggers, and database design using ER diagrams.
What Is a Database?
A database is any collection of related information. Examples include a phonebook, a shopping list, a to‑do list, your five best friends, or Facebook’s entire user base. Databases can be stored on paper, in your mind, or on a computer.
Computers are especially good for storing databases because they can handle massive amounts of data, provide security, and allow easy backup and duplication. For large‑scale applications (like Amazon), a computer‑based database is essential.
Database Management Systems (DBMS)
A database management system (DBMS) is special software that helps users create, maintain, and secure a database on a computer. It handles:
Storing large volumes of data
Security (user authentication, access control)
Backup and import/export
Interaction with other software applications
The four core operations performed with a DBMS are known as CRUD:
Create – add new data
Read – retrieve data
Update – modify existing data
Delete – remove data
Two Main Types of Databases
Relational Database (SQL Database)
Organizes data into one or more tables with columns and rows. Each row has a unique key (primary key) that identifies it. Relational databases are the most popular type and are managed by a Relational Database Management System (RDBMS). They use SQL (Structured Query Language) to perform CRUD and administrative tasks.
Popular RDBMS examples: MySQL, Oracle, PostgreSQL, MariaDB.Non‑Relational Database (NoSQL Database)
Any database that is not relational. Data can be stored as:Documents (JSON, XML)
Graphs (nodes and edges)
Key‑value stores (hash maps)
No standard language like SQL exists across all NoSQL systems; each implements its own.
Popular NoSQL examples: MongoDB, DynamoDB, Apache Cassandra, Firebase.
Queries
A query is a request made to the DBMS for specific information. As a database schema grows complex, querying becomes essential to retrieve exactly what is needed without pulling all data. Queries are written in SQL (for relational) or the system’s specific language.
Tables and Keys in Relational Databases
Table Structure
A table consists of columns (attributes) and rows (records). Each column represents a single piece of information, and each row is a complete entry.
Primary Key
A primary key is a column (or set of columns) that uniquely identifies each row in the table. It must be both NOT NULL and UNIQUE.
Natural key: has meaning in the real world (e.g., Social Security Number).
Surrogate key: has no real‑world meaning (e.g., an auto‑incrementing integer).
Foreign Key
A foreign key is an attribute in one table that references the primary key of another table. It defines a relationship between the two tables. A table can have multiple foreign keys, and they can even point back to the same table (self‑referencing, e.g., supervisor ID).
Composite Key
A composite key (or compound key) is a primary key that consists of two or more columns. This is necessary when no single column can uniquely identify a row.
SQL Basics
SQL (Structured Query Language) is the language used to interact with relational database management systems. It is a hybrid language that serves four purposes:
Data Query Language (DQL) – retrieve data (SELECT)
Data Definition Language (DDL) – define schemas (CREATE, ALTER, DROP)
Data Control Language (DCL) – manage users and permissions (GRANT, REVOKE)
Data Manipulation Language (DML) – insert, update, delete (INSERT, UPDATE, DELETE)
SQL implementations can vary slightly between RDBMS products (e.g., MySQL vs. PostgreSQL), but the core commands are standardized.
Installation Notes (Summary)
Windows Installation
Download MySQL Community Server (installer). Choose “Custom” installation and install MySQL Server and MySQL Shell.
Set a root password during configuration.
Use MySQL 5.7 Command Line Client to log in and create a database:
CREATE DATABASE giraffe;Optionally install PopSQL (a query editor) to connect to the database and write SQL visually.
Mac Installation
Download MySQL Community Server (DMG Archive). Save the temporary root password shown after installation.
Start MySQL from System Preferences.
Use Terminal to add MySQL to PATH:
echo 'export PATH="/usr/local/mysql/bin:$PATH"' >> ~/.bash_profile
Then reload withsource ~/.bash_profile.Log in:
mysql -u root -p(enter temporary password). Then change the password:ALTER USER 'root'@'localhost' IDENTIFIED BY 'newpassword';Create a database:
CREATE DATABASE giraffe;Install PopSQL and connect using host
localhost, port3306, databasegiraffe, userroot, and the new password.
Creating Tables
Basic Data Types
INT – whole numbers (no decimals)
DECIMAL(M, N) – decimal numbers;
M= total digits,N= digits after decimalVARCHAR(n) – variable‑length string (up to
ncharacters)BLOB – Binary Large Object (stores binary data like images/files)
DATE – date in format
YYYY‑MM‑DDTIMESTAMP – date and time:
YYYY‑MM‑DD HH:MI:SS
Creating a Table
Syntax:
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
PRIMARY KEY (column_name)
);Constraints include NOT NULL, UNIQUE, DEFAULT, and AUTO_INCREMENT.
Altering and Dropping Tables
-- Add a column
ALTER TABLE student ADD gpa DECIMAL(3,2);
-- Drop a column
ALTER TABLE student DROP COLUMN gpa;
-- Delete an entire table
DROP TABLE student;Inserting Data
Basic Insert
INSERT INTO student VALUES (1, 'Jack', 'Biology');Order of values must match the table’s column order.
Specifying Columns
INSERT INTO student (student_id, name) VALUES (3, 'Claire');Columns not listed will be set to NULL or their default value.
Duplicate Primary Keys
Attempting to insert a row with an existing primary key value will cause a duplicate entry error.
Constraints
Constraints enforce rules on columns during table creation:
NOT NULL – column cannot contain NULL.
UNIQUE – all values in the column must be different.
DEFAULT – provides a default value if none is supplied (e.g.,
'undecided').AUTO_INCREMENT – automatically generates a unique integer for each new row (commonly used for surrogate primary keys).
Updating and Deleting Data
UPDATE
UPDATE student
SET major = 'Bio'
WHERE major = 'Biology';The
WHEREclause is optional; omitting it updates all rows.Multiple columns can be set at once:
SET name = 'Tom', major = 'undecided'.Complex conditions using
AND,OR, etc.
DELETE
DELETE FROM student
WHERE student_id = 5;Without
WHERE, all rows in the table are deleted.WHEREsupports the same logical operators as UPDATE.
Basic Queries (SELECT)
Selecting Columns
SELECT * FROM student; -- all columns
SELECT name, major FROM student; -- specific columns
SELECT student.name, student.major FROM student; -- prefixed with table nameOrdering Results
SELECT * FROM student ORDER BY name; -- ascending (default)
SELECT * FROM student ORDER BY name DESC; -- descending
SELECT * FROM student ORDER BY major, student_id; -- multiple criteriaLimiting Results
SELECT * FROM student LIMIT 2;Filtering with WHERE
SELECT * FROM student WHERE major = 'Biology';
SELECT * FROM student WHERE student_id < 3 AND name <> 'Jack';Using IN
SELECT * FROM student WHERE name IN ('Claire', 'Kate', 'Mike');DISTINCT
SELECT DISTINCT sex FROM employee;Aliases (AS)
SELECT first_name AS forename, last_name AS surname FROM employee;Company Database Schema
A more complex schema was introduced for learning advanced queries. It includes these tables (refer to the PDF linked in the original course for the full diagram):
Employee:
emp_id,first_name,last_name,birth_day,sex,salary,super_id,branch_idBranch:
branch_id,branch_name,mgr_id,mgr_start_dateClient:
client_id,client_name,branch_idWorks_With:
emp_id,client_id,total_sales(composite primary key)Branch_Supplier:
branch_id,supplier_name,supply_type(composite primary key)
Foreign keys link these tables. Because of circular dependencies, data insertion must be done in a specific order (e.g., insert employee with NULL branch, then branch, then update employee).
More Advanced Queries
Functions
COUNT(column)– counts non‑NULL values.AVG(column)– average of numeric values.SUM(column)– total sum.Use with
WHEREfor filtered calculations.
Aggregation with GROUP BY
SELECT sex, COUNT(sex) FROM employee GROUP BY sex;This shows the count of males and females.
Wildcards and LIKE
%– any number of characters (including zero)._– exactly one character.
SELECT * FROM client WHERE client_name LIKE '%LLC';
SELECT * FROM employee WHERE birth_date LIKE '____-10%'; -- born in OctoberUNION
Combines results from multiple SELECT statements into one column set.
All
SELECTstatements must have the same number of columns.Columns must have compatible data types.
SELECT first_name FROM employee
UNION
SELECT branch_name FROM branch;JOINs
Combine rows from two or more tables based on a related column.
INNER JOIN (default
JOIN) – returns only rows where the condition matches.LEFT JOIN – includes all rows from the left table, even if no match.
RIGHT JOIN – includes all rows from the right table, even if no match.
FULL OUTER JOIN – not supported in MySQL; combines left and right.
Example:
SELECT employee.emp_id, employee.first_name, branch.branch_name
FROM employee
JOIN branch ON employee.emp_id = branch.mgr_id;Nested Queries
Use the result of one SELECT inside another.
SELECT first_name, last_name
FROM employee
WHERE emp_id IN (
SELECT emp_id FROM works_with WHERE total_sales > 30000
);ON DELETE Actions
When a row referenced by a foreign key is deleted, you can define what happens:
ON DELETE SET NULL – sets the foreign key column to
NULL. Used when the foreign key is not part of the primary key.ON DELETE CASCADE – deletes the entire row that contains the foreign key. Used when the foreign key is part of the primary key (composite key) or when total deletion is appropriate.
Example:
FOREIGN KEY (mgr_id) REFERENCES employee(emp_id) ON DELETE SET NULLTriggers
A trigger is a block of SQL code that automatically executes when a specified event occurs (INSERT, UPDATE, DELETE) on a table.
In MySQL, triggers require changing the delimiter:
DELIMITER $$
CREATE TRIGGER my_trigger
BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
INSERT INTO trigger_test VALUES('added new employee');
END $$
DELIMITER ;Triggers can also:
Access the new row using
NEW.column_name.Use conditionals (
IF,ELSEIF,ELSE).Be set to
AFTERinstead ofBEFORE.Be dropped with
DROP TRIGGER trigger_name;
ER Diagrams (Entity‑Relationship Diagrams)
An ER diagram is a visual tool used to design a database schema from data requirements. It acts as a bridge between business requirements and actual database tables.
Components
Entity (rectangle) – an object to model (e.g., Student, Course).
Attribute (oval) – a property of an entity.
Primary key (underlined) – uniquely identifies each instance.
Composite attribute – attribute that can be subdivided (e.g., Name into First Name, Last Name).
Multi‑valued attribute – double oval (e.g., Clubs).
Derived attribute – dashed oval (e.g., Age derived from Birth Date).
Relationship (diamond) – a verb connecting entities.
Participation: single line = partial (not all instances must participate); double line = total (all instances must participate).
Cardinality: 1:1, 1:N, M:N (also written as N:M).
Weak Entity (double rectangle) – cannot exist without a related entity. Its primary key is partially derived from the owner’s primary key. The identifying relationship is shown with a double diamond.
Designing from Requirements
Steps to create an ER diagram:
Identify entities from nouns in the requirements.
Identify attributes and primary keys.
Identify relationships (verbs) and their cardinalities and participations.
Mark weak entities if needed.
Converting ER Diagrams to Database Schemas
Five basic mapping steps:
Regular Entity Types – Each regular entity becomes a table. Include all simple attributes. The primary key of the entity becomes the table’s primary key.
Weak Entity Types – Create a table for the weak entity. The primary key is the combination of the weak entity’s partial key and the primary key of its owner.
Binary 1:1 Relationships – Add the primary key of one side as a foreign key in the other. Favor the table with total participation.
Binary 1:N Relationships – Add the primary key of the “1” side as a foreign key in the “N” side’s table.
Binary M:N Relationships – Create a new table whose primary key is a composite of both entity primary keys. Include any relationship attributes as columns.
Following these steps on the company ER diagram produces the relational schema described earlier (Employee, Branch, Client, Works_With, Branch_Supplier). The resulting tables can then be created using SQL CREATE TABLE statements.
Mastering these fundamentals allows you to design, create, query, and manage relational databases effectively. Practice writing queries against the company database schema to reinforce all concepts.

Ask anything
We've read this whole study set, so questions about it get the best answers.