Moi CT2 RDBMS MSC2
Moi CT2 RDBMS MSC2
1 001 C001
2 056 C005
Note: In SQL Server a unique constraint that has a nullable
column, allows the value ‘null‘ in that column only once. That’s why the
STUD_PHONE attribute is a candidate here, but can not be a ‘null’ value in the
primary key attribute.
Primary Key
There can be more than one candidate key in relation out of which one can
be chosen as the primary key. For Example, STUD_NO, as well as
STUD_PHONE, are candidate keys for relation STUDENT but STUD_NO can be
chosen as the primary key (only one out of many candidate keys).
It is a unique key.
It can identify only one tuple (a record) at a time.
It has no duplicate values, it has unique values.
It cannot be NULL.
Primary keys are not necessarily to be a single column; more than
one column can also be a primary key for a table.
Example:
STUDENT table -> Student(STUD_NO, SNAME,
ADDRESS, PHONE) , STUD_NO is a primary key
Table STUDENT
STUD_NO SNAME ADDRESS PHONE
Alternate Key
The candidate key other than the primary key is called an alternate key.
All the keys which are not primary keys are called alternate keys.
It is a secondary key.
It contains two or more fields to identify two or more records.
These values are repeated.
Eg:- SNAME, and ADDRESS is Alternate keys
Example:
Consider the table shown above.
STUD_NO, as well as PHONE both,
are candidate keys for relation STUDENT but
PHONE will be an alternate key
(only one out of many candidate keys).
Primary Key, Candidate Key, and Alternate Key
Foreign Key
If an attribute can only take the values which are present as values of some
other attribute, it will be a foreign key to the attribute to which it refers. The
relation which is being referenced is called referenced relation and the
corresponding attribute is called referenced attribute the relation which
refers to the referenced relation is called referencing relation and the
corresponding attribute is called referencing attribute. The referenced
attribute of the referenced relation should be the primary key to it.
It is a key it acts as a primary key in one table and it acts as
secondary key in another table.
It combines two or more relations (tables) at a time.
They act as a cross-reference between the tables.
For example, DNO is a primary key in the DEPT table and a non-key
in EMP
Example:
Refer Table STUDENT shown above.
STUD_NO in STUDENT_COURSE is a
foreign key to STUD_NO in STUDENT relation.
Table STUDENT_COURSE
STUD_NO TEACHER_NO COURSE_NO
1 005 C001
2 056 C005
It may be worth noting that, unlike the Primary Key of any given relation,
Foreign Key can be NULL as well as may contain duplicate tuples i.e. it need
not follow uniqueness constraint. For Example, STUD_NO in the
STUDENT_COURSE relation is not unique. It has been repeated for the first
and third tuples. However, the STUD_NO in STUDENT relation is a primary key
and it needs to be always unique, and it cannot be null.
Composite Key
Sometimes, a table might not have a single column/attribute that uniquely
identifies all the records of a table. To uniquely identify rows of a table, a
combination of two or more columns/attributes can be used. It still can give
duplicate values in rare cases. So, we need to find the optimal set of
attributes that can uniquely identify rows in a table.
It acts as a primary key if there is no primary key in a table
Two or more attributes are used together to make a composite key.
Different combinations of attributes may give different accuracy in
terms of identifying the rows uniquely.
Example:
FULLNAME + DOB can be combined
together to access the details of a student.
1. Select Operation:
1. Notation: σ p(r)
Where:
Input:
1. σ BRANCH_NAME="perryride" (LOAN)
Output:
o This operation shows the list of those attributes that we wish to appear
in the result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.
Where
Input:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
3. Union Operation:
o Suppose there are two tuples R and S. The union operation contains all
the tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.
1. Notation: R ∪ S
Example:
DEPOSITOR RELATION
CUSTOMER_NAME ACCOUNT_NO
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
Input:
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
4. Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in both R & S.
o It is denoted by intersection ∩.
1. Notation: R ∩ S
Output:
CUSTOMER_NAME
Smith
Jones
5. Set Difference:
o Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in R but not in S.
o It is denoted by intersection minus (-).
1. Notation: R - S
Input:
Output:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
6. Cartesian product
o The Cartesian product is used to combine each row in one table with
each row in the other table. It is also known as a cross product.
o It is denoted by X.
1. Notation: E X D
Example:
EMPLOYEE
1 Smith A
2 Harry C
3 John B
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
1. EMPLOYEE X DEPARTMENT
Output:
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
7. Rename Operation:
The rename operation is used to rename the output relation. It is denoted
by rho (ρ).
1. ρ(STUDENT1, STUDENT)
Example:
EMPLOYEE
EMP_CODE EMP_NAME
101 Stephan
102 Jack
103 Harry
SALARY
EMP_CODE SALARY
101 50000
102 30000
103 25000
Result:
1. Natural Join:
o A natural join is the set of tuples of all combinations in R and S that are
equal on their common attribute names.
o It is denoted by ⋈.
Example: Let's use the above EMPLOYEE table and SALARY table:
Input:
Output:
EMP_NAME SALARY
Stephan 50000
Jack 30000
Harry 25000
2. Outer Join:
The outer join operation is an extension of the join operation. It is used to
deal with missing information.
Example:
EMPLOYEE
FACT_WORKERS
Input:
1. (EMPLOYEE ⋈ FACT_WORKERS)
Output:
o Left outer join contains the set of tuples of all combinations in R and S that
are equal on their common attribute names.
o In the left outer join, tuples in R have no matching tuples in S.
o It is denoted by ⟕.
Input:
1. EMPLOYEE ⟕ FACT_WORKERS
o Right outer join contains the set of tuples of all combinations in R and S
that are equal on their common attribute names.
o In right outer join, tuples in S have no matching tuples in R.
o It is denoted by ⟖.
Input:
1. EMPLOYEE ⟖ FACT_WORKERS
Output:
o Full outer join is like a left or right join except that it contains all rows from
both tables.
o In full outer join, tuples in R that have no matching tuples in S and tuples
in S that have no matching tuples in R in their common attribute name.
o It is denoted by ⟗.
1. EMPLOYEE ⟗ FACT_WORKERS
Output:
3. Equi join:
It is also known as an inner join. It is the most common join. It is based on
matched data as per the equality condition. The equi join uses the
comparison operator(=).
Example:
CUSTOMER RELATION
CLASS_ID NAME
1 John
2 Harry
3 Jackson
PRODUCT
PRODUCT_ID CITY
1 Delhi
2 Mumbai
3 Noida
Input:
1. CUSTOMER ⋈ PRODUCT
Output:
1 John 1 Delhi
2 Harry 2 Mumbai
3 Harry 3 Noida
NULL value acceptance Cannot accept NULL values. Can accept NULL values.
The primary Key is used for The Unique Key is used for
Uses
indicating the rows uniquely. preventing duplicate entries.
Before finding the SQL percentages across rows and columns, let’s first see how you can find
percentages using two basic variables in SQL Server.
The script below defines three float variables @num1, @num2 and @perc. Next, the
@num2 variable is divided by the @num1 variable and the result is multiplied by 100 which
is stored in the @perc variable and is printed on the console.
PRINT @perc
Output:
The script below, creates a table Result with two float type columns “obtained”, and “total”.
The script also inserts five dummy rows in the Result table. The SELECT query then selects all
the records in the Result table. Here is an example:
SELECT *
FROM Result
Output:
Let’s try to find percentages for each row as a result of the division between the values in
the “obtained” and “total” columns as shown below where a new column is added for
percentages.
SELECT *
FROM Scores
Output:
Now if you want to find what percent of the sum of total values in the “val” column does
each value constitutes, you can use subqueries.
In this regard, the outer query will multiply all the values in the “val” column by 100 which
will be divided by the result of the subquery which finds the sum of all the values in the
“val” column.
Let’s first see how our subquery looks that calculate the sum of the values in the “val”
column.
Output:
The following script returns the percentage of the total for each value in the “val ” column.
SELECT val,
val * 100/(SELECT SUM(val) FROM Scores) as 'Percentage of Total'
From Scores
If you do not want to exclude any value while calculating the percentage of the total, you
can do so with the WHERE clause as shown in the script below where the value 40 is not
included.
SELECT val,
val * 100/(SELECT SUM(val) FROM Scores WHERE val < 40) as 'Percentage of Total' From
Scores WHERE val < 40
You can see from the above output that the values now have a larger percentage share of
total values since the value 40 is removed.
Finally, as a side note, you can round off the percentages returned using the “round”
function as shown below. The script below rounds off the percentage values to 2 decimal
places.
SELECT val,
round(val * 100/(SELECT SUM(val) FROM Scores WHERE val < 40), 2) as 'Percentage of Total'
From Scores WHERE val < 40
Output:
7. Explain packages.
PL/SQL packages are a way to organize and encapsulate
related procedures, functions, variables, triggers, and other PL/SQL items into a single
item. Packages provide a modular approach to write and maintain the code. It makes it
easy to manage large codes.
A package is compiled and then stored in the database, which then can be shared with
many applications. The package also has specifications, which declare an item to be public
or private. Public items can be referenced from outside of the package.
A PL/SQL package is a collection of related Procedures, Functions, Variables, and other
elements that are grouped for Modularity and Reusability.
The needs of the Packages are described below:
Modularity: Packages provide a modular structure, allowing developers to
organize and manage code efficiently.
Code Reusability: Procedures and functions within a package can be reused
across multiple programs, reducing redundancy.
Private Elements: Packages support private procedures and functions, limiting
access to certain code components.
Encapsulation: Packages encapsulate related logic, protecting internal details
and promoting a clear interface to other parts of the code.
PL/SQL Package
A PL/SQL package consists of two parts:
1. A package Specification.
2. A package Body.
Package Specification
The package specification declares the public interface of the package. It includes
declarations of procedures, functions, variables, cursors, and other constructs that are
meant to be accessible from outside the package. The specification is like a header file
that defines what a package can do.
Package Body
The package body contains the implementation of the details of the package. It includes
the coding of the procedures or functions which are decalared in the package
specification. The body can also contain private variables and procedures that are not
exposed to outside the code.
Example of Package Body
CREATE OR REPLACE PACKAGE BODY my_package AS
PROCEDURE my_procedure(p_param1 NUMBER) IS
BEGIN
-- Implementation code...
END my_procedure;
Once your create your package in above two steps, you can use it in PL/SQL codes. This
allows for modular programming, code reuse, and better maintenance of the the code
base.
To Use the Package in Our Code, Follow the Below Pattern
DECLARE
result NUMBER;
BEGIN
-- Call a procedure from the package
my_package.my_procedure(42);
-- Other code...
END;
Example 1
-- Enable the display of server output
SET SERVEROUTPUT ON;
Output:
Explanation
The PL/SQL code defines a package named math_operations with a procedure
(add_numbers) and a function (multiply_numbers). The package is then implemented in a
package body, with the procedure adding two numbers and the function multiplying them.