6 Sql

Database Management System Ā· Unit 6 Ā· 8 hrs

SQL

Exam-focused notes for SQL (Database Management System, CSC265): what the TU syllabus asks and how it has actually been tested, with 5 solved past questions from this unit.

SQL in short

This unit covers SQL itself: how to define tables and constraints, how to write retrieval queries from a simple SELECT up through nested subqueries, how to modify data, and how to define a view. SQL uses table, row and column for what the formal relational model calls relation, tuple and attribute, and it is the standard query language of essentially every commercial DBMS (Oracle, MySQL, SQL Server, PostgreSQL among them).

SQL: notes

The examples below share one schema, an EMPLOYEE table linked to a DEPARTMENT table by a foreign key:

DEPARTMENT

DnumberDname
1Headquarters
4Administration
5Research

EMPLOYEE

SsnFnameLnameSalaryDnoSuper_ssn
333445555JohnSmith300005888665555
999887777AliciaZelaya250004987654321
987654321JenniferWallace430004888665555
666884444RameshNarayan380005333445555
453453453JoyceEnglish250005333445555
888665555JamesBorg550001NULL

Data Definition and Data Types

CREATE TABLE tells the DBMS to define a new base table (also called a base relation), physically created and stored by the system. Each column is given a name, a data type (its domain), and optionally a constraint such as NOT NULL:

CREATE TABLE EMPLOYEE (
    Ssn        CHAR(9)       NOT NULL,
    Fname      VARCHAR(15)   NOT NULL,
    Lname      VARCHAR(15)   NOT NULL,
    Bdate      DATE,
    Address    VARCHAR(30),
    Sex        CHAR(1),
    Salary     DECIMAL(10,2),
    Dno        INT           NOT NULL,
    Super_ssn  CHAR(9),
    PRIMARY KEY (Ssn)
);

SQL's basic data types cover numeric values, both integers (INTEGER/INT, SMALLINT) and floating point (FLOAT, DOUBLE PRECISION), with DECIMAL(i, j) giving a fixed-precision number of $i$ total digits and $j$ digits after the decimal point; character strings, either fixed length (CHAR(n)) or variable length up to $n$ characters (VARCHAR(n)); bit strings, fixed (BIT(n)) or variable (BIT VARYING(n)), written as a literal such as B'10101'; Boolean values, TRUE, FALSE, or, because SQL allows NULL, the third possible state UNKNOWN; and date and time values, DATE in the form YYYY-MM-DD and TIME in the form HH:MM:SS. A domain can also be declared once and reused across many attribute definitions, for example CREATE DOMAIN SSN_TYPE AS CHAR(9);, which both documents intent and makes a later, schema-wide type change easier.

ALTER TABLE modifies an existing table without destroying its data, most commonly to add a column: ALTER TABLE EMPLOYEE ADD COLUMN Bonus DECIMAL(8,2);. DROP TABLE EMPLOYEE; removes a table's definition and its data entirely from the schema.

What this unit covers

  • Data Definition and Data Types
  • Specifying Constraints
  • Basic Retrieval Queries
  • Complex Retrieval Queries
  • INSERT, DELETE, and UPDATE Statements
  • Views

Complex Retrieval Queries

2080 Ā· 10 marks

Consider a banking database with three tables and primary keys underlined as given below: Customer(CustomerID, CustomerName, Address, Phone, Email) Owns(CustomerID, AccountNumber) Account(AccountNumber, AccountType, Balance) Write both relational algebra and SQL queries: a. To display name of all customers who live in 'Kathmandu'. b. To count total number of customers. c. To find name of those customers who have balance greater than or equal to 100000. d. To find average balance of each account type.[10]

Show solved answer

Relational Algebra and SQL Queries for Banking Database

Given Schema

  • Customer(<u>CustomerID</u>, CustomerName, Address, Phone, Email)
  • Owns(<u>CustomerID</u>, <u>AccountNumber</u>)
  • Account(<u>AccountNumber</u>, AccountType, Balance)

a. Display name of all customers who live in 'Kathmandu'

Relational Algebra

Ļ€ CustomerName (σ Address = 'Kathmandu' (Customer))

Steps:

  1. Apply selection (σ) on Customer table where Address = 'Kathmandu'
  2. Apply projection (Ļ€) to retrieve only CustomerName

SQL Query

SELECT CustomerName
FROM Customer
WHERE Address = 'Kathmandu';

b. Count total number of customers

Relational Algebra

ℱ COUNT(CustomerID) (Customer)

Note: Aggregate functions use the aggregate operator ℱ (script F) in relational algebra.

SQL Query

SELECT COUNT(CustomerID) AS TotalCustomers
FROM Customer;

c. Find name of customers who have balance greater than or equal to 100000

Relational Algebra

Ļ€ CustomerName (Customer ā‹ˆ Owns ā‹ˆ (σ Balance >= 100000 (Account)))

Steps:

  1. Apply selection (σ) on Account table where Balance >= 100000
  2. Natural join (ā‹ˆ) the result with Owns on AccountNumber
  3. Natural join (ā‹ˆ) the result with Customer on CustomerID
  4. Apply projection (Ļ€) to retrieve only CustomerName

SQL Query

SELECT DISTINCT C.CustomerName
FROM Customer C
JOIN Owns O ON C.CustomerID = O.CustomerID
JOIN Account A ON O.AccountNumber = A.AccountNumber
WHERE A.Balance >= 100000;

DISTINCT is used to avoid duplicate customer names if a customer owns multiple qualifying accounts.


d. Find average balance of each account type

Relational Algebra

AccountType ℱ AVG(Balance) (Account)

The attribute before ℱ denotes the grouping attribute (GROUP BY equivalent).

SQL Query

SELECT AccountType, AVG(Balance) AS AverageBalance
FROM Account
GROUP BY AccountType;

Summary Table

PartOperation UsedKey Clause
aSelection + ProjectionWHERE Address = 'Kathmandu'
bAggregate (COUNT)COUNT()
cSelection + Join + ProjectionJOIN + WHERE Balance >= 100000
dAggregate (AVG) + GroupingGROUP BY + AVG()
Open this answer on its own page →

2080.1 Ā· 10 marks

Consider a banking database with three tables and primary key underlined as given below: Customer(CustomerID, CustomerName, Address, Phone, Email) Borrows(CustomerID, LoanNumber) Loan(LoanNumber, LoanType, Amount) Write both relational algebra and SQL queries: a. To display name of all customers who live in ā€œLalitpurā€ in ascending order of name. b. To count total number of customers having loan at the bank. c. To find name of those customers who have loan amount greater than or equal to 500000. d. To find average loan amount of each account type.[10]

  • Customer(<uCustomerID</u, CustomerName, Address, Phone, Email) - Borrows(<uCustomerID</u, <uLoanNumber</u) - Loan(<uLoanNumber</u, LoanType, Amount) --- $$\tau{CustomerName}(\pi{CustomerName}(\sigma{Address='Lalitpur'}(Customer)))$$ Where: - $\sigma$ = Selection operator (filters rows) - $\pi$ ...
Open this answer on its own page →

Specifying Constraints

2079 Ā· 5 marks

Explain Assertion and Triggers with example. [5]

--- An assertion is a predicate (condition) that expresses a constraint that the database must always satisfy. It is a general integrity constraint that is not tied to a single table but can span multiple tables. - Assertions are part of SQL's Data Definition Language (DDL). - Whenever a database...

Open this answer on its own page →

Basic Retrieval Queries

2078 Ā· 5 marks

Retirve the TName, SName, SPhone for ā€œABCā€ school using SQL from given relation as below. [5]

The question asks to retrieve TName (Teacher Name), SName (Student Name), and SPhone (Student Phone) for the school named "ABC" using SQL. To answer this, we assume the following relational schema (standard school database relations): --- --- --- Step Description ------------------- Step 1 Select...

Open this answer on its own page →

Data Definition and Data Types

2076 Ā· 5 marks

Create two table Courses (CID, Course, Dept) and HoD (Dept, Head) using SQL language with all constraints [Primary key, Foreign key and Referential Integrity]. Assume the types of attributes by your own. [5]

  • Courses (CID, Course, Dept) - HoD (Dept, Head) --- Attribute Type Reason ------------------------- CID INT Numeric course identifier Course VARCHAR(50) Course name as string Dept VARCHAR(30) Department name as string Head VARCHAR(50) Head of Department name --- The HoD table must be created fir...
Open this answer on its own page →