DB Practical Summary
DB Practical Summary
May 9, 2025
Contents
1 Introduction to SQL 2
4 Data Modification 6
6 Subqueries 11
7 Set Operations 12
1
Hevar 1 INTRODUCTION TO SQL
1 Introduction to SQL
Purpose of SQL
Structured Query Language (SQL) is used to manage and manipulate relational databases.
It is divided into two major parts:
• DDL (Data Definition Language) – for creating and modifying schema structures
like tables, views, and constraints.
• DML (Data Manipulation Language) – for data manipulation operations like SE-
LECT, INSERT, UPDATE, DELETE.
• |: Choice.
• {}: Required.
• [] : Optional.
2
Hevar 2 BASIC DATA RETRIEVAL
Explanation:
• The first query retrieves all columns (using the * wildcard) from the Staff
table, showing complete employee records.
• The second query retrieves only specific columns (staffNo, fName, lName)
from the Staff table, showing just employee IDs and names.
WHERE Clause
Filters records that meet a condition:
1 SELECT * FROM Staff WHERE salary > 10000;
Explanation: This query retrieves all columns for employees whose salary exceeds
$10,000. The WHERE clause applies this filtering condition before returning results,
reducing the result set to only matching records.
Explanation:
• The first query uses the OR operator to retrieve branches located in either
London OR Glasgow.
• The second query uses NOT to invert a condition, retrieving staff members
whose salary is NOT less than 5000 (equivalent to salary ¿= 5000).
3
Hevar 2 BASIC DATA RETRIEVAL
Explanation:
• IN checks if the position column equals any value in the list, efficiently replacing
multiple OR conditions.
NULL Handling
1 SELECT * FROM Staff WHERE DOB IS NULL ;
2 SELECT * FROM Staff WHERE salary IS NOT NULL ;
Explanation:
• The first query finds staff with no birth date recorded (DOB is NULL).
• The second query finds staff with known salaries (salary is not NULL).
• Note that NULL values require special operators (IS NULL, IS NOT NULL)
because NULL represents unknown values, not empty strings or zeros.
ORDER BY
1 SELECT * FROM Staff ORDER BY salary DESC ;
Explanation: This query retrieves all staff records sorted by salary in descending
order (highest to lowest). The default sort is ascending (ASC), but DESC reverses
the order. You can sort by multiple columns by listing them with commas.
DISTINCT
Eliminates duplicates:
1 SELECT DISTINCT propertyNo FROM Viewing ;
Explanation: This query returns a list of unique property numbers that have been
viewed. The DISTINCT keyword removes duplicate values from the result set,
showing each property number only once regardless of how many viewings it had.
4
Hevar 3 AGGREGATE FUNCTIONS AND GROUPING
• SUM()
• AVG()
• MIN()
• MAX()
Explanation:
• All these aggregate functions operate on sets of rows and return a single value.
• Uses HAVING to filter out branches with only one staff member
• Returns results only for branches with more than one employee
Unlike WHERE (which filters individual rows), HAVING filters groups after aggre-
gation.
5
Hevar 4 DATA MODIFICATION
4 Data Modification
INSERT
1 -- Full column list
2 INSERT INTO Staff
3 VALUES ( ’ SG16 ’ , ’ Alan ’ , ’ Brown ’ , ’ Assistant ’ , ’M ’ , DATE ’ 1957 -05 -25 ’ ,
8300 , ’ B003 ’) ;
4
5 -- Specific columns only
6 INSERT INTO Staff ( staffNo , fName , lName , position , salary , branchNo )
7 VALUES ( ’ SG44 ’ , ’ Anne ’ , ’ Jones ’ , ’ Assistant ’ , 8100 , ’ B003 ’) ;
Explanation:
• The first query inserts a complete row with values for all columns in the order
they appear in the table definition.
• The second query inserts a row with values for only specified columns.
Unspecified columns will receive NULL values or their default values if defined.
UPDATE
1 -- Update all rows
2 UPDATE Staff SET salary = salary * 1.03;
3
4 -- Conditional update
5 UPDATE Staff SET position = ’ Manager ’ , salary = 18000 WHERE staffNo = ’
SG14 ’;
Explanation:
• The first query gives a 3% salary increase to all employees by multiplying the
current salary by 1.03.
• The second query modifies only one specific employee (identified by staffNo
’SG14’), changing both their position and salary in a single statement.
DELETE
1 -- Delete specific row
2 DELETE FROM Viewing WHERE propertyNo = ’ PG4 ’;
3
6
Hevar 4 DATA MODIFICATION
Explanation:
• The first query removes only the viewings for property ’PG4’, leaving other
viewing records intact.
• The second query (with no WHERE clause) removes all records from the
Viewing table, leaving an empty table structure.
7
Hevar 5 JOINS AND MULTI-TABLE QUERIES
Explanation: This query performs an inner join between Client (aliased as ’c’)
and Viewing (aliased as ’v’) tables:
• This syntax is called ”implicit join” because the join condition is in the WHERE
clause
The modern equivalent would be: FROM Client c JOIN Viewing v ON c.clientNo
= v.clientNo
• INNER JOIN: Returns only rows where there are matches in both tables. In
the example, it returns clients who have viewings.
• LEFT JOIN: Returns all rows from the left table (Staff), plus matches from
the right table (PropertyForRent). Staff members without properties still ap-
8
Hevar 5 JOINS AND MULTI-TABLE QUERIES
• RIGHT JOIN: Returns all rows from the right table (PropertyForRent), plus
matches from the left table (Staff). Properties without assigned staff still ap-
pear with NULL staff values.
• FULL JOIN: Returns all rows when there is a match in either the left or right
table. Shows all staff and all properties, with NULL values when there’s no
match.
JOIN syntax is preferred over implicit joins for clarity and to separate join conditions
from filtering conditions.
Three-table Join
1 SELECT b . branchNo , b . city , s . staffNo , fName , lName , propertyNo
2 FROM Branch b , Staff s , PropertyForRent p
3 WHERE b . branchNo = s . branchNo AND s . staffNo = p . staffNo ;
Explanation: This query joins three tables to connect branch, staff, and property
information:
• Returns branch location, staff details, and the properties they handle
This creates a complete view of which properties are managed by which staff members
at which branches.
• Joins are processed sequentially (first Branch to Staff, then their result to
PropertyForRent)
9
Hevar 5 JOINS AND MULTI-TABLE QUERIES
• This syntax is more readable when dealing with complex joins and multiple
tables
You can mix different join types (LEFT, RIGHT, INNER) in multi-table joins as
needed.
10
Hevar 6 SUBQUERIES
6 Subqueries
Subquery with Equality
1 SELECT staffNo , fName , lName , position
2 FROM Staff
3 WHERE branchNo = (
4 SELECT branchNo FROM Branch WHERE street = ’ 163 Main St ’
5 );
Explanation: This query uses a subquery to find staff who work at a specific
branch location:
• The inner query (subquery) finds the branchNo for ’163 Main St’
• The outer query selects staff details where their branchNo matches this value
• This approach is useful when you don’t know the branch number but know its
address
• The equals operator (=) implies the subquery must return exactly one value
Subqueries make queries more readable and maintainable compared to complex joins.
• It also calculates how much each selected employee earns above $17,000, creat-
ing a computed column ’salDiff’
• Column aliases (AS salDiff) name computed expressions for easier reference
This type of query is useful for identifying top performers or outliers in the data.
11
Hevar 7 SET OPERATIONS
7 Set Operations
UNION
1 SELECT city FROM Branch
2 UNION
3 SELECT city FROM PropertyForRent ;
• Requires both queries to have compatible columns (same number and data
types)
• Returns all cities where either branches exist or properties are available
Use UNION ALL instead if you want to keep duplicates (for better performance).
INTERSECT
1 SELECT city FROM Branch
2 INTERSECT
3 SELECT city FROM PropertyForRent ;
• Shows cities where the company has both branches and properties for rent
EXCEPT
1 SELECT city FROM Branch
2 EXCEPT
3 SELECT city FROM PropertyForRent ;
• Returns cities from the first query that do not exist in the second query
12
Hevar 7 SET OPERATIONS
This can help identify market opportunities (cities with branches but no properties).
13
Hevar 8 VIEWS AND VIEW CONSTRAINTS
• It appears as a table but stores only the query definition, not data
You can query this view like a table: SELECT * FROM Manager3Staff
• Defines explicit column names (branchNo, staffNo, cnt) for the view
The column list is especially important for aggregate views to name computed columns
like COUNT(*).
14
Hevar 8 VIEWS AND VIEW CONSTRAINTS
• Prevents inserts or updates that would create rows not visible through the view
• For example, it prevents adding staff with branchNo other than ’B003’
• Makes sure all view operations comply with the view’s WHERE clause
This ensures that the view remains consistent with its definition.
Updatability Rules
View is updatable if:
15
Hevar 9 ALTER TABLE AND REFERENTIAL INTEGRITY
• The first adds a new ’address’ column with VARCHAR(200) data type
Note that some operations (like dropping columns) may not be supported in all SQL
implementations.
• Specifies that if a branch is deleted, all associated staff records are automatically
deleted
ON DELETE/UPDATE Options
• CASCADE: Deletes child rows
• SET NULL: Sets FK to NULL (if allowed)
• SET DEFAULT: Sets FK to its default value
• NO ACTION: Prevents deletion if dependencies exist
16