first commit
This commit is contained in:
@@ -0,0 +1 @@
|
||||
XɁ<EFBFBD>ƈ<EFBFBD><EFBFBD><EFBFBD>};<EFBFBD><EFBFBD><EFBFBD>&<EFBFBD>x<EFBFBD>'ɍ<EFBFBD><EFBFBD><EFBFBD><EFBFBD> <EFBFBD>eő+<EFBFBD>uOr<EFBFBD>=<EFBFBD><EFBFBD><EFBFBD>
|
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"folders": {},
|
||||
"connections": {
|
||||
"postgres-jdbc-18bb8d14e3a-4b7a96932eaa0782": {
|
||||
"provider": "postgresql",
|
||||
"driver": "postgres-jdbc",
|
||||
"name": "postgres",
|
||||
"save-password": true,
|
||||
"configuration": {
|
||||
"host": "localhost",
|
||||
"port": "5432",
|
||||
"database": "postgres",
|
||||
"url": "jdbc:postgresql://localhost:5432/postgres",
|
||||
"configurationType": "MANUAL",
|
||||
"type": "dev",
|
||||
"properties": {
|
||||
"connectTimeout": "20",
|
||||
"loginTimeout": "20",
|
||||
"escapeSyntaxCallMode": "callIfNoReturn"
|
||||
},
|
||||
"provider-properties": {
|
||||
"@dbeaver-show-non-default-db@": "false",
|
||||
"@dbeaver-show-template-db@": "false",
|
||||
"@dbeaver-show-unavailable-db@": "false",
|
||||
"show-database-statistics": "false",
|
||||
"@dbeaver-read-all-data-types-db@": "false",
|
||||
"read-keys-with-columns": "false",
|
||||
"@dbeaver-use-prepared-statements-db@": "false",
|
||||
"postgresql.dd.plain.string": "false",
|
||||
"postgresql.dd.tag.string": "false"
|
||||
},
|
||||
"auth-model": "native",
|
||||
"handlers": {}
|
||||
}
|
||||
}
|
||||
},
|
||||
"connection-types": {
|
||||
"dev": {
|
||||
"name": "Development",
|
||||
"color": "255,255,255",
|
||||
"description": "Regular development database",
|
||||
"auto-commit": true,
|
||||
"confirm-execute": false,
|
||||
"confirm-data-change": false,
|
||||
"smart-commit": false,
|
||||
"smart-commit-recover": false,
|
||||
"auto-close-transactions": true,
|
||||
"close-transactions-period": 1800
|
||||
}
|
||||
}
|
||||
}
|
12
Semester 1/DatabaseBackup/Assignment/.project
Normal file
12
Semester 1/DatabaseBackup/Assignment/.project
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<projectDescription>
|
||||
<name>Assignment1</name>
|
||||
<comment></comment>
|
||||
<projects>
|
||||
</projects>
|
||||
<buildSpec>
|
||||
</buildSpec>
|
||||
<natures>
|
||||
<nature>org.jkiss.dbeaver.DBeaverNature</nature>
|
||||
</natures>
|
||||
</projectDescription>
|
19772
Semester 1/DatabaseBackup/Exercise Booklet.pdf
Normal file
19772
Semester 1/DatabaseBackup/Exercise Booklet.pdf
Normal file
File diff suppressed because one or more lines are too long
BIN
Semester 1/DatabaseBackup/NorthWindTraders.accdb
Normal file
BIN
Semester 1/DatabaseBackup/NorthWindTraders.accdb
Normal file
Binary file not shown.
BIN
Semester 1/DatabaseBackup/Week 1/Test.db.odb
Normal file
BIN
Semester 1/DatabaseBackup/Week 1/Test.db.odb
Normal file
Binary file not shown.
BIN
Semester 1/DatabaseBackup/Week 1/Test.db.odb.lck
Normal file
BIN
Semester 1/DatabaseBackup/Week 1/Test.db.odb.lck
Normal file
Binary file not shown.
165
Semester 1/DatabaseBackup/Week 1/Week 1 Database Systems.md
Normal file
165
Semester 1/DatabaseBackup/Week 1/Week 1 Database Systems.md
Normal file
@@ -0,0 +1,165 @@
|
||||
## Lecture 1 (13:00) Organisation
|
||||
|
||||
### 32741 ( Module Code )
|
||||
|
||||
### Module Information
|
||||
|
||||
- 67 hours of private study across all modules in semester 1
|
||||
- Exercise booklet on blackboard
|
||||
- Semester 1 Coursework 50%
|
||||
- Semester 2 Coursework 50%
|
||||
|
||||
### Reading
|
||||
|
||||
- Preface, C.1 & C.2 of exercise booklet.
|
||||
|
||||
## Lecture 2 (15:00) Introduction
|
||||
|
||||
### Applications of Databases
|
||||
|
||||
- Supermarket
|
||||
- Barcode DB
|
||||
- Price Retrieval
|
||||
- Stock Control
|
||||
- Credit Card
|
||||
- Credit Limit Check
|
||||
- Security Check
|
||||
- Other
|
||||
- Library
|
||||
- Websites
|
||||
|
||||
### File-Based Systems
|
||||
|
||||
- Attempt to digitise information
|
||||
- Collection of application programs
|
||||
- Each performs a front end interface
|
||||
- Each manages and defines its own data
|
||||
- Limitations lay the foundations to what we have now
|
||||
|
||||
#### Limitations
|
||||
|
||||
- **Separation** and **isolation** of data
|
||||
- **Incompatible** file formats
|
||||
- **Fixed queries** (written by the developer, not the end user) / proliferation of application programs
|
||||
- Data **duplication**
|
||||
- Costs money and time to enter data multiple times
|
||||
- **individual**, **independent** instances of data
|
||||
- Additional storage space taken
|
||||
- **Loss of data integrity** and parity (consistency lost), since they are individual sources of data.
|
||||
- Ex. Payroll and Personnel data duplicated across DB
|
||||
- Data **dependence**
|
||||
- **Physical structure** / storage of data / records is defined in **application code**
|
||||
- Difficult to change structure
|
||||
- Programs have to be modified if structure needs changing
|
||||
|
||||
### Databases
|
||||
|
||||
- Shared collection of **logically related** data (+ **description**), designed to fit needs.
|
||||
- **Self-describing** collection of integrated records
|
||||
|
||||
#### Database System
|
||||
|
||||
1. Collection of data stored on files
|
||||
2. Database Management System ( Interface )
|
||||
3. Variety of users
|
||||
|
||||
### Database Management System
|
||||
|
||||
- Software that enables the **creation**, **definition**, and **maintenance** of databases. and provides **controlled access**.
|
||||
- User Interaction is provided through User Programs (Queries), examples of include:
|
||||
- Add Data
|
||||
- Delete Data
|
||||
- Update Data
|
||||
- Retrieve Data
|
||||
|
||||
#### Functions of DBMS
|
||||
|
||||
- Data Integration
|
||||
- Stored **efficiently**
|
||||
- Minimises **duplication** and **redundancy**
|
||||
- Data Integrity
|
||||
- No **corruption** or **inconsistency**
|
||||
- Data Security
|
||||
- Data is not lost or made inconsistent through system failures, or through deliberate corruption.
|
||||
- Data Independence
|
||||
- **Isolates users** from physical data
|
||||
- User has logical model interface of database
|
||||
|
||||
#### Users of a DB Environment
|
||||
|
||||
- Data Admin
|
||||
- Consults and advises senior management
|
||||
- Ensures database serves its purpose
|
||||
- Database Admin
|
||||
- Technically oriented
|
||||
- Ultimate control over data structure and access
|
||||
- Database Designers
|
||||
- Designs structure of database to cater to needs
|
||||
- Application Programmers
|
||||
- Designers of end user applications
|
||||
- End Users
|
||||
- Clients who require access to the database
|
||||
- No control over function of the applications
|
||||
- May have little to no knowledge on back-end
|
||||
|
||||
#### Advantages over File-Based
|
||||
|
||||
- **De-Duplication**
|
||||
- Lowers risk of inconsistency
|
||||
- More users share more data
|
||||
- Improved **Security**
|
||||
- Improved **accessibility** and **responsiveness**
|
||||
- Department boundaries crossed, data is **no longer independent**
|
||||
- Provides **query** language
|
||||
- **On-demand** access
|
||||
- Improved **productivity**
|
||||
- Provides many standard functions programmers would have to hard code
|
||||
- Improved **maintenance**
|
||||
- Separates data descriptions from applications
|
||||
- Improved **backup** and **recovery**
|
||||
|
||||
#### Disadvantages
|
||||
|
||||
- **Complicated**
|
||||
- **Large** / Heavy
|
||||
- **Expensive** setup
|
||||
- May incur **additional storage** space
|
||||
- **Cost** of conversion
|
||||
- **Performance** may not be as good as file-based
|
||||
- Higher **impact of failure**
|
||||
|
||||
### Relational DBMS
|
||||
|
||||
- Dominant DBMS in use
|
||||
- Estimated sales of $15-20m/year
|
||||
- Established in 1970
|
||||
- Simple logical structure
|
||||
|
||||
#### Relational DB
|
||||
|
||||
- Stored in files called relations (tables)
|
||||
- Consists of rows and columns
|
||||
- Carries data on one kind of entity ex. Cars
|
||||
- Commonly addressed as entity-name(attributes). Ex. Cars(Model, Age, Colour)
|
||||
- Primary Key - The identifying attribute of a table. Ex. Registration Plate (Unique)
|
||||
- Goal is to remove as much redundant data as possible.
|
||||
- Foreign Key - another unique key to provide an index to another table.
|
||||
- Attribute that is linked to the primary key of another table
|
||||
|
||||
### Reading
|
||||
|
||||
- C.1 Connolly & Begg (2014 & 2004)
|
||||
|
||||
## Workshop 1 (9:00)
|
||||
|
||||
```
|
||||
SELECT *
|
||||
FROM [Customers];
|
||||
WHERE [Country] = "Germany";
|
||||
```
|
||||
|
||||
```
|
||||
SELECT *
|
||||
FROM [Customers];
|
||||
WHERE [Country] = "Germany" AND [ContactTitle] = "Sales Representative";
|
||||
```
|
31
Semester 1/DatabaseBackup/Week 2/Week 2 Database Systems.md
Normal file
31
Semester 1/DatabaseBackup/Week 2/Week 2 Database Systems.md
Normal file
@@ -0,0 +1,31 @@
|
||||
## Lecture 1
|
||||
|
||||
## Lecture 2
|
||||
|
||||
## Workshop 1 (9:00) - More SQL Queries
|
||||
|
||||
### Single-Table Queries
|
||||
|
||||
1. Display names and quantities of products in the database. Sort the results in order
|
||||
of increasing quantity.
|
||||

|
||||
2. Display the names and addresses of companies who are customers from France.
|
||||

|
||||
3. Display the contact names of customers who are from UK and whose contact title
|
||||
is “Sales Representative”.
|
||||

|
||||
|
||||
### Multi-Table Queries
|
||||
|
||||
1. List the names of the products which are supplied by a supplier in Manchester.
|
||||

|
||||
2. List the names and telephone numbers of shippers who have shipped orders to
|
||||
Bern.
|
||||

|
||||
|
||||
5.3.3
|
||||
Challenge Question
|
||||
There are just five orders in which both the customer and employee come from the same
|
||||
city. These five orders involve just two cities. Write an SQL query which lists the names
|
||||
of these cities.
|
||||

|
339
Semester 1/DatabaseBackup/Week 3/Week 3 Database Systems.md
Normal file
339
Semester 1/DatabaseBackup/Week 3/Week 3 Database Systems.md
Normal file
@@ -0,0 +1,339 @@
|
||||
## Lecture 1 (13:00) - More SQL
|
||||
|
||||
### Attribute Alias
|
||||
|
||||
```sql
|
||||
SELECT driverID AS DriverNumber
|
||||
FROM Drivers;
|
||||
```
|
||||
|
||||
### Distinct
|
||||
|
||||
```sql
|
||||
SELECT address FROM Drivers WHERE DriverID IN (D020, D030)
|
||||
```
|
||||
|
||||
#### Output:
|
||||
|
||||
| address |
|
||||
|---------|
|
||||
| Dundee |
|
||||
| Dundee |
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT address FROM Drivers WHERE DriverID IN (D020, D030)
|
||||
```
|
||||
|
||||
#### Output:
|
||||
|
||||
| address |
|
||||
|---------|
|
||||
| Dundee |
|
||||
|
||||
### Aggregate Functions
|
||||
|
||||
- **sum()** - Adds all inputs
|
||||
- **avg()** - Mean average of all inputs
|
||||
- **count()** - Count total records of input
|
||||
- **max()** - Get maximum value of inputs
|
||||
- **min()** - Get minimum value of inputs
|
||||
|
||||
### Group By
|
||||
|
||||
```sql
|
||||
SELECT address, COUNT(niNo)
|
||||
FROM Employees
|
||||
GROUP BY address;
|
||||
```
|
||||
|
||||
#### Output:
|
||||
|
||||
| Address | count(niNo) |
|
||||
|---------|--------------|
|
||||
| Aberdeen | 2 |
|
||||
| Dundee | 2 |
|
||||
| Stirling | 1 |
|
||||
|
||||
### Having Clause
|
||||
|
||||
- Used with group by to filter groups / rows
|
||||
|
||||
```sql
|
||||
SELECT <attributes>, <column functions>
|
||||
FROM <tables>
|
||||
WHERE <conditions> //Optional
|
||||
GROUP BY <attributes>
|
||||
HAVING <conditions>;
|
||||
```
|
||||
|
||||

|
||||
|
||||
```sql
|
||||
SELECT address, AVG(salary)
|
||||
FROM Employees
|
||||
GROUP BY address
|
||||
HAVING AVG(salary) > 21000;
|
||||
```
|
||||
|
||||
#### Output:
|
||||
|
||||
| address | avg(salary) |
|
||||
|---|----|
|
||||
| Dundee | 22500 |
|
||||
|
||||
### Having Vs. Where
|
||||
|
||||
- **WHERE** removes rows *before* grouping
|
||||
- **HAVING** filters groups
|
||||
- Aggregate functions cannot be used with the **WHERE** clause.
|
||||
|
||||
### Update Queries
|
||||
|
||||
- Allows you to change the values of attributes of existing rows ( tuples ) of a table
|
||||
|
||||
```sql
|
||||
UPDATE <table>
|
||||
SET <attribute assignments>
|
||||
WHERE <conditions>; //optional
|
||||
```
|
||||
|
||||
```sql
|
||||
UPDATE Drivers
|
||||
SET points = 6
|
||||
WHERE driverID = "D040";
|
||||
```
|
||||
|
||||
#### Output:
|
||||
|
||||

|
||||
|
||||
```sql
|
||||
UPDATE Drivers
|
||||
SET address = "Salford"
|
||||
WHERE driverID = "D020";
|
||||
```
|
||||
|
||||

|
||||
|
||||
### Delete Queries
|
||||
|
||||
- Deletes whole rows ( tuples ), not individual values
|
||||
|
||||
```sql
|
||||
DELETE FROM <table name>
|
||||
WHERE <conditions>; //optional
|
||||
```
|
||||
|
||||
```sql
|
||||
DELETE FROM Drivers
|
||||
WHERE points > 10;
|
||||
```
|
||||
|
||||
#### Output
|
||||
|
||||

|
||||
|
||||
### Insert Queries
|
||||
|
||||
- Adds data to existing table without deleting it or any records
|
||||
|
||||
```sql
|
||||
INSERT INTO <table name> <attribute list> //optional
|
||||
SELECT <statement> | VALUES <value list>;
|
||||
```
|
||||
|
||||
```sql
|
||||
INSERT INTO Drivers
|
||||
VALUES ("D060", "Betty", "Inverness", 6);
|
||||
```
|
||||
|
||||
#### Output
|
||||
|
||||

|
||||
|
||||
```sql
|
||||
INSERT INTO Drivers (driverID, name)
|
||||
VALUES ("D070", "Jeannie")
|
||||
```
|
||||
|
||||
#### Output
|
||||
|
||||

|
||||
|
||||
## Lecture 2 (15:00) - More SQL
|
||||
|
||||
### Data Types
|
||||
|
||||
```sql
|
||||
CHARACTER(L)
|
||||
```
|
||||
|
||||
- Fixed length character string containing L letters. Fewer characters are used as padding.
|
||||
|
||||
```sql
|
||||
CHARACTER VARYING(L)
|
||||
```
|
||||
|
||||
- Variable length character string that holds up to L characters. No padding.
|
||||
|
||||
```sql
|
||||
INTEGER(L)
|
||||
```
|
||||
|
||||
- Signed whole number.
|
||||
|
||||
```sql
|
||||
NUMERIC(P,S)
|
||||
```
|
||||
|
||||
- P = Precision. Total number of digits
|
||||
- S = Scale. Number of digits to correct decimal place.
|
||||
- Ex. NUMERIC(5,2) is `-999.99` to `999.99`
|
||||
|
||||
```sql
|
||||
DATE YYYY-MM-DD
|
||||
```
|
||||
|
||||
- YYYY = `1` to `9999`
|
||||
- MM = `1` to `12`
|
||||
- DD = `1` to `31
|
||||
|
||||
```sql
|
||||
TIME HH:MM:SS
|
||||
```
|
||||
|
||||
- HH = Hours
|
||||
- MM = Minutes
|
||||
- SS = Seconds
|
||||
|
||||
```sql
|
||||
TIMESTAMP YYYY-MM-DD HH:MM:SS
|
||||
```
|
||||
|
||||
- Combination of DATE and TIME
|
||||
|
||||
```sql
|
||||
INTERVAL
|
||||
```
|
||||
|
||||
- Refers to period of time. May have value such as `90 days`. Also known as a span
|
||||
|
||||
```sql
|
||||
BINARY LARGE OBJECT(L)
|
||||
```
|
||||
|
||||
- Large, variable length binary string that can hold up to L bytes. Also known as `BLOB`
|
||||
|
||||
```sql
|
||||
BOOLEAN
|
||||
```
|
||||
|
||||
- Value of TRUE or FALSE
|
||||
|
||||
```sql
|
||||
NULL
|
||||
```
|
||||
|
||||
- Value of unknown, valid for any data type.
|
||||
|
||||
#### Exercise
|
||||
|
||||
1. CHAR
|
||||
2. DATE
|
||||
3. BOOLEAN
|
||||
4. INTEGER
|
||||
5. NUMERIC
|
||||
6. CHAR(10) = Bryant____
|
||||
7. VARCHAR(10) = Bryant
|
||||
8. INTEGER can have the value NULL
|
||||
|
||||
### Exercise on Data Types and Keys
|
||||
|
||||
1. Book
|
||||
1. ISBN - VARCHAR
|
||||
2. Title - VARCHAR
|
||||
3. Author - VARCHAR
|
||||
2. Members
|
||||
1. MemID - CHAR
|
||||
2. Name - VARCHAR
|
||||
3. Age - INTEGER
|
||||
4. Address - VARCHAR
|
||||
5. Phone - VARCHAR
|
||||
3. Loan
|
||||
1. LoanID - CHAR
|
||||
2. ISBN ( Foreign Key )
|
||||
3. MemID ( Foreign Key )
|
||||
4. LoanDate - DATE
|
||||
5. ReturnDate - DATE
|
||||
|
||||
### Exercise on Adding, Deleting and Modifying Data
|
||||
|
||||
1. Append tuple to pirates table
|
||||
|
||||
```SQL
|
||||
INSERT INTO Pirates
|
||||
VALUES ("p5", "Pegleg", 1, 2, "Spain");
|
||||
```
|
||||
|
||||
```SQL
|
||||
INSERT INTO Boats (boat-code, boat-name, origin)
|
||||
VALUES ("b9", "Swift", "British");
|
||||
```
|
||||
|
||||
```SQL
|
||||
INSERT INTO Booty
|
||||
VALUES ("bt13", "Flour", 8);
|
||||
```
|
||||
|
||||
1. Change the name of Booty "bt8" from "nothing" to "infected animals"
|
||||
|
||||
```sql
|
||||
UPDATE Booty
|
||||
SET booty-name = "Infected Animals"
|
||||
WHERE booty-code = "bt8";
|
||||
```
|
||||
|
||||
1. Remove b7 from the boats table
|
||||
|
||||
```sql
|
||||
DELETE FROM Boats
|
||||
WHERE boat-code = "b7";
|
||||
```
|
||||
|
||||
### Exercise on Aggregating Results
|
||||
|
||||
#### Exercise
|
||||
|
||||
1. Calculate total value of all booty in booty table
|
||||
|
||||
```sql
|
||||
SELECT SUM(value)
|
||||
FROM booty;
|
||||
```
|
||||
|
||||
1. List each type of boat, with the number of boats with that type
|
||||
|
||||
```sql
|
||||
SELECT boat-type, COUNT (boat-code)
|
||||
FROM boats;
|
||||
```
|
||||
|
||||
- Remember comma between select and aggregate functions
|
||||
|
||||
## Workshop 1 (10:00)
|
||||
|
||||

|
||||
|
||||
1. List the unit price of the cheapest product.
|
||||

|
||||
2. What is the total value of all the products?
|
||||

|
||||
3. How many products have been discontinued?
|
||||

|
||||
4. What is the average unit price of the products which have been discontinued?
|
||||

|
||||
5. Display the name of every supplier and the total number of products supplied by
|
||||
that company.
|
||||

|
||||
6. Display total number of orders for each employee.
|
||||

|
@@ -0,0 +1,254 @@
|
||||
## Lecture 1 (13:00)
|
||||
|
||||
### Intro
|
||||
|
||||
- Create relations `CREATE TABLE`
|
||||
- Modify relations `ALTER TABLE`
|
||||
- Destroy relations `DROP TABLE`
|
||||
|
||||
### Common Datatypes
|
||||
|
||||
- **CHARACTER(L)** / **CHAR(L)**
|
||||
- Fixed length containing L letters
|
||||
- Fewer characters, padded with (usually) spaces
|
||||
- **CHARACTER VARYING(L)** / **VARCHAR(L)**
|
||||
- Variable length string that may hold up to L characters
|
||||
- No padding
|
||||
- **INTEGER** / **INT**
|
||||
- Signed whole number
|
||||
- Range of possible values is dependant on the DBMS
|
||||
- **NUMERIC(P,S)**
|
||||
- Signed, fixed point number
|
||||
- P = Precision (# Digits)
|
||||
- S = Scale (# Digits to the right of decimal place)
|
||||
- `NUMERIC(5,2) = -999.99 to 999.99`
|
||||
- **BOOLEAN**
|
||||
- 3 values - TRUE, FALSE, UNKNOWN
|
||||
- **DATE**
|
||||
- YYYY-MM-DD
|
||||
- **TIME**
|
||||
- HH:MM:SS
|
||||
- **TIMESTAMP**
|
||||
- YYYY-MM-DD HH:MM:SS
|
||||
- **INTERVAL**
|
||||
- Refers to period of time. ex. Time Span.
|
||||
- **BINARY LARGE OBJECT(L)** / **BLOB(L)**
|
||||
- Large, variable length binary string up to L bytes of length
|
||||
- NULL
|
||||
- Indicates value is unknown
|
||||
- Valid for any data type
|
||||
|
||||
### Creating Tables
|
||||
|
||||
```sql
|
||||
CREATE TABLE <table name> (
|
||||
<column name> <data type> [<default value>] [<column constraint>],
|
||||
<column name> <data type> [<default value>] [<column constraint>],
|
||||
...
|
||||
...
|
||||
[<table constraint1>],
|
||||
[<table constraint2>],
|
||||
...
|
||||
);
|
||||
```
|
||||
|
||||
#### Examples
|
||||
|
||||
```sql
|
||||
CREATE TABLE students (
|
||||
studentID INTEGER,
|
||||
title VARCHAR(4),
|
||||
name VARCHAR(20),
|
||||
city VARCHAR(20)
|
||||
);
|
||||
```
|
||||
|
||||
```sql
|
||||
CREATE TABLE courses (
|
||||
courseID CHAR(4),
|
||||
courseName VARCHAR(20),
|
||||
startDate DATE,
|
||||
endDate DATE
|
||||
);
|
||||
```
|
||||
|
||||
#### Default Values
|
||||
|
||||
- When using `INSERT`, any columns without a specified value are assigned to default
|
||||
- Unless specified, default value is **NULL**
|
||||
- By specifying `DEFAULT <value expression>` in `CREATE TABLE`, we can assign default values
|
||||
|
||||
```sql
|
||||
CREATE TABLE courses (
|
||||
courseID CHAR(4) DEFAULT ("XXXX")
|
||||
...
|
||||
);
|
||||
```
|
||||
|
||||
#### Constraints
|
||||
|
||||
- **NOT NULL**
|
||||
- Prohibits NULL from being the value in a column
|
||||
|
||||
```sql
|
||||
CREATE TABLE students (
|
||||
...
|
||||
name varchar(20) NOT NULL,
|
||||
...
|
||||
);
|
||||
```
|
||||
|
||||
This example shows that any values in the column `name` must not be NULL
|
||||
|
||||
- **UNIQUE**
|
||||
- Forces distinct column values.
|
||||
- Allows NULL values
|
||||
|
||||
```sql
|
||||
CREATE TABLE employee (
|
||||
...
|
||||
niNumber CHAR(11) UNIQUE,
|
||||
...
|
||||
);
|
||||
```
|
||||
|
||||
This example shows that every value in the column `niNumber` must be unique.
|
||||
|
||||
- **PRIMARY KEY**
|
||||
- Uniquely identifies a tuple (row) in the table.
|
||||
- May not be NULL.
|
||||
|
||||
```sql
|
||||
CREATE TABLE employee (
|
||||
employeeID INTEGER PRIMARY KEY,
|
||||
...
|
||||
);
|
||||
```
|
||||
|
||||
This example shows that the column `employeeID` is the primary key of the table.
|
||||
|
||||
- **FOREIGN KEY**
|
||||
- References another table with a unique link
|
||||
|
||||
```sql
|
||||
CREATE TABLE students (
|
||||
studentID INTEGER PRIMARY KEY,
|
||||
...
|
||||
course CHAR(4) REFERENCES courses(courseID)
|
||||
);
|
||||
|
||||
CREATE TABLE courses (
|
||||
courseID CHAR(4) PRIMARY KEY,
|
||||
...
|
||||
)
|
||||
```
|
||||
|
||||
#### Naming Constraints
|
||||
|
||||
- **CONSTRAINT**
|
||||
- If a constraint violation occurs, the DBMS will notify which constraint was violated.
|
||||
- Constraints can be deleted by name.
|
||||
|
||||
```sql
|
||||
CONSTRAINT <constraint name> <constraint>
|
||||
```
|
||||
|
||||
```sql
|
||||
CREATE TABLE students (
|
||||
studID INTEGER CONSTRAINT student_pk PRIMARY KEY,
|
||||
title VARCHAR(4),
|
||||
name VARCHAR(20) CONSTRAINT name_not_null NOT NULL,
|
||||
city VARCHAR(20) CONSTRAINT city_default DEFAULT "Salford",
|
||||
course CHAR(4) CONSTRAINT student_fk REFERENCES courses(coursesID)
|
||||
);
|
||||
|
||||
CREATE TABLE courses (
|
||||
coursesID CHAR(4) CONSTRAINT course_pk PRIMARY KEY,
|
||||
courseName VARCHAR(20)
|
||||
...
|
||||
);
|
||||
```
|
||||
|
||||
#### Table Constraints
|
||||
|
||||
- Example of composite primary key: `supply(partID, supplierID)`
|
||||
- Multiple attributes cannot be assigned the constraint **PRIMARY KEY**, they must be assigned it in a list.
|
||||
|
||||
```sql
|
||||
CREATE TABLE supply (
|
||||
partID INTEGER,
|
||||
supplierID INTEGER,
|
||||
PRIMARY KEY (partID, supplierID)
|
||||
);
|
||||
```
|
||||
|
||||
### Exercise
|
||||
|
||||
```sql
|
||||
CREATE TABLE team (
|
||||
teamID CHAR(4) CONSTRAINT team_pk PRIMARY KEY,
|
||||
name VARCHAR(20) CONSTRAINT name_not_null NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
```sql
|
||||
CREATE TABLE member (
|
||||
memberID CHAR(4) CONSTRAINT member_pk PRIMARY KEY,
|
||||
niNumber CHAR(11) CONSTRAINT ni_unique UNIQUE,
|
||||
address VARCHAR(40) CONSTRAINT address_default DEFAULT "Salford",
|
||||
teamID CHAR(4) CONSTRAINT team_fk REFERENCES team(teamID)
|
||||
);
|
||||
```
|
||||
|
||||
## Lecture 2 (15:00)
|
||||
|
||||
#### Modifying Tables
|
||||
|
||||
```sql
|
||||
ALTER TABLE <table name>
|
||||
ADD <column name> <data type>;
|
||||
```
|
||||
|
||||
#### Destroying Tables
|
||||
|
||||
- Can be used with **\*** :)
|
||||
|
||||
```sql
|
||||
DROP TABLE <table name>;
|
||||
```
|
||||
|
||||
### 3 Areas of SQL
|
||||
|
||||
- Data Manipulation Language
|
||||
- Retrieve and modify data.
|
||||
- Data Description Language
|
||||
- Define structure of the data.
|
||||
- Data Control Language
|
||||
- Used to restrict access by certain users.
|
||||
|
||||
### Tutorial
|
||||
|
||||
```sql
|
||||
CREATE TABLE doctors (
|
||||
doctor-id CHAR(4) PRIMARY KEY,
|
||||
doctor-name VARCHAR(20) NOT NULL,
|
||||
telephone-number INTEGER(12) UNIQUE
|
||||
);
|
||||
|
||||
CREATE TABLE treats (
|
||||
treat-id CHAR(4) PRIMARY KEY,
|
||||
doctor-id CHAR(4) UNIQUE,
|
||||
patient-id CHAR(4) UNIQUE,
|
||||
drug VARCHAR(30),
|
||||
treatment-date DATE,
|
||||
FOREIGN KEY (doctor-id, patient-id)
|
||||
);
|
||||
|
||||
CREATE TABLE patients (
|
||||
patient-id CHAR(4) PRIMARY KEY,
|
||||
title CHAR(3),
|
||||
first-name VARCHAR(20) NOT NULL,
|
||||
surname VARCHAR(20) NOT NULL,
|
||||
address VARCHAR(30) DEFAULT ("Salford")
|
||||
);
|
||||
```
|
128
Semester 1/DatabaseBackup/Week 5/Week 5 Database Systems.md
Normal file
128
Semester 1/DatabaseBackup/Week 5/Week 5 Database Systems.md
Normal file
@@ -0,0 +1,128 @@
|
||||
## Lecture 1 (13:00) - Conceptual Modelling
|
||||
|
||||
### Role of Conceptual Modelling
|
||||
|
||||
- Real world problem -> Conceptual Model Data -> Logical Data Model -> Physical Model (DBMS)
|
||||
- Identify important concepts and data needs, creating a conceptual model.
|
||||
- Many different ways to get to the same solution.
|
||||
- Iterative process - if one method does not work, it can be revised.
|
||||
|
||||
### Conceptual Data Model
|
||||
|
||||
- Abstract view of situation.
|
||||
- Identifies important elements and relationships between them. (ex. Library: Books, Members, ~~Carpets~~)
|
||||
- Human interact-able, not computer terms.
|
||||
- Implementation Independent.
|
||||
- Useful for client brief.
|
||||
|
||||
### Reasons for Using ER Modelling
|
||||
|
||||
- Simpler and easier to understand than database tables
|
||||
- Helps discussions with clients and colleagues
|
||||
- Allows for segmentation of work.
|
||||
- Modelling real world solution
|
||||
- Designing DB tables
|
||||
- Most large organisations will require it
|
||||
|
||||
### Obtaining an ER Model
|
||||
|
||||
- Given a spec, you need to identify:
|
||||
- entities - 'things' with physical or conceptual existence
|
||||
- relationships
|
||||
- attributes
|
||||
- constraints or assumptions
|
||||
|
||||
#### Example
|
||||
|
||||
Departments control many projects and each department has many employees. Each employee works on only one project at a time. A project’s start date must be before the project’s target completion date. Each employee has an NI number, name and address
|
||||
|
||||
Entities:
|
||||
|
||||
- departments
|
||||
- projects
|
||||
- employees
|
||||
Relationships:
|
||||
- **control** between departments and projects
|
||||
- **has between** departments and employees
|
||||
- **works on** between employees and projects
|
||||
Attributes:
|
||||
- startdate
|
||||
- completiondate
|
||||
- ninumber
|
||||
- name
|
||||
- address
|
||||
Constraints:
|
||||
- Start date must be before the target completion date
|
||||
|
||||
### ER Diagram
|
||||
|
||||

|
||||
|
||||
- Many different notations
|
||||
- One is "crows foot":
|
||||

|
||||

|
||||

|
||||
|
||||
## Lecture 3 (16:00)
|
||||
|
||||
1. Generate a list of the ages of ATMs whose security level is normal. The list should be in descending order.
|
||||
|
||||
```sql
|
||||
SELECT age
|
||||
FROM atm
|
||||
WHERE security-level = "normal"
|
||||
ORDER BY age DESC;
|
||||
```
|
||||
|
||||
2. List the name of each bank which has a branch whose address starts with the word Eccles. The list should not include any duplicates.
|
||||
|
||||
```sql
|
||||
SELECT DISTINCT name
|
||||
FROM bank, branch
|
||||
WHERE Bank.bankID = Branch.bankID
|
||||
AND address LIKE "Eccles*";
|
||||
```
|
||||
|
||||
3. Calculate the average age of the ATMs with low or normal levels of security. Name the results column “Average age”.
|
||||
|
||||
```sql
|
||||
SELECT AVG(age) AS "Average Age"
|
||||
FROM atm
|
||||
WHERE security-level = "low" OR security-level = "normal";
|
||||
```
|
||||
|
||||
4. Remove the tuple from the relation ATM whose identifier is atm04.
|
||||
|
||||
```sql
|
||||
DELETE FROM atm
|
||||
WHERE atmID = "atm04";
|
||||
```
|
||||
|
||||
5. Add a row for an ATM, whose atmID is atm05, whose security level is high and which is located at branch T1.
|
||||
|
||||
```sql
|
||||
INSERT INTO atm
|
||||
VALUES ("atm05", "high", "0", "T1");
|
||||
```
|
||||
|
||||
6. Add an attribute called telephone number to the relation Branch.
|
||||
|
||||
```sql
|
||||
ALTER TABLE branch
|
||||
ADD telephone CHAR(15)
|
||||
```
|
||||
|
||||
7. Set the address of every branch to the value Salford.
|
||||
|
||||
```sql
|
||||
UPDATE branch
|
||||
SET address = "Salford";
|
||||
```
|
||||
|
||||
1) Bank LEFT OUTER JOIN Branch
|
||||
```sql
|
||||
SELECT *
|
||||
FROM bank
|
||||
INNER JOIN
|
||||
```
|
206
Semester 1/DatabaseBackup/Week 6/Week 6 Database Systems.md
Normal file
206
Semester 1/DatabaseBackup/Week 6/Week 6 Database Systems.md
Normal file
@@ -0,0 +1,206 @@
|
||||
## Lecture 1 (13:00)
|
||||
|
||||
### Candidate Key
|
||||
|
||||
- Attribute / Set of attributes that are:
|
||||
- Irreducible
|
||||
- A **Unique ID** for the rows in the table
|
||||
- If every attribute in the key is required to uniquely identify every row in the relation, it **is irreducible**.
|
||||
- If there is a subset of this set that uniquely identifies every row in the table, it **is reducible**.
|
||||
- **Primary Key** is the candidate key chosen to be the identifier.
|
||||
|
||||
#### Primary Key
|
||||
|
||||
- Many attributes may be required to form.
|
||||
|
||||
### Transforming ER to Relational
|
||||
|
||||
- Each entity transforms into a table with same attributes and primary key.
|
||||
- Each relationship transforms into either:
|
||||
- A foreign key in existing table.
|
||||
- New table, linked by foreign keys.
|
||||
- Constraints transform into attribute constraints or table constraints.
|
||||
|
||||
#### Transforming ER Model into Tables
|
||||
|
||||

|
||||
|
||||
#### Representing a Relationship Using Foreign Key
|
||||
|
||||

|
||||
|
||||
### Principles of Choosing Foreign Keys
|
||||
|
||||
- Should not be null
|
||||
- Should not have multiple values
|
||||
- Keep it simple
|
||||
- Ex.
|
||||

|
||||
- All Many to Many relationships are transformed the same way.
|
||||
|
||||
### \[1:1] \[o:m] Relationships
|
||||
|
||||

|
||||
|
||||
- Since a professor does not have to have a department, we should not add `dep#` as a foreign key to the professors table, as values may be null.
|
||||
- As a department must have exclusively one professor, the logical choice is to add `p#` as the foreign key in the departments table.
|
||||
|
||||
### \[1:1] \[o:o] Relationships
|
||||
|
||||

|
||||
|
||||
- As neither table can fulfil its purpose as a foreign key, we cannot add either relation to either table, as it would break the principles of foreign keys.
|
||||
- Instead we should create a third table, containing both primary keys, as seen below.
|
||||

|
||||
- The primary key for this table may be `p#`, `dep#`, but never both.
|
||||
- There will never be more than one professor to one department, as seen by the lack of crows foot in the diagram.
|
||||
|
||||
### \[1:1] \[m:m] Relationships
|
||||
|
||||

|
||||
|
||||
- Since there must be 1 professor to 1 department, there would never be a null value, and never have multiple values in the foreign key. This way we can add either primary key as the foreign key in the other table.
|
||||
- If we know the query types that would be most common, we can choose the foreign key that would be most applicable.
|
||||
|
||||
### Exercise 1
|
||||
|
||||
A person must have exactly one birth certificate.
|
||||
Each birth certificate is for just for one person.
|
||||
|
||||
\[Person] -|---|- \[Certificate]
|
||||
|
||||
- This is a \[1:1] \[m:m] relationship, meaning we can have either primary key as the foreign key in the other table.
|
||||
|
||||
#### Answer
|
||||
|
||||

|
||||
|
||||
### Exercise 2
|
||||
|
||||
Each birth certificate is for just for one person.
|
||||
A person may have a birth certificate, or may have lost it!
|
||||
|
||||
\[Person] -o---|- \[Certificate]
|
||||
|
||||
- This is a \[1:1] \[o:m] relationship. The person table primary key should be the foreign key in the certificate table.
|
||||
|
||||
#### Answer
|
||||
|
||||

|
||||
|
||||
### \[M:1] \[m:o] Relationships
|
||||
|
||||

|
||||
|
||||
- A team can include none, one or many junior doctors, but a junior cannot be part of multiple teams.
|
||||
- Each junior is in exactly one team, so adding the team primary key to the juniors table is the most acceptable in this scenario.
|
||||
|
||||
### \[M:1] \[o:o] Relationships
|
||||
|
||||

|
||||
|
||||
- Since in this example, a junior may not be in a team, we must have to make a third table, since any solution would lead to multiple or null values, which would violate foreign key principles.
|
||||
|
||||
### Exercise 3
|
||||
|
||||
#### Part 1
|
||||
|
||||
A person must own one or more cars.
|
||||
A car must have exactly one owner.
|
||||
|
||||
\[Person] \-|---|-/\\ \[Car]
|
||||
|
||||
- This is a \[1:M] \[m:m] Relationship
|
||||
- person(person#, name…)
|
||||
- car(car#, …, person#\*)
|
||||
- The person candidate key would be the foreign key in the car table.
|
||||
|
||||
#### Part 2
|
||||
|
||||
A person may own none, one or more cars.
|
||||
A car must have exactly one owner.
|
||||
|
||||
\[Person] -o---|-/\\ \[Car]
|
||||
|
||||
- This is a \[1:M] \[o:m] Relationship
|
||||
- person(person#, name, …)
|
||||
- car(car#, …, person#\*)
|
||||
|
||||
## Lecture 2 (15:00)
|
||||
|
||||
### Many to Many Relationships
|
||||
|
||||

|
||||
|
||||
- Since we cannot have either primary key be a foreign key, as we would have multiple values, we would have to make a composite 3rd table.
|
||||

|
||||
|
||||
### Transforming Complex ER Diagrams
|
||||
|
||||

|
||||
|
||||
### Flow Chart
|
||||
|
||||

|
||||
|
||||
## Tutorial 1 (15:00)
|
||||
|
||||
### Exercise 1
|
||||
|
||||
#### Part 1
|
||||
Project -o---|-/\\- Order
|
||||
\[1:M] \[o:m] Relationship
|
||||
|
||||
project(proj#, name, start-date, end-date)
|
||||
order(order#, date, inquiry, proj#\*)
|
||||
|
||||
#### Part 2
|
||||
Supplier -/\\-o---o-/\\- Part
|
||||
\[M:M] \[o:o] Relationship
|
||||
|
||||
supplier(supplier#, name, tel-no)
|
||||
part(part#, name, price)
|
||||
orderList(supplier#\*, part#\*)
|
||||
|
||||
- We must create a new composite table to contain the relation, since we cannot sustain the principles of foreign keys.
|
||||
|
||||
#### Part 3
|
||||
Staff -/\\-|---|- Department
|
||||
\[M:1] \[m:m] Relationship
|
||||
|
||||
staff(staff-id, name, address, phone-no, dept-id*)
|
||||
department(dept-id, name, location)
|
||||
|
||||
- We would create dept-id as a foreign key in the staff table, as multiple values wont occur, and staff must be a part of a department in this scenario.
|
||||
|
||||
#### Part 4
|
||||
Manager -|---|- Project
|
||||
\[1:1] \[m:m] Relationship
|
||||
|
||||
manager(man-id, name, address, tel-no, proj-id*)
|
||||
project(proj-id, name, start-date, end-date)
|
||||
|
||||
- We could use either primary key for the alternate table's foreign key, since they are both mandatory and 1:1, so there would be no multiple values nor would there be null values.
|
||||
|
||||
#### Part 5
|
||||
Manager -|---|-/\\- Team -|---|-/\\- Player
|
||||
\[1:M] \[m:m] (Both) Relationship
|
||||
|
||||
manager(man-id, name, address, tel-no)
|
||||
team(team-name, date-founded, address, man-id*)
|
||||
player(player-id, name, address, tel-no, team-name*)
|
||||
|
||||
## Tutorial 2 (14:00)
|
||||
|
||||
#### Entities & Attributes
|
||||
| Entities | Attributes |
|
||||
|----------|------------|
|
||||
| Regional Office | *regioncode*, name, location |
|
||||
| Branch | *branch_no*, institution |
|
||||
| Member | *mem_no*, name, age, type |
|
||||
| Role | *role_id*, level, role |
|
||||
|
||||
#### Relations
|
||||
Role - \[1:M]\[m:o] - Member
|
||||
Member - \[M:1]\[o:m] - Branch
|
||||
Branch - \[M:1]\[m:m] - Region
|
162
Semester 1/DatabaseBackup/Week 7/Week 7 Database Systems.md
Normal file
162
Semester 1/DatabaseBackup/Week 7/Week 7 Database Systems.md
Normal file
@@ -0,0 +1,162 @@
|
||||
## Lecture 1 (13:00) - Normalisation
|
||||
|
||||
### Functional Dependency
|
||||
|
||||
- A -> B
|
||||
- A functionally determines B
|
||||
- B is functionally dependent on A
|
||||
This means you cannot have two rows with the same value of A and different values of B
|
||||
- ex.
|
||||
- StudentID -> StudentSurname
|
||||
- u001 -> smith
|
||||
- StudentSurname -/> StudentID
|
||||
- smith -> u001
|
||||
- smith -> u002
|
||||
- smith -> u003
|
||||
|
||||
### 1st NF
|
||||
|
||||
- First normal form has:
|
||||
- No repeating groups
|
||||
- Non-key attributes determined by key
|
||||
|
||||
##### Example 1
|
||||
|
||||

|
||||
In this example, 2 tables are created, since there is a repeating group in the initial table. The separate composite table allows us to remove the repeating group.
|
||||
|
||||
##### Example 2
|
||||
|
||||

|
||||
In this example, 3 tables are created. A composite table to keep the relations, and 2 tables to contain the repeated groups.
|
||||
There are 2 repeating groups, since the attribute Department has multiple values for a value of the key ID, and the attribute Interests does the same.
|
||||
As they do not relate to each other, they are not part of the same repeating group.
|
||||
|
||||
#### Repeating Group
|
||||
|
||||
- Repeating group is an attribute or group of attributes in a table that occur with multiple values for a single occurrence of the nominated key attributes for that table
|
||||
ex.
|
||||

|
||||
|
||||
### Full / Partial Functional Dependency
|
||||
|
||||
- Attributes may depend on a set of other attributes
|
||||
- StudentId, ModuleName -> ExamMark
|
||||
- OrderNo, PartNo -> Quantity
|
||||
- D is *fully functionally dependent* on A, B and C if
|
||||
- A, B, C -> D but A, B -/> and B, C -> D
|
||||
- All the attributes on the left are needed to determine the right
|
||||
- Partial dependency refers to the attributes which are only dependent on part of the composite primary key.
|
||||
|
||||
##### Example 1
|
||||
|
||||

|
||||
|
||||
These partial dependencies can be removed by doing the following
|
||||

|
||||
|
||||
### 2nd NF
|
||||
|
||||
- A table is in second normal form if:
|
||||
- It is in 1NF
|
||||
- There are **no** partial dependencies
|
||||
- (every non-key attribute is fully dependent on the primary key)
|
||||
- Partial dependencies can only be possible if the primary key is composite, if not then nothing depends on part of the PK, since it has no parts.
|
||||
- A 1NF table is automatically 2NF if the PK is atomic ( one attribute )
|
||||
|
||||
### 3rd NF
|
||||
|
||||
- A table is in 3rd normal form if:
|
||||
- It is in 2NF
|
||||
- There are no transitive dependencies
|
||||
- (if no non-key attribute is transitively dependent on the PK)
|
||||
|
||||
#### Transitive Dependency
|
||||
|
||||
- If A -> B and B -> C, then we can write:
|
||||
- A -> B -> C
|
||||
- OrderNo -> SupplierNo -> SupplierName
|
||||
- We say
|
||||
- “C is transitively dependent on A”.
|
||||
- “A determines C via B”.
|
||||
- So for the supplier table we say:
|
||||
- “Supplier name is transitively dependent on OrderNo.”
|
||||
- “OrderNo determines SupplierName via SupplierNo.”
|
||||
|
||||
### Normalisation Venn Diagram
|
||||
|
||||

|
||||
|
||||
### Summary
|
||||
|
||||

|
||||
|
||||
## Tutorial 1 (15:00) - Normalisation
|
||||
|
||||
### Exercise 1 - Identifying Design Faults
|
||||
|
||||
1. Is Table 14.1 in 1NF? Is it in 2NF? Is it in 3NF? Justify your answers.
|
||||

|
||||
CW Mark and Exam Mark depend on the composite key. Does not contain repeating groups.
|
||||
CW Mark and Exam Mark are fully functionally dependent on both StudentID and Module. There are no partial dependencies.
|
||||
There are no transitive dependencies. 3NF
|
||||
|
||||
2. Is Table 14.2 in 1NF? Is it in 2NF? Is it in 3NF? Justify your answers.
|
||||

|
||||
2NF - CW and CW Outcome depend on the composite key. No repeating groups
|
||||
CW Mark and CW Outcome are functionally dependent on both StudentID and Module. No partial Dependencies
|
||||
There is a transitive dependency (CW Mark depends on key, CW Outcome depends on CW Mark), so 2NF
|
||||
|
||||
### Exercise 2 - Restructuring Tables
|
||||
|
||||
1. Convert Table 14.3 to 1st normal form.
|
||||

|
||||
|
||||
We must first create a composite table.
|
||||
|
||||
| *country* | saint |
|
||||
|-|-|
|
||||
| England | George |
|
||||
| Wales | David |
|
||||
| Scotland | Andrew |
|
||||
|
||||
Then we can use the cities field as the primary key in the second table
|
||||
|
||||
| *cities* | country |
|
||||
|-|-|
|
||||
| Manchester | England |
|
||||
| Leeds | England |
|
||||
| Newcastle | England |
|
||||
| Swansea | Wales |
|
||||
| Cardiff | Wales |
|
||||
| Glasgow | Scotland |
|
||||
| Edinburgh |Scotland |
|
||||
|
||||
1. Convert Table 14.4 to 2nd normal form.
|
||||

|
||||
|
||||
| student-ID | stud-name |
|
||||
|------------|-----------|
|
||||
| S001 | Tom |
|
||||
| S002 | Dick |
|
||||
| S003 | Harry |
|
||||
|
||||
| module | student-ID | grade |
|
||||
|--------|------------|-------|
|
||||
|Databases|S001|A|
|
||||
|Databases|S002|B|
|
||||
|Databases|S003|B|
|
||||
|Research Methods|S001|A|
|
||||
|Research Methods|S003|B|
|
||||
|Java|S001|C|
|
||||
|Java|S002|C|
|
||||
|Java|S003|C|
|
||||
|
||||
1. Examine Table 14.5 to see if it contains redundant data, i.e., the same fact stored
|
||||
more than once. Suggest how the redundancy might be removed by splitting the
|
||||
table into two relations with a primary key/foreign key link.
|
||||

|
||||
|
||||
We could remove the redundant data by creating a composite table of project-manager-id and project-manager-name. project-manager-id then becomes a foreign key in a second table with fields (*project-ID*, part, quantity and project-manager-ID). Since there is no candidate key, we must create a new primary key called project-id with a unique value.
|
||||
|
||||
![[images/Diagram.svg]]
|
95
Semester 1/DatabaseBackup/Week 8/Week 8 Database Systems.md
Normal file
95
Semester 1/DatabaseBackup/Week 8/Week 8 Database Systems.md
Normal file
@@ -0,0 +1,95 @@
|
||||
## Lecture 1 (13:00) - Sub-queries
|
||||
|
||||
- Aggregate functions cannot be used in a where clause.
|
||||
ex.
|
||||
|
||||
```sql
|
||||
SELECT staffNo, name, position, salary
|
||||
FROM staff
|
||||
WHERE salary > ( SELECT AVG(salary) FROM STAFF )
|
||||
```
|
||||
|
||||
### IN Operator
|
||||
|
||||
- Used to check if an attribute has a value from a set of values.
|
||||
- \[NOT] IN (\<value list>)
|
||||
ex.
|
||||
|
||||
```sql
|
||||
SELECT name
|
||||
FROM Drivers
|
||||
WHERE address IN ("Dundee", "Aberdeen")
|
||||
```
|
||||
|
||||
ex of IN used with subqueries. This would select all properties, their rooms and rent values, where their staff number matches a specific branch number
|
||||
|
||||
```sql
|
||||
SELECT propertyNo, rooms, rent
|
||||
FROM property
|
||||
WHERE staffNo IN
|
||||
( SELECT staffNo
|
||||
FROM staff
|
||||
WHERE branchNo = (
|
||||
SELECT branchNo
|
||||
FROM branch
|
||||
WHERE street = "Main St"
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
## Tutorial 2 (15:00) - SQL Sub-queries
|
||||
|
||||

|
||||

|
||||
|
||||
1. List the names of pirates who have pillaged booty of type bt3.
|
||||
|
||||
```sql
|
||||
SELECT p-name
|
||||
FROM pirates
|
||||
WHERE p-code IN (
|
||||
SELECT p-code
|
||||
FROM pillage
|
||||
WHERE boat-code = "b3"
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
1. List the names of pirates who have pillaged any kind of fruit.
|
||||
|
||||
```sql
|
||||
SELECT p-name
|
||||
FROM pirates
|
||||
WHERE p-code IN (
|
||||
SELECT p-code
|
||||
FROM pillage
|
||||
WHERE booty-code IN (
|
||||
SELECT booty-code
|
||||
FROM booty
|
||||
WHERE booty-name LIKE "%Fruit"
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
1. List the names of booty whose value is greater than the average value of all the booty.
|
||||
|
||||
```sql
|
||||
SELECT booty-name
|
||||
FROM booty
|
||||
WHERE value > (
|
||||
SELECT AVG(value)
|
||||
FROM booty
|
||||
);
|
||||
```
|
||||
|
||||
## Workshop 2 (10:00)
|
||||
|
||||
1. List the names of the products whose number of units on order is greater than the average number of units in stock.
|
||||

|
||||
|
||||
2. List the names of the products which have a value for UnitsInStock that is less than the average number of units in stock. Your query should also list the value for the UnitsInStock for each of these products. The results must be sorted into ascending order on UnitsInStock.
|
||||

|
||||
|
||||
3. List names of the products whose number of units in stock is less than the average number of units in stock and whose number of units on order is less than the average number of units on order.
|
||||
|
||||

|
Reference in New Issue
Block a user