0% found this document useful (0 votes)
8 views

Unit 3 DBMS Keys Join Aggregate View Clauses

DBMS Notes

Uploaded by

padanursatish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 3 DBMS Keys Join Aggregate View Clauses

DBMS Notes

Uploaded by

padanursatish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

DBMS Keys: Primary, Candidate, Super,

Alternate and Foreign (Example)


What are Keys?

A DBMS key is an attribute or set of an attribute which helps you to identify a row(tuple) in a relation(table).
They allow you to find the relation between two tables. Keys help you uniquely identify a row in a table by a
combination of one or more columns in that table.

Example:

Employee ID FirstName LastName

11 Andrew Johnson

22 Tom Wood

33 Alex Hale

In the above-given example, employee ID is a primary key because it uniquely identifies an employee
record. In this table, no other employee can have the same employee ID.

Why we need a Key?

Here, are reasons for using Keys in the DBMS system.

 Keys help you to identify any row of data in a table. In a real-world application, a table could contain
thousands of records. Moreover, the records could be duplicated. Keys ensure that you can
uniquely identify a table record despite these challenges.
 Allows you to establish a relationship between and identify the relation between tables
 Help you to enforce identity and integrity in the relationship.

Various Keys in Database Management System

DBMS has folwing seven types of Keys each have their different functionality:

 Super Key
 Primary Key
 Candidate Key
1
 Alternate Key
 Foreign Key
 Compound Key
 Composite Key
 Surrogate Key

What is the Super key?

A superkey is a group of single or multiple keys which identifies rows in a table. A Super key may have
additional attributes that are not needed for unique identification.

Example:

EmpSSN EmpNum Empname

9812345098 AB05 Shown

9876512345 AB06 Roslyn

199937890 AB07 James

In the above-given example, EmpSSN and EmpNum name are superkeys.

What is a Primary Key?

A column or group of columns in a table which helps us to uniquely identifies every row in that table is
called a primary key. This DBMS can't be a duplicate. The same value can't appear more than once in the
table.

Rules for defining Primary key:

 Two rows can't have the same primary key value


 It must for every row to have a primary key value.
 The primary key field cannot be null.
 The value in a primary key column can never be modified or updated if any foreign key refers to that
primary key.

Example:

In the following example, <code>StudID</code> is a Primary Key.

2
StudID Roll No First Name LastName Email

1 11 Tom Price [email protected]

2 12 Nick Wright [email protected]

3 13 Dana Natan [email protected]

What is the Alternate key?

All the keys which are not primary key are called an alternate key. It is a candidate key which is currently
not the primary key. However, A table may have single or multiple choices for the primary key.

Example: In this table.

StudID, Roll No, Email are qualified to become a primary key. But since StudID is the primary key, Roll No,
Email becomes the alternative key.

StudID Roll No First Name LastName Email

1 11 Tom Price [email protected]

2 12 Nick Wright [email protected]

3 13 Dana Natan [email protected]

What is a Candidate Key?

A super key with no repeated attribute is called candidate key.

The Primary key should be selected from the candidate keys. Every table must have at least a single
candidate key.

Properties of Candidate key:

 It must contain unique values


 Candidate key may have multiple attributes
 Must not contain null values
 It should contain minimum fields to ensure uniqueness
 Uniquely identify each record in a table

3
Example: In the given table Stud ID, Roll No, and email are candidate keys which help us to uniquely
identify the student record in the table.

StudID Roll No First Name LastName Email

1 11 Tom Price [email protected]

2 12 Nick Wright [email protected]

3 13 Dana Natan [email protected]

What is the Foreign key?

A foreign key is a column which is added to create a relationship with another table. Foreign keys help us to
maintain data integrity and also allows navigation between two different instances of an entity. Every
relationship in the model needs to be supported by a foreign key.

Example:

DeptCode DeptName

001 Science

002 English

005 Computer

Teacher ID Fname Lname

B002 David Warner

B017 Sara Joseph

B009 Mike Brunton

4
In this example, we have two table, teach and department in a school. However, there is no way to see
which search work in which department.

In this table, adding the foreign key in Deptcode to the Teacher name, we can create a relationship
between the two tables.

Teacher ID DeptCode Fname Lname

B002 002 David Warner

B017 002 Sara Joseph

B009 001 Mike Brunton

This concept is also known as Referential Integrity.

What is the Compound key?

Compound key has many fields which allow you to uniquely recognize a specific record. It is possible that
each column may be not unique by itself within the database. However, when combined with the other
column or columns the combination of composite keys become unique.

Example:

OrderNo PorductID Product Name Quantity

B005 JAP102459 Mouse 5

B005 DKT321573 USB 10

B005 OMG446789 LCD Monitor 20

B004 DKT321573 USB 15

B002 OMG446789 Laser Printer 3

In this example, OrderNo and ProductID can't be a primary key as it does not uniquely identify a record.
However, a compound key of Order ID and Product ID could be used as it uniquely identified each record.

What is the Composite key?

5
A key which has multiple attributes to uniquely identify rows in a table is called a composite key. The
difference between compound and the composite key is that any part of the compound key can be a foreign
key, but the composite key may or maybe not a part of the foreign key.

What is a Surrogate Key?

An artificial key which aims to uniquely identify each record is called a surrogate key. These kind of key are
unique because they are created when you don't have any natural primary key. They do not lend any
meaning to the data in the table. Surrogate key is usually an integer.

Fname Lastname Start Time End Time

Anne Smith 09:00 18:00

Jack Francis 08:00 17:00

Anna McLean 11:00 20:00

Shown Willam 14:00 23:00

Above, given example, shown shift timings of the different employee. In this example, a surrogate key is
needed to uniquely identify each employee.

Surrogate keys are allowed when

 No property has the parameter of the primary key.


 In the table when the primary key is too big or complicated.

Difference Between Primary key & Foreign key

Primary Key Foreign Key

Helps you to uniquely identify a It is a field in the table that is the primary key
record in the table. of another table.

Primary Key never accept null values. A foreign key may accept multiple null
values.

Primary key is a clustered index and A foreign key cannot automatically create an
data in the DBMS table are physically index, clustered or non-clustered. However,
organized in the sequence of the you can manually create an index on the

6
clustered index. foreign key.

You can have the single Primary key You can have multiple foreign keys in a
in a table. table.

Summary

 A DBMS key is an attribute or set of an attribute which helps you to identify a row(tuple) in a
relation(table)
 DBMS keys allow you to establish a relationship between and identify the relation between tables
 Seven Types of DBMS keys are Super, Primary, Candidate, Alternate, Foreign, Compound,
Composite, and Surrogate Key.
 A super key is a group of single or multiple keys which identifies rows in a table.
 A column or group of columns in a table which helps us to uniquely identifies every row in that table
is called a primary key
 All the keys which are not primary key are called an alternate key
 A super key with no repeated attribute is called candidate key
 A compound key is a key which has many fields which allow you to uniquely recognize a specific
record
 A key which has multiple attributes to uniquely identify rows in a table is called a composite key
 An artificial key which aims to uniquely identify each record is called a surrogate key
 Primary Key never accept null values while a foreign key may accept multiple null values.

SQL Clauses

The following are the various SQL clauses:

1. GROUP BY

o SQL GROUP BY statement is used to arrange identical data into groups. The
GROUP BY statement is used with the SQL SELECT statement.
o The GROUP BY statement follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
o The GROUP BY statement is used with aggregation function.

Syntax
7
SELECT column FROM table_name WHERE conditions GROUP BY column
ORDER BY column

Sample table:

PRODUCT_MAST

PRODUCT COMPAN QTY RATE COST


Y

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example:
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2

8
2. HAVING

o HAVING clause is used to specify a search condition for a group or an


aggregate.
o Having is used in a GROUP BY clause. If you are not using GROUP BY clause
then you can use HAVING function like a WHERE clause.

Syntax:

SELECT column1, column2 FROM table_name


WHERE conditions GROUP BY column1, column2
HAVING conditions ORDER BY column1, column2;

Example:

SELECT COMPANY, COUNT(*)


FROM PRODUCT_MAST GROUP BY COMPANY
HAVING COUNT(*)>2;
Output:
Com1 5
Com2 3

3. ORDER BY

o The ORDER BY clause sorts the result-set in ascending or descending order.


o It sorts the records in ascending order by default. DESC keyword is used to sort
the records in descending order.

Syntax:

1. SELECT column1, column2


2. FROM table_name
3. WHERE condition
4. ORDER BY column1, column2... ASC|DESC;

Where

ASC: It is used to sort the result set in ascending order by expression.

9
DESC: It sorts the result set in descending order by expression.

Example: Sorting Results in Ascending Order


Table:
CUSTOMER

CUSTOMER_I NAME ADDRESS


D

12 Kathrin US

23 David Bangkok

34 Alina Dubai

45 John UK

56 Harry US

Enter the following SQL statement:


1. SELECT * FROM CUSTOMER ORDER BY NAME;
Output:

CUSTOMER_ID NAME ADDRESS

34 Alina Dubai

23 David Bangkok

56 Harry US

45 John UK

12 Kathrin US

10
Example: Sorting Results in Descending Order

Using the above CUSTOMER table

1. SELECT *
2. FROM CUSTOMER
3. ORDER BY NAME DESC;

Output:

CUSTOMER_ID NAME ADDRESS

12 Kathrin US

45 John UK

56 Harry US

23 David Bangkok

34 Alina Dubai

Views
N A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one
or many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
 Structure data in a way that users or classes of users find natural or intuitive.
 Restrict access to the data in such a way that a user can see and (sometimes)
modify exactly what they need and no more.
 Summarize data from various tables which can be used to generate reports.
11
Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from a
single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you use them in a
normal SQL SELECT query.

Example
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example to create a view from the CUSTOMERS table. This view would be used
to have customer name and age from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;

Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table.
Following is an example for the same.
SQL > SELECT * FROM CUSTOMERS_VIEW;

This would produce the following result.


+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
12
+----------+-----+

SQL - Using Joins


The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN
is a means for combining fields from two tables by using values common to each.
Consider the following two tables −
Table 1 − CUSTOMERS Table
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Table 2 − ORDERS Table


+-----+---------------------+-------------+--------+
|OID | DATE | CUSTOMER_ID | AMOUNT |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+-----+---------------------+-------------+--------+

Now, let us join these two tables in our SELECT statement as shown below.
SQL> SELECT ID, NAME, AGE, AMOUNT
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result.


+----+----------+-----+--------+
| ID | NAME | AGE | AMOUNT |
+----+----------+-----+--------+
| 3 | kaushik | 23 | 3000 |
| 3 | kaushik | 23 | 1500 |
| 2 | Khilan | 25 | 1560 |
| 4 | Chaitali | 25 | 2060 |
+----+----------+-----+--------+
Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be
used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be
used to join tables. However, the most common operator is the equal to symbol.

13
SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the database
very fast.
o An Index is used to speed up select queries and where clauses. But it shows
down the data input with insert and update statements. Indexes can be created
or dropped without affecting the data.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a certain
topic, you first have to refer to the index, which alphabetically lists all the topics
and then referred to one or more specific page numbers.

1. Create Index statement


It is used to create an index on a table. It allows duplicate value.

Syntax

1. CREATE INDEX index_name


2. ON table_name (column1, column2, ...);

Example

1. CREATE INDEX idx_name


2. ON Persons (LastName, FirstName);

2. Unique Index statement


It is used to create a unique index on a table. It does not allow duplicate value.

Syntax

1. CREATE UNIQUE INDEX index_name


2. ON table_name (column1, column2, ...);

Example

1. CREATE UNIQUE INDEX websites_idx


2. ON websites (site_name);

14
3. Drop Index Statement
It is used to delete an index in a table.

Syntax

1. DROP INDEX index_name;

Example

1. DROP INDEX websites_idx;

SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means
"to combine two or more tables".
In SQL, JOIN clause is used to combine the records from two or more tables in a
database.

Types of SQL JOIN


1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN

Sample Table
EMPLOYEE

EMP_I EMP_NAM CITY SALAR AG


D E Y E

1 Angelina Chicago 200000 30

2 Robert Austin 300000 26

15
3 Christian Denver 100000 42

4 Kristen Washingto 500000 29


n

5 Russell Los angels 200000 36

6 Marry Canada 600000 48

PROJECT

PROJECT_NO EMP_ID DEPARTMENT

101 1 Testing

102 2 Development

103 3 Designing

104 4 Development

1. INNER JOIN
In SQL, INNER JOIN selects records that have matching values in both tables as long
as the condition is satisfied. It returns the combination of all rows from both the
tables where the condition satisfies.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. INNER JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. INNER JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

16
EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

2. LEFT JOIN
The SQL left join returns all the values from left table and the matching values from
the right table. If there is no matching join value, it will return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. LEFT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. LEFT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

17
Russell NULL

Marry NULL

3. RIGHT JOIN
In SQL, RIGHT JOIN returns all the values from the values from the rows of right
table and the matched values from the left table. If there is no matching in both
tables, it will return NULL.
Syntax
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. RIGHT JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. RIGHT JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

4. FULL JOIN
In SQL, FULL JOIN is the result of a combination of both left and right outer join. Join
tables have all the records from both tables. It puts NULL on the place of matches not
found.
Syntax
18
1. SELECT table1.column1, table1.column2, table2.column1,....
2. FROM table1
3. FULL JOIN table2
4. ON table1.matching_column = table2.matching_column;
Query
1. SELECT EMPLOYEE.EMP_NAME, PROJECT.DEPARTMENT
2. FROM EMPLOYEE
3. FULL JOIN PROJECT
4. ON PROJECT.EMP_ID = EMPLOYEE.EMP_ID;
Output

EMP_NAME DEPARTMENT

Angelina Testing

Robert Development

Christian Designing

Kristen Development

Russell NULL

Marry NULL

SQL Aggregate Functions


o SQL aggregation function is used to perform the calculations on multiple rows of
a single column of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

1. COUNT FUNCTION
19
o COUNT function is used to Count the number of rows in a database table. It can
work on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
20
Example: COUNT with WHERE
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
7

Example: COUNT() with DISTINCT


1. SELECT COUNT(DISTINCT COMPANY)
2. FROM PRODUCT_MAST;
Output:
3

Example: COUNT() with GROUP BY


1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;
Output:
Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING


1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;
Output:
Com1 5
Com2 3

2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
21
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670

Example: SUM() with WHERE


1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320

Example: SUM() with GROUP BY


1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170

Example: SUM() with HAVING


1. SELECT COMPANY, SUM(COST)
2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;
Output:
Com1 335
Com3 170

3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG
function returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:

22
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00

4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30

5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10

23

You might also like