1 of 125

INFORMATION TECHNOLOGY�SUBJECT CODE – 802�Grade 12

UNIT 1

DATABASE CONCEPTS

AUTHOR: GAURAV KUMAR VASHISHT

2 of 125

BASIC CONCEPTS

  • Data is a collection of raw facts which have not been processed to reveal useful information.
  • Information is processed data

  • Example:

3 of 125

Definition of Database

  • A collection of related data that has been recorded, organized and made available for searching is called a Database.
  • For example, consider the name, class, roll number, marks in every subject of every student in a school. To record this information about every student in a school, the school might have maintained a register, or stored it on a hard drive using a computer system and software such as a spreadsheet or DBMS package.

4 of 125

Spreadsheet v/s DBMS

  • Spreadsheet is not organised and automated where as DBMS is automated and more organised.
  • Searching and updating a record in database is easy and convenient in databases.
  • Database can be of any size and complexity.

5 of 125

Why database is needed?

  • 1. Data Redundancy: Same information is stored in more than one file. This would result in wastage of space.
  • 2. Data Inconsistency: If a file is updated then all the files containing similar information must be updated else it would result in inconsistency of data.
  • 3. Lack of Data Integration: As data files are independent, accessing information out of multiple files becomes very difficult.
  • Database approach overcomes these problems

6 of 125

For example

  • Consider the Sales and Payroll departments of a company. One user will maintain information about all the salespersons in the Sales department in some file say File1 and another user will maintain details about the payroll of the salesperson in a separate file say File2 in the Payroll Department as shown in Figure
  • Although both the departments need information about the salesperson but they will store information about the salesperson in different files and will use different application programs to access those files.

7 of 125

Data Base Management System (DBMS)

  • A database management system is a collection of programs that enables users to create, maintain and use a database.
  • Thus there is a single repository of data which is accessed by all the application programs

8 of 125

The various operations performed by DBMS:

1. Defining the Database: It involves specifying the data type of data that will be stored in the database and also any constraints on that data.

2. Populating the Database: It involves storing the data on some storage medium that is controlled by DBMS.

3. Manipulating the Database: It involves modifying the database, retrieving data or querying the database, generating reports from the database etc.

4. Sharing the Database: Allow multiple users to access the database at the same time.

5. Protecting the Database: It enables protection of the database from software/ hardware failures and unauthorized access.

6. Maintaining the Database: It is easy to adapt to the changing requirements.

Some examples of DBMS are – MySQL, Oracle, DB2, IMS, IDS etc.

9 of 125

Characteristics of DBMS

  • 1. Self-describing Nature of a Database System: DBMS contains not only the database but also the description of the data that it stores. This description of data is called metadata.
  • 2. Insulation Between Programs and Data: Since the definition of data is stored separately in a DBMS, any change in the structure of data would be done in the catalogue and hence programs which access this data need not be modified. This property is called Program-Data Independence.
  • 3. Sharing of Data: A multiuser environment allows multiple users to access the database simultaneously.

10 of 125

Types of Users of DBMS

  • 1. End Users: Users who use the database for querying, modifying and generating reports as per their needs.
  • 2. Database Administrator (DBA): The DBA is responsible for authoring access, monitoring its use, providing technical support, acquiring software and hardware resources.
  • 3. Application Programmers: Application programmes write application programs to interact with the database.
  • 4. System Analyst: System analyst determines the requirements of the end users and then develops specifications to meet these requirements. A system analyst plays a major role in the database design and all the technical, economic and feasibility aspects.

11 of 125

Advantages of using DBMS Approach

  • 1. Reduction in Redundancy: Data in a DBMS is stored at one place. There is no repetition of the same data. This also reduces the cost of storing data on hard disks or other memory devices.
  • 2. Improved Consistency: The chances of data inconsistencies in a database are also reduced as there is a single copy of data that is accessed or updated by all the users.
  • 3. Improved Availability: Same information is made available to different users. This helps sharing of information by various users of the database.
  • 4. Improved Security: By making use of passwords and controlling users' database access rights, the DBA can provide security to the database.
  • 5. User Friendly: Using a DBMS, it becomes very easy to access, modify and delete data.

12 of 125

Limitations of using DBMS Approach

  • 1. High Cost: The cost of implementing a DBMS system is very high. It is also a very time consuming.
  • 2. Security and Recovery Overheads: Unauthorized access to a database can lead to threat to the individual or organization depending on the data stored. Also the data must be regularly backed up to prevent its loss due to fire, earthquakes, etc.

13 of 125

Relational Database

  • Various types of databases have been developed. One of them was relational database developed by E.F Codd at IBM in 1970. It is used to organize collection of data as a collection of relations . A relation is also referred as table. Each row in the table corresponds to a unique instance of data and each column name is used to interpret the meaning of that data in each row.

14 of 125

  • For example, consider EMPLOYEE table in Figure
  • Each row in this table represents facts about a particular employee. The column names – Name, Employee_ID, Gender, Salary and Date_of_Birth specify how to interpret the data in each row.

15 of 125

Important Terms in Relational Database

  • A row is called a Tuple.
  • A column is called an Attribute.
  • A table is called as a Relation.
  • The data type of values in each column is called the Domain.
  • The number of attributes in a relation is called the Degree of a relation.
  • The number of rows in a relation is called the Cardinality of a relation.
  • Relation Schema R is denoted by R (A , A , A …, A ) where R is the relation name 1 2 3, n and A , A , A ,….A is the list of attributes. 1 2 3 n
  • Relation State is the set of tuples in the relation at a point in time.

16 of 125

  • EMPLOYEE table is a relation.
  • There are three tuples in EMPLOYEE relation.
  • Name, Employee_ID, Gender, Salary, Date_of_Birth are attributes.
  • The domain of a database attribute is the set of all the possible values that attribute may contain. Following are the domain of attributes of the EMPLOYEE relation:

(a) Name – Set of character strings representing names of persons.

(b) Employee_ID–Set of 4-digit numbers

(c) Gender – male or female

(d) Salary – Number

(e) Date_of_Birth – Should have a valid date, month and year in the format dd-mm-yyyy.

  • The degree of the EMPLOYEE relation is 5 as there are five attributes in this relation.
  • The cardinality of the EMPLOYEE relation is 3 as there are three tuples in this relation.
  • Relation Schema – EMPLOYEE (Name, Employee_ID, Gender, Salary, Date_of_Birth)
  • Relation State –{<Neha Mehta, 1121,Female,20000,04-03-1990>,

<Paras Bansal, 2134, Male, 25000, 19-10-1993>,

<Himani Verma, 3145, Female, 20000, 23-11-1992>}

17 of 125

How to remember Cardinality and Degree

  • Cardinality – Number of Rows
  • Degree - Number of Columns

  • Rule: ‘C’ and ‘C’ never matches.
  • i.e. ‘C’ for Cardinality never matches with ‘C’ of Columns.

18 of 125

Some More Characteristics of Relations:

  • Ordering of tuples is not important in a Relation
  • The ordering of attributes is also unimportant.
  • No two tuples of relation should be identical i.e. given any pair of two tuples, value in at least one column must be different.
  • The value in each tuple is an atomic value (indivisible).
  • If the value of an attribute in a tuple is not known or not applicable or not available, a special value called null is used to represent them.
  • For example consider the following cases:
    • Unknown value: A person has a date of birth but it is not known at the time of data entry.
    • Unavailable value: A person has a home phone but does not want it to be listed.
    • Not applicable: College degree attribute would be NULL for a person who has no college degrees.
  • In all the above cases NULL value would be used.

19 of 125

Relational Model Constraints

  • Constraints, are restrictions on the values, stored in a database based on the requirements.
  • For example, in the relation EMPLOYEE, the Employee_ID must be a 4-digit number, the
  • Date_of_Birth must be such that the birth year > 1985.

20 of 125

Domain Constraint:

  • It specifies that the value of every attribute in each tuple must be from the domain of that attribute. For example, the Employee_ID must be a 4-digit number. Hence a value such as “12321” or “A234” violates the domain constraint as the former is not 4-digit long and the latter contains an alphabet.

21 of 125

Null Value Constraint:

  • Sometimes it is required that certain attributes cannot have null values. For example, if every EMPLOYEE must have a valid name then the Name attribute is constrained to be NOT NULL
  • If we apply NOT NULL constraint to any column then we cannot leave any value blank in the column.

22 of 125

Super Key Constraint:

  • Superkey is a set of attributes (columns) in a relation, for which no two tuples in a relation state have the same combination of values.
  • Every relation must have at least one superkey which is the combination of all attributes in a relation
  • For example in table Employee if Gender and Salary column have integer values then {Gender, Salary} is not a superkey because both these attributes have identical values.

23 of 125

  • Candidate key: A key which can have unique value in a table is called candidate key. For example, in the EMPLOYEE relation has three candidate keys as given here:
  • Employee_ID, Name, Date_of Birth
  • All these have unique values. No repetition.

24 of 125

Primary Key

  • Primary Key: One of the candidate keys may be designated as Primary key. Primary key is used to identify tuples in a relation. If a relation has many candidate keys it is preferable to choose that one as primary key which has least number of attributes.
  • Here Employee_ID can be primary

25 of 125

Null Value Constraint

  • Sometimes it is required that certain attributes cannot have null values. For example, if every EMPLOYEE must have a valid name then the Name attribute is constrained to be NOT NULL.

26 of 125

Entity Integrity Constraint

  • This constraint specifies that primary key of a relation cannot have null value. The reason behind this constraint is that we know primary key contains no duplicates. However if we allow null values for a primary key then there can be multiple tuples for which primary key is having null values.

27 of 125

Referential Integrity Constraint

  • This constraint is specified between two relations.
  • Before defining this constraint let us study the concept of foreign keys. Foreign key in a relation R1 is the set of attributes in R1 that refer to primary key in another relation R2 if the domain of foreign key attributes is same as that of primary key attributes and the value of foreign key either occurs as a value of primary key in some tuple of R2 or is NULL.

28 of 125

Structured Query Language (SQL)

  • SQL is a language that is used to manage data stored in a RDBMS. It comprises of a Data Definition Language (DDL) and a Data Manipulation Language (DML) where DDL is a language which is used to define structure and constraints of data and DML is used to insert, modify and delete data in a database.

29 of 125

How to download MySQL

  • The most recent versions can be found on the website: http://dev.mysql.com/downloads/
  • Following are the steps to install and configure MySQL Community Server 5.6.20 for studying SQL commands.
  • 1. Open the URL: http://dev.mysql.com/downloads/mysql/#downloads
  • 2. Download the MySQL Community Server 5.6.20 available on the above webpage.

30 of 125

31 of 125

3. Once you have downloaded the file mysql-installer-community 5.6.20.0.msi, double click on the downloaded file and then click on the “Run” button.

32 of 125

4. MySQL Installer will start installing. Click on the “Install MySQL Products” option.

33 of 125

�5. Check the option “I accept the license terms” and then Click on “Next” button.

34 of 125

6. Then next click on the “Execute” button.

35 of 125

7. On successful execution, click on the “Next” button.

36 of 125

8. Select the “Server only” option. Then click on “Next” button.

37 of 125

9. Installer will check for the requirements. If any requirements are required, you have to download them first before installing MySQL server. If all the requirements are met, then the following message will be displayed. Click “Next” to continue.

38 of 125

10. Click on “Execute” to install MySQL Server 5.6.20.

39 of 125

11. On successful installation, Click on “Next”

40 of 125

12. Click on “Next” to start initial configuration.

41 of 125

13. Select the following configurations and then Click “Next”.

42 of 125

14. Type the MySQL root password (minimum 4 characters long) and then click “Next”

43 of 125

15. Click on “Next” on the following window.

44 of 125

16. Installer will configure the server. On successful configuration, click on “Next”.

45 of 125

17. Then Click on “Finish”. The installation and configuration of MySQL Server 5.6.20 is now complete. You can now start using the server for creating and modifying databases.

46 of 125

Create Table Command

  • This command is used to create a new table or relation. The syntax for this command is :

CREATE TABLE<table name>

(

<column 1><data type> [constraint] ,

<column 2><data type>[constraint],

<column 3><data type>[constraint]

);

where [ ]=optional

47 of 125

  • To create the above relations in SQL, following CREATE TABLE command is used:

CREATE TABLE Teacher

(

Teacher_ID INTEGER,

First_Name VARCHAR(20),

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2),

Date_of_Birth DATE,

Dept_No INTEGER

);

Teacher_ID

First_Name

Last_Name

Gender

Salary

Date_of_Birth

Dept_No

Name of the Table: TEACHER

48 of 125

Commonly used Data types

49 of 125

Creating a Database in MySQL

  • To create a database named school we have to write following command in MySQL .

CREATE DATABASE School;

  • To show the lists of databases in the software we have to write following command:

SHOW DATABASES;

50 of 125

In case you want to remove a database

  • This can be done by using following command:

DROP DATABASE�

51 of 125

To tell the server which database we will use for further statements

  • This can be done by using the USE command.

52 of 125

SHOW TABLES

  • To verify you can use SHOW TABLES command which displays all the tables created in the current database.

53 of 125

Database Constraints: NOT NULL

CREATE TABLE TEACHER

(

Teacher_ID INTEGER,

First_NameVARCHAR(20) NOT NULL,

Last_NameVARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2),

Date_of_Birth DATE,

Dept_No INTEGER

);

54 of 125

Database Constraints: DEFAULT

CREATE TABLE TEACHER

(

Teacher_ID INTEGER,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER

);

55 of 125

If you want to look at the structure and description of the tables created, DESC command can be used

56 of 125

Database Constraints : CHECK

CREATE TABLE TEACHER

(

Teacher_ID INTEGER,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER CHECK (Dept_No<=110)

);

57 of 125

Database Constraints : KEY CONSTRAINT

CREATE TABLE TEACHER

(

Teacher_ID INTEGER PRIMARY KEY,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER

);

58 of 125

If you want to look at the structure and description of the tables created, DESC command can be used

By default, Primary keys are NOT NULL and there is no need to mention this

constraint separately.

59 of 125

COMPOSITE KEY

  • However if primary key contains more than one attribute then it must be specified separately as a list of attributes it comprises of, within parenthesis, separated by commas. For example, the primary key of the TEACHER relation comprises of Teacher_ID and Date_of_Birth.

CREATE TABLE TEACHER

(

Teacher_ID INTEGER,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER,

PRIMARY KEY (Teacher_ID, Date_of_Birth)

);

60 of 125

REFERENTIAL INTEGRITY CONSTRAINT

  • This constraint is specified by using the foreign key clause.
  • For example consider the following tables created in the School Database:
  • Department (Dept_ID, Dept_Name)
  • Teacher (Teacher_ID, First_Name, Last_Name, Gender, Salary, Date_of_Birth, Dept_No)
  • In this example Dept_No is the foreign key that references Dept_ID of Department relation which is a primary key

61 of 125

FOREIGN KEY

CREATE TABLE Department

(

Dept_ID INTEGER PRIMARY KEY,

Dept_Name VARCHAR(20) NOT NULL

);

CREATE TABLE Teacher

(

Teacher_ID INTEGER PRIMARY KEY,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER,

FOREIGN KEY (Dept_No) REFERENCES Department(Dept_ID)

);

62 of 125

DESC Teacher;

63 of 125

CREATE TABLE Department�(�Dept_ID INTEGER PRIMARY KEY,�Dept_Name VARCHAR(20) NOT NULL�);

CREATE TABLE Teacher

(

Teacher_ID INTEGER PRIMARY KEY,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER,

FOREIGN KEY (Dept_No) REFERENCES Department (Dept_ID) ON

DELETE SET NULL ON UPDATE SET NULL

);

Thus if a department with a given value of Dept_ID is deleted in Department table, then the corresponding tuples that contains the deleted value for Dept_No attribute in Teacher table would be set to NULL. Similarly, if Dept_ID value is updated then also the corresponding attribute in Teacher table would be set to NULL.

64 of 125

CREATE TABLE Teacher

(

Teacher_ID INTEGER PRIMARY KEY,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER,

FOREIGN KEY (Dept_No) REFERENCES Department (Dept_ID) ON

DELETE CASCADE ON UPDATE CASCADE

);

In the above table, if a department with a given value of the Dept_ID attribute in Department table is deleted, then the corresponding rows in the Teacher table would also be deleted. However if Dept_ID value is updated in the Department table, the change in corresponding value is also reflected in Teacher Table.

CREATE TABLE Department�(�Dept_ID INTEGER PRIMARY KEY,�Dept_Name VARCHAR(20) NOT NULL�);

65 of 125

CREATE TABLE Teacher

(

Teacher_ID INTEGER PRIMARY KEY,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER,

FOREIGN KEY (Dept_No) REFERENCES Department (Dept_ID) ON

DELETE RESTRICT ON UPDATE RESTRICT

);

RESTRICT option will reject the delete or update operation for the referenced table if there are one or more related foreign key values in a referencing table, i.e, you cannot delete or update a department if there are teachers who belong to that department.

CREATE TABLE Department�(�Dept_ID INTEGER PRIMARY KEY,�Dept_Name VARCHAR(20) NOT NULL�);

66 of 125

Self-Referencing Tables:

  • A foreign key constraint can reference columns within the same table. These tables are called as self-referencing tables.
  • For example,
  • Consider a table Employee that contains five columns: Employee_ID, Name, Age, Salary and Manager_ID. Because the manager is also an employee, there is a foreign key relationship between the Manager_ID and Employee_ID as shown below:

67 of 125

CREATE TABLE Employee

(

Employee_ID INTEGER PRIMARY KEY,

Name VARCHAR(30),

Age INTEGER,

Salary DECIMAL(10,2),

Manager_ID INTEGER,

FOREIGN KEY (Manager_ID) REFERENCES Employee (Employee_ID)

);

68 of 125

Drop Table Command:

  • In MySQL server 5.6.20, you can simply type Drop Table followed by the table name to delete a table from the database. However, it will not allow you to drop a table if the table to be deleted is being referenced in some other table.

69 of 125

Alter Table Command

  • This command is used to modify the base table definition. It allows us to do following things:
  • Adding a column
  • Dropping a column
  • Altering a Column
  • Dropping keys
  • Adding a Constraint

70 of 125

Adding a column:

  • Suppose we want to add a column Age in the Teacher table.
  • Following command is used to add the column:
  • ALTER TABLE Teacher ADD Age INTEGER;

71 of 125

Dropping a column:

  • A column can be dropped using this command. For example:
  • ALTER TABLE Teacher DROP Dept_No
  • But if this column Dept_No is referenced to other table then it will not to deleted. To allow this write the command in this way:
  • ALTER TABLE Teacher DROP Dept_No CASCADE;
  • This will drop the Dept_No column in the Teacher Table and it would also drop the foreign key constraint

72 of 125

Altering a Column

  • A column definition can also be altered. For example – dropping the default value or defining a new default value. For example, in the Teacher table the default value of Salary is 40000. If you want to drop this default value or change this value to 30000 then it can be done by using the following commands:
  • ALTER TABLE Teacher ALTER Salary DROP DEFAULT;
  • ALTER TABLE Teacher ALTER Salary SET DEFAULT 30000;

73 of 125

Dropping keys

  • A foreign key/primary key/key can be dropped by using ALTER TABLE command. For example if you want to delete the foreign key TEACHER_FK in the Teacher table then following command can be used:
  • ALTER TABLE Teacher DROP FOREIGN KEY TEACHER_FK;
  • Primary key can be dropped by using the command:
  • ALTER TABLE Teacher DROP PRIMARY KEY TEACHER_PK;
  • However, primary key cannot be removed if it is the only primary key of the table. Hence the above command will result in an error.

74 of 125

Adding a Constraint

  • In a table if there was no foreign key set at the time of creation, then ff you want to add the foreign key constraint TEACHER_FK , then the command would be:
  • ALTER TABLE Teacher ADD CONSTRAINT TEACHER_FK FOREIGN KEY (Dept_No) REFERENCES Department(Dept_ID) ON DELETE SET NULL ON UPDATE SET NULL;

75 of 125

Insert Command

  • This command is used to insert a tuple in a relation.

CREATE TABLE Teacher

(

Teacher_ID INTEGER,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_No INTEGER,

CONSTRAINT TEACHER_PK PRIMARY KEY (Teacher_ID),

);

  • To insert a tuple in the Teacher table INSERT command can be used as shown below:

INSERT INTO Teacher

VALUES (101,"Shanaya", "Batra", 'F', 50000, '1984-08-11', 1);

76 of 125

Another form of INSERT command

  • Another form of INSERT command is used to insert a tuple in which the ordering of values is done by explicitly specifying the attribute names as shown below:

INSERT INTO Teacher (First_Name, Last_Name, Gender, Teacher_ID, Date_of_Birth, Dept_No, Salary)

VALUES ("Shanaya", "Batra", 'F', 101, '1984-08-11', 1, 50000);

77 of 125

  • In the above example if salary was not specified in the INSERT command, then its default value i.e.40000 as given in the table creation command would have been used as shown below.

INSERT INTO Teacher (First_Name, Last_Name, Gender, Teacher_ID, Date_of_Birth, Dept_No, Salary) VALUES ("Shanaya", "Batra", 'F', 101, '1984-08-11', 1,);

78 of 125

  • If DEFAULT value is also not specified then NULL value is used.
  • INSERT INTO Teacher (First_Name, Last_Name, Gender, Teacher_ID, Date_of_Birth, Dept_No, Salary) VALUES ("Shanaya", "Batra", 'F', 101, '1984-08-11', 1, null);

79 of 125

Update Command:

  • This command is used to update the attribute values of one or more tuples in a table. For example in the Teacher table, we want to update the Salary of teacher with Teacher_ID=101 to 55000. This can be done using the following command:

UPDATE Teacher

SET Salary=55000

WHERE Teacher_ID=101;

80 of 125

  • We can also have an algebraic expression in the SET clause. Suppose it is required to increase the salary of a Teacher Shanaya by 5000, the command would be:

UPDATE Teacher

SET Salary=Salary+5000

WHERE Teacher_Name="Shanaya";

81 of 125

Delete Command:

  • In order to delete one or more tuples, DELETE command is used. If we want to delete the tuple for Teacher with ID=101 the command would be:

DELETE FROM Teacher

WHERE Teacher_ID=101;

  • If the WHERE clause is missing then it will delete all the tuples in a table as shown below:

DELETE FROM Teacher;

82 of 125

Select Command

  • The SELECT Command is used to retrieve information from a database.

Syntax of

SELECT Command is as follows:

SELECT <attribute list>

FROM <table list>

WHERE <condition>

83 of 125

Query:

SELECT *

FROM Teacher

WHERE Teacher_ID=101;

Output

84 of 125

Query:

SELECT First_Name,Last_Name

FROM Teacher

WHERE salary > 50000;

Output:

85 of 125

Query:

SELECT Teacher_ID,First_Name, Last_Name, Dept_No

FROM Teacher

WHERE Dept_No = 4 OR Dept_No = 7;

Output:

86 of 125

Query:

SELECT *

FROM Teacher

WHERE Dept_No = 4 AND Gender =‘F’;

Output:

87 of 125

DISTINCT

Query:

SELECT Dept_No

FROM Teacher;

WHERE GENDER ='M';

Query:

SELECT DISTINCT Dept_No

FROM Teacher;

WHERE GENDER ='M';

88 of 125

Sometimes it is required to match part of the string. This is called as string pattern matching. We can use 'LIKE' keyword along with two more reserved characters - % (percent) and _ (underscore) for specifying different number of characters. % replaces zero or more number of random characters and _ replaces a single character.

SELECT First_Name

FROM Teacher

WHERE First_Name LIKE "S%";

Output:

89 of 125

Query: To retrieve names of all the teachers having 6 characters in the first name

and starting with 'S'.

SELECT First_Name

FROM Teacher

WHERE First_Name LIKE "S_ _ _ _ _";

Output:

90 of 125

Suppose it required to sort the result of a query based on some attributes. This can be achieved by using the clause – ORDER BY. (By default the order is ascending) For ascending order the keyword ASC and for descending order the keyword DESC is used. By default the order is ascending.

Output:

To list the names of teachers in alphabetical order.

SELECT First_Name, Last_Name

FROM Teacher

ORDER BY First_Name, Last_Name;

91 of 125

Query: To list the names of all the Departments in the descending order of their names.

SELECT Dept_Name

FROM Department

ORDER BY Dept_Name DESC;

Output:

92 of 125

Query: To retrieve the names and department numbers of all the teachers ordered by the Department number and within each department ordered by the names of the teachers in descending order.

SELECT First_Name, Last_Name, Dept_No

FROM Teacher

ORDER BY Dept_No ASC, First_Name DESC, Last_Name DESC;

Output:

93 of 125

To test whether a value is unavailable or unknown or not applicable in a column (i.e, NULL values), SQL allows us to test this condition using keywords IS NULL and IS NOT NULL.

Query: To retrieve all the details of those employees whose last name is not specified.

SELECT *

FROM Teacher

WHERE Last_Name IS NULL;

94 of 125

We can have another query in the WHERE clause of SQL query if the condition is based on the result of another query as shown below (The query is called a nested query):

Query: To retrieve the names of all the departments having female teachers.

SELECT DISTINCT Dept_Name

FROM Department

WHERE Dept_ID IN (Select Dept_No

FROM Teacher

WHERE Gender = 'F');

Result:

95 of 125

Between clause

Query:

SELECT First_Name

FROM Teacher

WHERE Salary

BETWEEN 40000 and 50000;

Result:

This is to note that the same query can also be written as:

SELECT First_Name

FROM Department

WHERE Salary >=40000 and Salary<=50000;

Important: in between clause both the values are counted.

96 of 125

IN clause

Query:

SELECT First_Name

FROM Teacher

WHERE Salary

IN (40000 , 50000);

Result:

Here only 40000 and 50000 value are seen. No other values are counted.

97 of 125

98 of 125

We could have also written the above query by using JOIN condition as shown below:

SELECT DISTINCT Dept_Name

FROM Department , Teacher

WHERE Department.Dept_ID = Teacher.Dept_No AND Gender='F';

Result:

99 of 125

Joining

Query:

SELECT First_Name, Last_Name, Dept_ID, Dept_Name

FROM Teacher, Department

WHERE Dept_ID=Dept_No;

100 of 125

Output:

101 of 125

Now suppose we have to retrieve the similar details for the teacher in Chemistry�department, the query would be:�SELECT First_Name, Last_Name, Dept_ID, Dept_Name�FROM Teacher, Department�WHERE Dept_ID=Dept_No AND Dept_name=”Chemistry”;

Output:

102 of 125

Suppose the teacher and department table both had same names for the department number, say Dept_ID as shown below:

CREATE TABLE Department

(

Dept_ID INTEGER PRIMARY KEY,

Dept_Name VARCHAR (30) NOT NULL

);

CREATE TABLE Teacher

(

Teacher_ID INTEGER,

First_Name VARCHAR(20) NOT NULL,

Last_Name VARCHAR(20),

Gender CHAR(1),

Salary DECIMAL(10,2) DEFAULT 40000,

Date_of_Birth DATE,

Dept_ID INTEGER,

CONSTRAINT TEACHER_PK PRIMARY KEY (Teacher_ID),

CONSTRAINT TEACHER_FK FOREIGN KEY (Dept_ID) REFERENCES

Department (Dept_ID)

);

103 of 125

  • In such case, when the join condition is specified, there will be an ambiguity about which Dept_ID we are talking about. To resolve this problem, we have to prefix the name of the attribute with the relation name followed by a period as shown in the query below:
  • Query: To retrieve names of all the teachers who belong to Hindi department.

SELECT First_Name, Last_Name

FROM Teacher, Department

WHERE Department. Dept_ID=Teacher. Dept_ID AND Dept_Name="Hindi";

104 of 125

Create Aliases

  • Another method is to create aliases. Aliases are used to resolve ambiguity of the relations. They are created by using the keyword 'AS'. For example the above query can also be written as:

SELECT First_Name, Last_Name

FROM Teacher AS T, Department AS D

WHERE D.Dept_ID = T. Dept_ID AND Dept_Name="Hindi";

  • Here T is an alias for Teacher table and D is an alias for Department table.

105 of 125

  • We can also create alias to rename a column name as shown below:

SELECT First_Name AS Fname, Last_Name AS Lname

FROM Teacher AS T, Department AS D

WHERE D.Dept_ID = T. Dept_ID AND Dept_Name="Hindi";

Output:

Previous Result

106 of 125

Aggregate Functions

  • COUNT- It counts the numbers of tuples in the result of the query.
  • SUM – It finds the sum of all the values for a selected attribute which has numeric
  • data type.
  • MAX –It finds the maximum value out of all the values for a selected attribute which has numeric data type.
  • MIN - It finds the minimum value out of all the values for a selected attribute which has numeric data type.
  • AVG – It finds the average value of all the values for a selected attribute which has numeric data type.

107 of 125

To find total salary of all the teachers

SELECT SUM(Salary) AS Total_Salary

FROM Teacher;

Output:

108 of 125

To find the maximum and minimum salary.

SELECT MAX(Salary) AS Max_Salary, MIN(Salary) AS

Min_Salary

FROM Teacher;

Output:

109 of 125

To count the number of teachers earning more than Rs 40000.

SELECT COUNT(Salary)

FROM Teacher

WHERE Salary > 40000;

Output:

SELECT COUNT(Salary) AS Salary

FROM Teacher

WHERE Salary > 40000;

Output:

110 of 125

SELECT COUNT(Last_Name)

FROM Teacher;

Output:

SELECT COUNT(*)

FROM Teacher

Output:

(*) Asterisk symbol is used to count the number of rows in the result of the query.

Count(Last_Name)

12

Count(Last_Name)

14

111 of 125

SELECT AVG(Dept_No)

FROM Teacher;

Output:

SELECT AVG(Dept_No)

FROM Teacher

Output:

AVG(Dept_No)

4.57

If null is there in place of 2

AVG(Dept_No)

4.76

64/14 = 4.57

62/13 = 4.76

112 of 125

We can also use arithmetic operators in the SELECT clause. For example, if we want to display Teacher name, current salary and a 10% increase in the salary for those teachers who belongs to Department number 4, the SELECT statement can be written as shown below:

SELECT First_Name, Last_Name, Salary, Salary*1.1 AS New_Salary

FROM Teacher WHERE Dept_No = 4;

For permanent change:

Update TEACHER set Salary = Salary + Salary *10/100 where Dept_No = 4;

113 of 125

Grouping based on an attribute can be done in SQL. For such grouping, GROUP BY clause is added in the SQL query.

For example, we have to find the number of teachers teaching in each Department. Thus we have to group the result based on the Departments and for each Department we have to count number of teachers who teach in that Department. This query is written by using GROUP BY clause and aggregate function as shown below:

Output:

SELECT Dept_No, COUNT(*) AS No_of_Teachers

FROM Teacher

GROUP BY Dept_No;

114 of 125

The above result can be enhanced if we display the name of Departments also as shown below:

SELECT Dept_No, Dept_Name, COUNT(*) AS No_of_Teachers

FROM Teacher, Department

WHERE Dept_ID = Dept_No

GROUP BY Dept_No;

Result:

115 of 125

It is also possible to apply some condition on the group. This condition will not come under the WHERE clause, but in a new clause HAVING.

For example, we have to find those departments which have more than one teacher.

SELECT Dept_No, Dept_Name, COUNT(*) AS No_of_Teachers FROM Teacher, Department

WHERE Dept_No=Dept_ID

GROUP BY Dept_No HAVING COUNT(*) > 1;

Result:

116 of 125

A Select command can also result in an empty set.

For example, retrieve the name of Teacher with ID=115. Since there is no such teacher in the Teacher table, following query results in an empty set.

SELECT *

FROM Teacher

WHERE Teacher_ID = 115;

Result:

Empty set

117 of 125

END OF THE CHAPTER

118 of 125

Q1.Consider the following Employee table:

The primary key of this table is Employee_ID and Manager_ID is a foreign key that references Employee_ID.

119 of 125

Write SQL commands for the following:

  • (a) Create the above table.
  • Ans:
  • Create table Employee (Employee_ID int Primary Key, Employee_Name char(20), Job_Title char(20),Salary int, Bonus int, Age int, Manager_ID int, Foreign Key (Manager_ID) references Employee(Employee_ID));

120 of 125

  • (b) Insert values as shown above.
  • Ans:
  • Insert into Employee values(1201,”Divya”, ‘Preseident’,50000,Null, 29, Null);
  • Insert into Employee values(1205,”Amyra”, ‘Manager’,30000, 2500, 26, 1201);

121 of 125

  • (c) Delete the Employee having Employee_ID 1217.
  • Ans:
  • Delete from Employee where Employee_ID = 1217;
  • (d) Update the salary of “Amyra” to 40000.
  • Ans:
  • Update Employee set Salary =40000 where Employee_Name=‘Amyra’;

122 of 125

  • (e) Alter the table Employee so that NULL values are not allowed for Age column.
  • Ans:
  • Alter table Employee Modify Age Not Null;
  • (f) Write a query to display names and salaries of those employees whose salary are greater than 20000.
  • Ans:
  • Select En=mloyee_Name, Salary from Emlpoyee where Salary >20000;

123 of 125

  • (g) Write a query to display details of employees who are not getting any bonus.
  • Ans:
  • Select * from Employee where Bonus is null;

  • (h) Write a query to display the names of employees whose name contains “a” as the last alphabet.
  • Ans:
  • Select Employee_Name fro Employee where Employee_Name like “%a”;

124 of 125

  • (i) Write a query to display the name and Job title of those employees whose Manager_ID is 1201.
  • Ans:
  • Select Employee_Name, Job_Title from Employee where Manager_ID =1201;

  • (j) Write a query to display the name and Job title of those employees whose Manager is “Amyra”.
  • Ans:
  • Select Employee_Name, Job_Title from Employee where Manager_ID=1205;

125 of 125

  • (k) Write a query to display the name and Job title of those employees aged between 26 years and 30 years (both inclusive)
  • Ans�Select Employee_Name, Job_Title from Employee where Age between 26 and 30;
  • Or
  • Select Employee_Name, Job_Title from Employee where Age >=26 and Age<=30;