0% found this document useful (0 votes)
18 views25 pages

Wa0012.

The document discusses SQL commands and their usage. SQL is used to manage and retrieve data from relational databases. The document also provides examples of creating databases and tables in SQL, inserting data, and using SELECT statements to retrieve data.

Uploaded by

kaleprathmesh60
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)
18 views25 pages

Wa0012.

The document discusses SQL commands and their usage. SQL is used to manage and retrieve data from relational databases. The document also provides examples of creating databases and tables in SQL, inserting data, and using SELECT statements to retrieve data.

Uploaded by

kaleprathmesh60
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/ 25

Practical Questions on RDBMS (based on CS-312T)

Q. 1. What is SQL?
SQL is a database language designed for the retrieval and management of data
in a relational database. SQL is the standard language for database management.
SQL programming language uses various commands for different operations.
SQL Commands:
o SQL commands are instructions. It is used to communicate with the
database. It is also used to perform specific tasks, functions, and queries
of data.
o SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, and set permission for users.
Structured Query Language (SQL) Commands from the name itself it’s very
obvious that we are going to discuss different SQL Commands. SQL is the
foundation of relational databases, which are one of the most common
databases. As a result, SQL abilities are required in almost every employment
role. In this blog on SQL Commands, SQL is the industry standard for database
management. It is a database language that allows you to manage and retrieve
data from relational databases. All relational database management systems
(RDBMS) like SQL Server, MySQL, Oracle, Sybase, Postgres, MS-Access use
SQL as their standard database language.

Q. 2. Why Use SQL?


Here, are important reasons for using SQL
 It helps users to access data in the RDBMS system.
 It helps you to describe the data.
 It allows you to define the data in a database and manipulate that specific
data.
 With the help of SQL commands in DBMS, you can create and drop
databases and tables.
 SQL offers you to use the function in a database, create a view, and stored
procedure.
 You can set permissions on tables, procedures, and views.
 Permissions for users can be configured on tables, processes, and views.
Types of SQL Commands
There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)
o DDL changes the structure of the table like creating a table, deleting a
table, altering a table, etc.
o All the command of DDL are auto-committed that means it permanently
save all the changes in the database.
Here are some commands that come under DDL:
o CREATE
o ALTER
o DROP
o TRUNCATE
2. Data Manipulation Language
o DML commands are used to modify the database. It is responsible for all
form of changes in the database.
o The command of DML is not auto-committed that means it can't
permanently save all the changes in the database. They can be rollback.
Here are some commands that come under DML:
o INSERT
o UPDATE
o DELETE

3. Data Control Language


DCL commands are used to grant and take back authority from any database
user.
Here are some commands that come under DCL:
o Grant
o Revoke
4. Transaction Control Language
TCL commands can only use with DML commands like INSERT, DELETE and
UPDATE only.
These operations are automatically committed in the database that's why they
cannot be used while creating tables or dropping them.
Here are some commands that come under TCL:
o COMMIT
o ROLLBACK
o SAVEPOINT
5. Data Query Language
DQL is used to fetch the data from the database.
It uses only one command:
o SELECT
Q. 3. What is a Primary Key in SQL?
 A Primary key is a unique column we set in a table to easily identify and
locate data in queries. A table can have only one primary key.
 The primary key column has a unique value and doesn’t store repeating
values. A Primary key can never take NULL values.

Q.4. What is a Foreign key in SQL?


 A Foreign key is beneficial when we connect two or more tables so that
data from both can be put to use parallels.
 A foreign key is a field or collection of fields in a table that refers to the
Primary key of the other table. It is responsible for managing the
relationship between the tables.
 The table which contains the foreign key is often called the child table,
and the table whose primary key is being referred by the foreign key is
called the Parent Table.

Q.5. Difference between Primary and Foreign Key


Sr.
Primary Key Foreign Key
No
1 Used to maintain the unique Used to maintain the relationship between
identification of data in the two or more relational tables.
table.
Helps us to identify data in a Helps to identify the data in another table
2
database table. using the connection with the foreign key.
A table can have only one A table can have any number of
3
Primary Key. Foreign Keys.
The primary key is unique and A foreign key can contain duplicate
4
Not Null. values also.
Primary key can’t take Null as
5 A foreign key can take NULL entries also.
a value.
Primary Key can’t be modified A foreign key can be modified at any
6
once entered. instance of time.
We can have Primary keys for We can’t have Foreign keys for the
7
temporary tables as well. temporary tables.
A Primary key can be defined For defining a Foreign key, we need a
8
on its own. parent table with a Primary Key.
Primary key creates clustered Foreign key does not create indexes on
9
indexes on the table. the table neither clustered nor unclustered.

**Create a database and tables using SQL commands:

Consider the following two tables for reference while to solve the SQL
queries for practical.
• Table – EmployeeDetails
• Table – EmployeeSalary
First create database:
mysql> create database EmployeeDetails;
Query OK, 1 row affected (0.00 sec)
Change the database:
mysql> use EmployeeDetails;
Database changed

Q. 1. Write a MYSQL statement to create a table name EmployeeDetails


including columns EmpId, FullName, ManagerId, DateOfJoining, City;
Ans: mysql> create table EmployeeDetails(EmpId int(4), FullName
varchar(15), ManagerId int(4), DateOfJoining date, City varchar(10));
Query OK, 0 rows affected (0.55 sec)
**Insert data into tables using SQL queries
Q. 2. Which query is used to insert the values in the table?
Ans: Insert statement is a DML (Data modification language) statement is used
to insert data in the MySQL table. Using the Insert query, we can add one or
more rows in the table. Following is the basic syntax of the MySQL INSERT
Statement.
mysql> insert into EmployeeDetails values(121,'John
Snow',321,20140131,'Toronto'),(321,'Walter White',
986,20150130,'California'),(421,'Kuldeep Rana’,876,20161127,’New
Delhi’),(244, 'RanjeetRavat',651,20141021,'Mumbai'),(610,'Sanjay
Pawar',540,20100522,'Chennai'),(110, 'jaya Kumari',350,20170228,'Pune'),(245,
'Shruti Sharma',148, 20160827, 'Jalna'), (127,'Sandeep Rajput', 345,
20130417,'Beed'), (213,'John Dsouja',114,20190902,'London'),(753,'Ritesh
Deshmukh',165,20150529,'America');
Query OK, 10 rows affected (0.18sec)
Records: 10 Duplicates: 0 Warnings: 0
**Use SELECT statement to retrieve data from tables
Q. 3. How to find the record of tables in the MySQL database.
Ans: mysql> select*from EmployeeDetails;
+-------+--------------------+--------------+------------------+----------------+
| EmpId | FullName | ManagerId | DateOfJoining | City |
+-------+--------------------+--------------+------------------+---------------+
| 121 | John Snow | 321 | 2014-01-31 | Toronto |
| 321 | Walter White | 986 | 2015-01-30 | California |
| 421 | Kuldeep Rana | 876 | 2016-11-27 | New Delhi |
| 244 | Ranjeet Ravat | 651 | 2014-10-21 | Mumbai |
| 610 | Sanjay Pawar | 540 | 2010-05-22 | Chennai |
| 110 | jaya Kumari | 350 | 2017-02-28 | Pune |
| 245 | Shruti Sharma | 148 | 2016-08-27 | Jalna |
| 127 | Sandeep Rajput | 345 | 2013-04-17 | Beed |
| 213 | John Dsouja | 114 | 2019-09-02 | London |
| 753 | Ritesh Deshmukh | 165 | 2015-05-29 | America |
+------+-----------------------+------------+-----------------+---------------------+
10 rows in set (0.00 sec)
Q.4. Write a MYSQL statement to create a table name EmployeeSalary
including columns EmpId, Project, Salary, and Bonus.
Ans: create table EmployeeSalary(EmpId int(4),Project varchar(3),Salary int(6),
Bonus int(5));
Query OK, 0 rows affected (0.52 sec)
Q. 5. Which Statement is used to insert the values in EmployeeSalary
table?
Ans: insert into EmployeeSalary
values(121,P1,8000,500),(321,P2,10000,1000),(421,P1,12000,0),(424,P3,20
000,700),(420,P2,7000,400),(340,P4,7500,750),(540,P5,30000,950),(225,P6,11
000,200),(220,P5,13000,900),(223,P3,18000,999);
Query OK, 10 rows affected (0.18 sec)
Records: 10 Duplicates: 0 Warnings: 0
Q. 6. How to find the record in the MySQL database.
Ans: mysql> select*from EmployeeSalary;
+--------+---------+---------+------------+
| EmpId | Project | Salary | Bonus |
+--------+----------+----------+----------+
| 121 | P1 | 8000 | 500 |
| 321 | P2 | 10000 | 1000 |
| 421 | P1 | 12000 | 0 |
| 424 | P3 | 20000 | 700 |
| 420 | P2 | 7000 | 400 |
| 340 | P4 | 7500 | 750 |
| 540 | P5 | 30000 | 950 |
| 225 | P6 | 11000 | 200 |
| 220 | P5 | 13000 | 900 |
| 223 | P3 | 18000 | 999 |
+--------+------------+---------+------------+
10 rows in set (0.00 sec)
**Use WHERE clause to filter data in SELECT statements
Q. 7. Write an SQL query to get the employees whose name begins with any
two characters, followed by a text “hn” and ending with any sequence of
characters.
Ans. For this query, we can create an SQL query using like operator with ‘_’ and
‘%’ wild card characters, where ‘_’ matches a single character and ‘%’ matches
‘0 or multiple characters’.
mysql> SELECT FullName FROM EmployeeDetails WHERE FullName
LIKE'__hn%';
+------------- +
| FullName |
+-------------+
| John Snow |
| John Dsouja |
+------------- +
2 rows in set (0.00 sec)
Q. 8. Write an SQL query to get all the EmpIds which are present in either
of the tables – ‘EmployeeDetails’ and ‘EmployeeSalary’.
Ans. In order to get unique employee ids from both the tables, we can use
Union clause which can combine the results of the two SQL queries and return
unique rows.
Ans: mysql> SELECT EmpId FROM EmployeeDetails UNION SELECT
EmpId FROM EmployeeSalary;
+-------+
| EmpId |
+-------+
| 121 |
| 321 |
| 421 |
| 244 |
| 610 |
| 110 |
| 245 |
| 127 |
| 213 |
| 753 |
| 424 |
| 420 |
| 340 |
| 540 |
| 225 |
| 220 |
| 223 |
+-------+
17 rows in set (0.00 sec)

Q. 9. Write an SQL query to get all the EmpIds which are present in either
of the tables – ‘EmployeeDetails’ and ‘EmployeeSalary’.
Ans. In order to get unique employee ids from both the tables, we can use
Union clause which can combine the results of the two SQL queries and return
unique rows.
Ans: mysql> SELECT EmpId FROM EmployeeDetails where EmpId IN
(SELECT EmpId FROM EmployeeSalary);
+-------+
| EmpId |
+-------+
| 121 |
| 321 |
| 421 |
+-------+
3 rows in set (0.01 sec)
Q. 10. Write an SQL query to get the EmpIds that are present in
EmployeeDetails but not in EmployeeSalary.
Ans. Using sub query-
Ans: mysql> SELECT EmpId FROM EmployeeDetails where EmpId Not IN
(SELECT EmpId FROM EmployeeSalary);
+-------+
| EmpId |
+-------+
| 244 |
| 610 |
| 110 |
| 245 |
| 127 |
| 213 |
| 753 |
+-------+
7 rows in set (0.01 sec)
Q. 11. Write an SQL query to get the employee full names and replace the
space with ‘-’.
Ans. Using ‘Replace’ function-
mysql> SELECT REPLACE(FullName,'','-')FROM EmployeeDetails;
+--------------------------+
| REPLACE(FullName,'','-') |
+--------------------------+
| John Snow |
| Walter White |
| Kuldeep Rana |
| Ranjeet Ravat |
| Sanjay Pawar |
| jaya Kumari |
| Shruti Sharma |
| Sandeep Rajput |
| John Dsouja |
| Ritesh Deshmukh |
+--------------------------+
10 rows in set (0.01 sec)
Q. 12. Write an SQL query to get the position of a given character(s) in a
field.
Ans. Using ‘Instr’ function-
mysql> SELECT INSTR('FullName','Snow')FROM EmployeeDetails;
+------------------------+
| INSTR('FullName','Snow') |
+------------------------+
| 6|
| 0|
| 0|
| 0|
| 0|
| 0|
| 0|
| 0|
| 0|
| 0|
+------------------------+
10 rows in set (0.00 sec)
Q. 13. Write an SQL query to display both the EmpId and ManagerId
together.
Ans. Here we can use the CONCAT command.
mysql> SELECT CONCAT(EmpId,ManagerId) as NewId FROM
EmployeeDetails;
+--------+
| NewId |
+--------+
| 121321 |
| 321986 |
| 421876 |
| 244651 |
| 610540 |
| 110350 |
| 245148 |
| 127345 |
| 213114 |
| 753165 |
+--------+
10 rows in set (0.00 sec)
Q. 14. Write a query to get only the first name(string before space) from
the FullName column of the EmployeeDetails table.
Ans. In this question, we are required to first get the location of the space
character in the FullName field and then extract the first name out of the
FullName field.
For finding the location we will use the LOCATE method in MySQL and
CHARINDEX in SQL SERVER and for fetching the string before space, we
will use the SUBSTRING OR MID method.
MySQL – using MID
mysql> SELECT MID(FullName,1,LOCATE('',FullName)) FROM
EmployeeDetails;
+-----------------------------------------------------+
| MID('FullName',1,LOCATE('FullName'); |
+-----------------------------------------------------+
|J |
|W |
|K |
|R |
|S |
|j |
|S |
|S |
|J |
|R |
+----------------------------------------------------+
10 rows in set (0.01 sec)
Q. 15. Write an SQL query to upper case the name of the employee and
lower case the city values.
Ans. We can use SQL Upper and Lower functions to achieve the intended
results.
mysql> SELECT UPPER('FullName'),LOWER('City') FROM
EmployeeDetails;
+-----------------+--------------------------+
| UPPER('FullName') | LOWER('City') |
+-----------------+--------------------------+
| JOHN SNOW | toronto |
| WALTER WHITE | california |
| KULDEEP RANA | new delhi |
| RANJEET RAVAT | mumbai |
| SANJAY PAWAR | chennai |
| JAYA KUMARI | pune |
| SHRUTI SHARMA | jalna |
| SANDEEP RAJPUT | beed |
| JOHN DSOUJA | london |
| RITESH DESHMUKH | America |
+-----------------+--------------------------+
10 rows in set (0.00 sec)

Q. 16. Write an SQL query to find the count of the total occurrences of a
particular character – ‘n’ in the FullName field.
Ans. Here, we can use the ‘Length’ function. We can subtract the total length of
the FullName field with a length of the FullName after replacing the character –
‘n’.
mysql> SELECT FullName, LENGTH('FullName') -
LENGTH(REPLACE('FullName','n',''))FROM EmployeeDetails;
+----------------- +-----------------------------------------------------+
| FullName LENGTH(FullName) -
LENGTH(REPLACE('FullName','n','')) |
+----------------- +-----------------------------------------------------+
| John Snow | 2|
| Walter White | 0|
| Kuldeep Rana | 1|
| Ranjeet Ravat | 1|
| Sanjay Pawar | 1|
| jaya Kumari | 0|
| Shruti Sharma | 0|
| Sandeep Rajput | 1|
| John Dsouja | 1|
| Ritesh Deshmukh | 0|
+-----------------+-----------------------------------------------------+
10 rows in set (0.00 sec)
**Update existing data in tables using SQL queries
Q. 17. Write an SQL query to update the employee names by removing
leading and trailing spaces.
Ans. Using the ‘Update’ command with the ‘LTRIM’ and ‘RTRIM’ function.
mysql> UPDATE EmployeeDetails SET
FullName=LTRIM(RTRIM('FullName'));
Query OK, 0 rows affected (0.01 sec)
Rows matched: 10 Changed: 0 Warnings: 0

Q. 18. Get all the employees who are not working on any project.
Ans. Commonly used – Is NULL operator.
mysql> SELECT EmpId FROM EmployeeSalary WHERE Project IS NULL;
Empty set (0.00 sec)
Q. 19. Write an SQL query to get employee names having a salary greater
than or equal to 5000 and less than or equal to 10000.
Ans. Here, we will use BETWEEN in the ‘where’ clause to return the EmpId of
the employees with salary satisfying the required criteria and then use it as
subquery to find the fullName of the employee from EmployeeDetails table.
mysql> SELECT FullName FROM EmployeeDetails WHERE EmpId IN
(SELECT EmpId FROM EmployeeSalary WHERE Salary BETWEEN 5000
AND 10000);
+----------------+
| FullName |
+----------------+
| John Snow |
| Walter White |
+-----------------+
2 rows in set (0.00 sec)
Q. 20. Write an SQL query to find the current date-time.
mysql> SELECT NOW();SQL Server- SELECT getdate();
+---------------------+
| NOW() |
+---------------------+
| 2021-12-31 12:31:34 |
+---------------------+
1 row in set (0.00 sec)
Q. 21. Write an SQL query to get all the Employees details from
EmployeeDetails table that joined in the Year 2020.
Ans. Using BETWEEN for the date range ’01-01-2020′ AND ’31-12-2020′-
mysql> SELECT * FROM EmployeeDetails WHERE DateOfJoining
BETWEEN '2020/01/01'AND'2020/12/31';
Empty set (0.00 sec)
Also, we can extract year part from the joining date (using YEAR in mySQL)-
mysql> SELECT*FROM EmployeeDetails WHERE
YEAR(DateOfJoining)='2020';
Empty set (0.00 sec)
Q. 22. Write an SQL query to get all employee records from
EmployeeDetails table who have a salary record in EmployeeSalary table.
Ans. Using ‘Exists’-
mysql> SELECT * FROM EmployeeDetails E WHERE EXISTS (SELECT *
FROM EmployeeSalary S WHERE E.EmpId=S.EmpId);
+-------+--------------+-----------+---------------+---------------------+
| EmpId | FullName | ManagerId | DateOfJoining | City |
+-------+------------------+-----------+---------------+-----------------+
| 121 | John Snow | 321 | 2014-01-31 | Toronto |
| 321 | Walter White | 986 | 2015-01-30 | California |
| 421 | Kuldeep Rana | 876 | 2016-11-27 | New Delhi |
+-------+--------------+-----------+---------------+------------+
3 rows in set (0.00 sec)
Q. 23. Write an SQL query to get project-wise count of employees sorted by
project’s count in descending order.
Ans. The query has two requirements – first to fetch the project-wise count and
then to sort the result by that count.
For project-wise count, we will be using the GROUP BY clause and for sorting,
we will use the ORDER BY clause on the alias of the project-count.
mysql> SELECT Project,count(EmpId)EmpProjectCount FROM
EmployeeSalary GROUP BY Project ORDER BY EmpProjectCount DESC;
+---------+-----------------------+
| Project | EmpProjectCount |
+---------+-----------------------+
| P1 | 2 |
| P2 | 2 |
| P3 | 2 |
| P5 | 2 |
| P4 | 1 |
| P6 | 1 |
+---------+-----------------------+
6 rows in set (0.00 sec)
Q. 24. Write a query to get employee names and salary records. Display the
employee details even if the salary record is not present for the employee.
Ans. This is again one of the very common interview questions in which the
interviewer just wants to check the basic knowledge of SQL JOINS.
Here, we can use left join with EmployeeDetail table on the left side of the
EmployeeSalary table.
mysql> SELECT E.FullName,S.Salary FROM EmployeeDetails E LEFT JOIN
EmployeeSalary S ON E.EmpId=S.EmpId;
+--------------------+--------------+
| FullName | Salary |
+--------------------+------------+
| John Snow | 8000 |
| Walter White | 10000 |
| Kuldeep Rana | 12000 |
| Ranjeet Ravat | NULL |
| Sanjay Pawar | NULL |
| jaya Kumari | NULL |
| Shruti Sharma | NULL |
| Sandeep Rajput | NULL |
| John Dsouja | NULL |
| Ritesh Deshmukh | NULL |
+-----------------+----------------+
10 rows in set (0.00 sec
Q. 25. Write an SQL get to get all the Employees who are also managers
from the EmployeeDetails table.
Ans. Here, we have to use Self-Join as the requirement wants us to analyze the
EmployeeDetails table as two tables. We will use different aliases ‘E’ and ‘M’
for the same EmployeeDetails table.
mysql> SELECT DISTINCT E.FullName FROM EmployeeDetails E INNER
JOIN EmployeeDetails M ON E.EmpID=M.ManagerID;
+----------------+
| FullName |
+----------------+
| Walter White |
+----------------+
1 row in set (0.00 sec)
Q. 26. Write an SQL query to get duplicate records from EmployeeDetails
(without considering the primary key – EmpId).
Ans. In order to find duplicate records from the table, we can use GROUP BY
on all the fields and then use the HAVING clause to return only those fields
whose count is greater than 1 i.e. the rows having duplicate records.
mysql> SELECT FullName,ManagerId, DateOfJoining,City, COUNT(*)
FROM EmployeeDetails GROUP BY FullName,
ManagerId,DateOfJoining,City HAVING COUNT(*)>1;
Empty set (0.00 sec).
**Delete data from tables using SQL queries
Q. 27. Write an SQL query to remove duplicates from a table without using
a temporary table.
Ans. Here, we can use delete with dubbed and inner join. We will check for the
equality of all the matching records and then remove the row with higher
EmpId.
mysql> DELETE E1 FROM EmployeeDetails E1 INNER JOIN
EmployeeDetails E2 WHERE E1.EmpId>E2.EmpId AND
E1.FullName=E2.FullName AND E1.ManagerId=E2.managerId AND
E1.DateOfJoining=E2.DateOfJoining AND E1.City=E2.City;
Query OK, 0 rows affected (0.00 sec)
** Use data normalization techniques to design and create efficient
database schemas.

Database normalization or SQL normalization helps us to group related data in


one single table. Any attributive data or indirectly related data are put in
different tables and these tables are connected with a logical relationship
between parent and child tables.

In 1970, Edgar F. Codd came up with the concept of normalization. He shared a


paper named “A Relational Model of Data for Large Shared Banks” in which he
proposed “First Normal Form (1NF)”.

Advantages of DBMS Normalization:

Database Normalization provides the following basic advantages:


1. Normalization increases data consistency as it avoids the duplicity of data
by storing the data in one place only.
2. Normalization helps in grouping like or related data under the same
schema, thereby resulting in the better grouping of data.
3. Normalization improves searching faster as indexes can be created faster.
Hence, the normalized database or table is used for OLTP (Online
Transaction Processing).
Disadvantages of Database Normalization:

DBMS Normalization has the following disadvantages:


1. We cannot find the associated data for, say a product or employee in one
place and we have to join more than one table. This causes a delay in
retrieving the data.
2. Thus, Normalization is not a good option in OLAP transactions (Online
Analytical Processing).

Normalization database with normalization example with solution:


1NF (First Normal Form) Rules

 Each table cell should contain a single value.


 Each record needs to be unique.

The above table in 1NF-

1NF Example

Example of 1NF in DBMS

What is a KEY in SQL


A KEY in SQL is a value used to identify records in a table uniquely. An SQL
KEY is a single column or combination of multiple columns used to uniquely
identify rows or tuples in the table. SQL Key is used to identify duplicate
information, and it also helps establish a relationship between multiple tables in
the database.
Note: Columns in a table that are NOT used to identify a record uniquely are
called non-key columns.

What is a Primary Key?

Primary Key in DBMS


A primary is a single column value used to identify a database record uniquely.It
has following attributes
 A primary key cannot be NULL
 A primary key value must be unique
 The primary key values should rarely be changed
 The primary key must be given a value when a new record is inserted.

What is Composite Key?


A composite key is a primary key composed of multiple columns used to
identify a record uniquely

In our database, we have two people with the same name Robert Phil, but they
live in different places.

Composite key in Database


Hence, we require both Full Name and Address to identify a record uniquely.
That is a composite key.

2NF (Second Normal Form) Rules


 Rule 1- Be in 1NF
 Rule 2- Single Column Primary Key that does not functionally dependant
on any subset of candidate key relation

It is clear that we can’t move forward to make our simple database in


2nd Normalization form unless we partition the table above.
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1
contains member information. Table 2 contains information on movies rented.

We have introduced a new column called Membership_id which is the primary


key for table 1. Records can be uniquely identified in Table 1 using membership
id

Database – Foreign Key


In Table 2, Membership_ID is the Foreign Key

Foreign Key in DBMS


Foreign Key references the primary key of another Table! It helps connect your
Tables

 A foreign key can have a different name from its primary key
 It ensures rows in one table have corresponding rows in another
 Unlike the Primary key, they do not have to be unique. Most often they
aren’t
 Foreign keys can be null even though primary keys can not
Why do you need a foreign key?
Suppose, a novice inserts a record in Table B such as
You will only be able to insert values into your foreign key that exist in the
unique key in the parent table. This helps in referential integrity.

The above problem can be overcome by declaring membership id from Table2


as foreign key of membership id from Table1

Now, if somebody tries to insert a value in the membership id field that does not
exist in the parent table, an error will be shown!

What are transitive functional dependencies?


A transitive functional dependency is when changing a non-key column, might
cause any of the other non-key columns to change

Consider the table 1. Changing the non-key column Full Name may change
Salutation.

3NF (Third Normal Form) Rules

 Rule 1- Be in 2NF
 Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.

3NF Example
Below is a 3NF example in SQL database:

We have again divided our tables and created a new table which stores
Salutations.

There are no transitive functional dependencies, and hence our table is in 3NF

In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign


to primary key in Table 3.

You might also like