0% found this document useful (0 votes)
17 views16 pages

DB Practical Summary

The document is a comprehensive guide on SQL covering various topics such as data retrieval, modification, joins, subqueries, set operations, and views. It includes syntax examples and explanations for each SQL command, illustrating how to manage and manipulate relational databases effectively. The content is structured into sections that progressively build on SQL concepts, making it a useful resource for learning and reference.

Uploaded by

hudaaghazi22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views16 pages

DB Practical Summary

The document is a comprehensive guide on SQL covering various topics such as data retrieval, modification, joins, subqueries, set operations, and views. It includes syntax examples and explanations for each SQL command, illustrating how to manage and manipulate relational databases effectively. The content is structured into sections that progressively build on SQL concepts, making it a useful resource for learning and reference.

Uploaded by

hudaaghazi22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Database Final Practical

May 9, 2025

Contents

1 Introduction to SQL 2

2 Basic Data Retrieval 3

3 Aggregate Functions and Grouping 5

4 Data Modification 6

5 Joins and Multi-table Queries 8

6 Subqueries 11

7 Set Operations 12

8 Views and View Constraints 14

9 ALTER TABLE and Referential Integrity 16

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.

Writing SQL Commands


Conventions:

• Upper-case: Reserved SQL keywords.

• Lower-case: User-defined elements (table/column names).

• |: Choice.

• {}: Required.

• [] : Optional.

• ... : Optional repetition.

2
Hevar 2 BASIC DATA RETRIEVAL

2 Basic Data Retrieval


SELECT Statement
Basic SELECT syntax retrieves data:
1 SELECT * FROM Staff ;
2 SELECT staffNo , fName , lName FROM Staff ;

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.

Comparison and Compound Conditions


1 -- OR , AND , NOT
2 SELECT * FROM Branch WHERE city = ’ London ’ OR city = ’ Glasgow ’;
3 SELECT * FROM Staff WHERE NOT salary < 5000;

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).

BETWEEN, IN, LIKE


1 -- Range
2 SELECT * FROM Staff WHERE salary BETWEEN 20000 AND 30000;
3
4 -- Multiple values
5 SELECT * FROM Staff WHERE position IN ( ’ Manager ’ , ’ Supervisor ’) ;
6
7 -- Pattern match
8 SELECT * FROM PrivateOwner WHERE address LIKE ’% Glasgow % ’;

3
Hevar 2 BASIC DATA RETRIEVAL

Explanation:

• BETWEEN finds employees with salaries from $20,000 to $30,000 inclusive


(both bounds included).

• IN checks if the position column equals any value in the list, efficiently replacing
multiple OR conditions.

• LIKE with % wildcards searches for addresses containing ”Glasgow” anywhere


in the text. The % matches zero or more characters.

% matches multiple characters, matches a single character.

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

3 Aggregate Functions and Grouping


Aggregate Functions
• COUNT()

• SUM()

• AVG()

• MIN()

• MAX()

1 SELECT COUNT (*) FROM PropertyForRent WHERE rent > 350;


2 SELECT AVG ( salary ) FROM Staff ;
3 SELECT MAX ( salary ) FROM Staff ;

Explanation:

• COUNT(*) counts the number of properties with rent exceeding $350.

• AVG(salary) calculates the average salary across all staff members.

• MAX(salary) finds the highest salary among all staff members.

• All these aggregate functions operate on sets of rows and return a single value.

GROUP BY and HAVING


1 SELECT branchNo , COUNT ( staffNo ) AS myCount , SUM ( salary ) AS mySum
2 FROM Staff
3 GROUP BY branchNo
4 HAVING COUNT ( staffNo ) > 1;

Explanation: This complex query:

• Groups staff records by branch number

• Counts the number of staff in each branch (aliased as ’myCount’)

• Sums the salaries for each branch (aliased as ’mySum’)

• 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.

• The DATE keyword specifies a date literal format.

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.

• Without a WHERE clause, UPDATE modifies all rows in the table.

DELETE
1 -- Delete specific row
2 DELETE FROM Viewing WHERE propertyNo = ’ PG4 ’;
3

4 -- Delete all rows


5 DELETE FROM Viewing ;

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.

• Be very careful with DELETE without WHERE - it cannot be undone unless


you have transaction control!

7
Hevar 5 JOINS AND MULTI-TABLE QUERIES

5 Joins and Multi-table Queries


Inner Join (Implicit Syntax)
1 SELECT c . clientNo , fName , lName , propertyNo , comment
2 FROM Client c , Viewing v
3 WHERE c . clientNo = v . clientNo ;

Explanation: This query performs an inner join between Client (aliased as ’c’)
and Viewing (aliased as ’v’) tables:

• It connects records where the clientNo matches in both tables

• It returns client information alongside their property viewings

• Table aliases (c, v) provide shorter references to 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

Modern JOIN Syntax


1 -- Inner join ( equivalent to previous example )
2 SELECT c . clientNo , fName , lName , propertyNo , comment
3 FROM Client c
4 INNER JOIN Viewing v ON c . clientNo = v . clientNo ;
5
6 -- Left outer join
7 SELECT s . staffNo , s . fName , s . lName , p . propertyNo , p . street
8 FROM Staff s
9 LEFT JOIN PropertyForRent p ON s . staffNo = p . staffNo ;
10
11 -- Right outer join
12 SELECT s . staffNo , s . fName , s . lName , p . propertyNo , p . street
13 FROM Staff s
14 RIGHT JOIN PropertyForRent p ON s . staffNo = p . staffNo ;
15

16 -- Full outer join


17 SELECT s . staffNo , s . fName , s . lName , p . propertyNo , p . street
18 FROM Staff s
19 FULL JOIN PropertyForRent p ON s . staffNo = p . staffNo ;

Explanation: Modern SQL provides explicit JOIN syntax:

• 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

pear with NULL property values.

• 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:

• Links Branch to Staff via branchNo

• Links Staff to PropertyForRent via staffNo

• Returns branch location, staff details, and the properties they handle

• Uses table aliases (b, s, p) for brevity

This creates a complete view of which properties are managed by which staff members
at which branches.

Modern Multi-table JOIN


1 SELECT b . branchNo , b . city , s . staffNo , s . fName , s . lName , p . propertyNo
2 FROM Branch b
3 INNER JOIN Staff s ON b . branchNo = s . branchNo
4 INNER JOIN PropertyForRent p ON s . staffNo = p . staffNo ;

Explanation: This is the modern equivalent of the three-table join above:

• It uses explicit INNER JOIN syntax instead of implicit WHERE joins

• Joins are processed sequentially (first Branch to Staff, then their result to
PropertyForRent)

• The join conditions are clearly separated in the ON clauses

• The result is identical to the implicit join version

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.

Subquery with Aggregate


1 SELECT staffNo , fName , lName , position , salary - 17000 AS salDiff
2 FROM Staff
3 WHERE salary > (
4 SELECT AVG ( salary ) FROM Staff
5 );

Explanation: This query demonstrates a subquery with an aggregate function:

• The subquery calculates the average salary across all staff

• The main query selects only employees with above-average salaries

• 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 ;

Explanation: The UNION operation:

• Combines results from both queries into a single result set

• Automatically removes duplicates (cities appearing in both tables appear only


once)

• 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 ;

Explanation: The INTERSECT operation:

• Returns only cities that appear in both result sets

• Shows cities where the company has both branches and properties for rent

• Acts like a logical AND between the two queries

• Returns a unique set of values (no duplicates)

This is useful for finding overlaps between two data sets.

EXCEPT
1 SELECT city FROM Branch
2 EXCEPT
3 SELECT city FROM PropertyForRent ;

Explanation: The EXCEPT operation (also called MINUS in some databases):

• Returns cities from the first query that do not exist in the second query

12
Hevar 7 SET OPERATIONS

• Shows cities where the company has branches but no properties

• Acts like set subtraction (first set minus second set)

• Is useful for finding what’s in one table but not another

This can help identify market opportunities (cities with branches but no properties).

13
Hevar 8 VIEWS AND VIEW CONSTRAINTS

8 Views and View Constraints


Create View
1 CREATE VIEW Manager3Staff AS
2 SELECT * FROM Staff WHERE branchNo = ’ B003 ’;

Explanation: This statement creates a virtual table (view) named ’Manager3Staff’:

• The view contains only staff from branch ’B003’

• It appears as a table but stores only the query definition, not data

• When queried, it executes the underlying SELECT statement dynamically

• Views provide security (column/row restriction) and simplify complex queries

You can query this view like a table: SELECT * FROM Manager3Staff

With Column List and Aggregates


1 CREATE VIEW StaffPropCnt ( branchNo , staffNo , cnt ) AS
2 SELECT s . branchNo , s . staffNo , COUNT (*)
3 FROM Staff s , PropertyForRent p
4 WHERE s . staffNo = p . staffNo
5 GROUP BY s . branchNo , s . staffNo ;

Explanation: This view creation statement:

• Defines explicit column names (branchNo, staffNo, cnt) for the view

• Counts properties managed by each staff member

• Uses a join between Staff and PropertyForRent tables

• Groups results by both branch and staff number

• Creates a summary/aggregate view (contains computed data)

The column list is especially important for aggregate views to name computed columns
like COUNT(*).

WITH CHECK OPTION


1 CREATE VIEW Manager3Staff AS
2 SELECT * FROM Staff WHERE branchNo = ’ B003 ’
3 WITH CHECK OPTION ;

14
Hevar 8 VIEWS AND VIEW CONSTRAINTS

Explanation: The WITH CHECK OPTION clause:

• Ensures data integrity when modifying data through the view

• 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:

• No DISTINCT, aggregates, GROUP BY, HAVING

• FROM clause refers to one base table

15
Hevar 9 ALTER TABLE AND REFERENTIAL INTEGRITY

9 ALTER TABLE and Referential Integrity


ALTER Commands
1 ALTER TABLE staff ADD address varchar (200) ;
2 ALTER TABLE staff DROP COLUMN address ;
3 ALTER TABLE staff ALTER COLUMN address SET DEFAULT ’ Erbil ’;
4 ALTER TABLE staff RENAME TO newStaff ;

Explanation: These ALTER TABLE statements modify the table structure:

• The first adds a new ’address’ column with VARCHAR(200) data type

• The second removes the ’address’ column completely

• The third changes the default value of ’address’ to ’Erbil’

• The fourth renames the entire table from ’staff’ to ’newStaff’

Note that some operations (like dropping columns) may not be supported in all SQL
implementations.

Add Foreign Key with ON DELETE


1 ALTER TABLE Staff
2 ADD CONSTRAINT SBF FOREIGN KEY ( BranchNo )
3 REFERENCES Branch ( BranchNo )
4 ON DELETE CASCADE ;

Explanation: This statement adds a foreign key constraint:

• Creates a named constraint ’SBF’ on the Staff table

• Establishes that BranchNo in Staff must match a BranchNo in Branch

• Specifies that if a branch is deleted, all associated staff records are automatically
deleted

• This enforces referential integrity between tables

The ON DELETE CASCADE option propagates deletions to maintain database


consistency.

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

You might also like