0% found this document useful (0 votes)
16 views136 pages

Database

This document discusses database concepts and the relational data model. It provides examples of data, such as student records, and discusses limitations of storing data in files, such as redundancy and inconsistency. It then explains how a database management system (DBMS) can overcome these limitations by linking related data across multiple tables and enforcing access controls. Key concepts of the relational data model are defined, including tables, rows, columns, primary keys, and relationships between tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views136 pages

Database

This document discusses database concepts and the relational data model. It provides examples of data, such as student records, and discusses limitations of storing data in files, such as redundancy and inconsistency. It then explains how a database management system (DBMS) can overcome these limitations by linking related data across multiple tables and enforcing access controls. Key concepts of the relational data model are defined, including tables, rows, columns, primary keys, and relationships between tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 136

Database concepts

What is data?
• Data is a collection of characters, numbers, and other symbols that
represents values of some situations or variables
• Examples:
• Name, age, gender, contact details, etc., of a person
• Transactions data generated through banking, ticketing, shopping, etc. whether
online or offline
• Images, graphics, animations, audio, video
• Documents and web pages
• Online posts, comments and messages
• Signals generated by sensors
• Satellite data including meteorological data, communication data, earth observation
data, etc.
• Let us take an example of a school that maintains data about its students,
along with their attendance record and guardian details.
• limitations of manual record keeping
• Entry of student details (Roll number and name) in the new attendance register
when the student is promoted to the next class.
• Writing student details on each month’s attendance page where inconsistency
may happen due to incorrectly written names, skipped student records, etc.
• Loss of data in case attendance register is lost or damaged.
• Erroneous calculation while consolidating attendance record manually.
• Finding information from a huge volume of papers or deleting/modifying an
entry is a difficult task in pen and paper based approach
• To overcome the hassles faced in manual record keeping, it is desirable to
store attendance record and student details on separate data files on a
computerised system, so that office staff and teachers can:
• Simply copy the student details to the new attendance file from the old attendance file
when students are promoted to next class
• Find any data about student or guardian
• Add more details to existing data whenever a new student joins the school
• Modify stored data like details of student or guardian whenever required
• Remove/delete data whenever a student leaves the school
File System
• A file can be understood as a container to store data in a computer
• Files can be stored on the storage device of a computer system
• Contents of a file can be texts, computer program code, comma separated
values (CSV), etc. Likewise, pictures, audios/videos, web pages are also files
• Files stored on a computer can be accessed directly and searched for
desired data
• But to access data of a file through software, for example, to display
monthly attendance report on school website, one has to write computer
programs to access data from files
• we need to store data about students and attendance in two
separate files
• Table 8.1 shows the contents of STUDENT file which has six
columns, as detailed below:
• RollNumber – Roll number of the student
• SName – Name of the student
• SDateofBirth – Date of birth of the student
• GName – Name of the guardian
• GPhone – Phone number of the student guardian
• GAddress – Address of the guardian of the student
• Table 8.2 shows another file called ATTENDANCE which has four
columns, as detailed below:
• AttendanceDate – Date for which attendance was marked
• RollNumber – Roll number of the student
• SName – Name of the student
• AttendanceStatus – Marked as P (present) or A (absent)
Limitations of a File System
• Difficulty in Access
• Files themselves do not provide any mechanism to retrieve data
• Data maintained in a file system are accessed through application programs
• Data Redundancy
• Redundancy means same data are duplicated in different places (files)
• In our example, student names are maintained in both the files. Besides, in
Table 8.1, students with roll numbers 3 and 5 have same guardian name and
therefore same guardian name is maintained twice.
• Redundancy leads to excess storage use and may cause data inconsistency also
• Data Inconsistency
• Data inconsistency occurs when same data maintained in different places do not
match
• If a student wants to get changed the spelling of her name, it needs to be changed
in SName column in both the files.
• Data Isolation
• Both the files presented at Table 8.1 (STUDENT) and at Table 8.2 (ATTENDANCE)
are related to students
• But there is no link or mapping between them
• The school will have to write separate programs to access these two files
• This is because data mapping is not supported in file system
• Data Dependence
• Data are stored in a specific format or structure in a file
• If the structure or format itself is changed, all the existing application programs
accessing that file also need to be changed
• Otherwise, the programs may not work correctly
• Controlled Data Sharing
• There can be different category of users like teacher, office staff and parents Ideally,
not every user should be able to access all the data.
• As an example, guardians and office staff can only see the student attendance data
but should not be able to modify/delete it
• It means these users should be given limited access (read only) to the
ATTENDANCE file
• Only the teacher should be able to update the attendance data
• It is very difficult to enforce this kind of access control in a file system while
accessing files through application programs
Database management system
• A database management system (DBMS) or database system in short,
is a software that can be used to create and manage databases
• DBMS lets users to create a database, store, manage, update/modify
and retrieve data from that database by users or application programs
• Some examples of open source and commercial DBMS include MySQL,
Oracle, PostgreSQL, SQL Server, Microsoft Access, MongoDB
• The DBMS serves as an interface between the database and end users
or application programs
• Retrieving data from a database through special type of commands is
called querying the database
File System to DBMS
• Let us now design a database to store data of those two files
• We know that tables in a database are linked or related through one or
more common columns or fields
• In our example, the STUDENT (Table 8.1) file and ATTENDANCE (Table
8.2) file have RollNumber and SName as common field names
• In order to convert these two files into a database, we need to
incorporate the following changes:
Key Concepts in DBMS
• Database Schema
• Database Schema is the design of a database
• It is the skeleton of the database that represents the structure (table names
and their fields/columns), the type of data each column can hold, constraints
on the data to be stored (if any), and the relationships among the tables
• Data Constraint
• Sometimes we put certain restrictions or limitations on the type of data that
can be inserted in one or more columns of a table
• This is done by specifying one or more constraints on that column(s) while
creating the tables
• For example, one can define the constraint that the column mobile number
can only have non-negative integer values of exactly 10 digits
• Query
• A query is a request to a database for obtaining information in a desired way. Query
can be made to get data from one table or from a combination of tables
• For example, “find names of all those students present on Attendance Date 2000-01-
02” is a query to the database
• Data Manipulation
• Modification of database consists of three operations viz. Insertion, Deletion or
Update
• Database Instance
• When we define database structure or schema, state of database is
empty i.e. no data entry is there
• After loading data, the state or snapshot of the database at any given time is
the database instance
• Meta-data or Data Dictionary
• The database schema along with various constraints on the data is stored by
DBMS in a database catalog or dictionary, called meta-data
• A meta-data is data about the data.
• Database Engine
• Database engine is the underlying component or set of programs used by a
DBMS to create database and handle various queries for data retrieval and
manipulation.
Relational data model
• A data model describes the structure of the database, including how
data are defined and represented, relationships among data, and the
constraints
• The most commonly used data model is Relational Data Model
• Other types of data models include object-oriented data model, entity-
relationship data model, document model and hierarchical data model
• In relational database model data is organized into table (i.e. rows
and columns)
• These tables are also known as relations
• A row in a table represent relationship among a set of values
• Row of a relation is called tuple or record
• A column represent the field/attributes related to relation under
which information will be stored
• Column of a relation is called attribute or field
• Number of columns (attributes) in a relation is called degree
• Number of records in a relation is called cardinality
• It is important to note here that relations in a database are not
independent tables, but are associated with each other
• For example, relation ATTENDANCE has attribute RollNumber which
links it with corresponding student record in relation STUDENT
• Similarly, attribute GUID is placed with STUDENT table for
extracting guardian details of a particular student
• If linking attributes are not there in appropriate relations, it will not
be possible to keep the database in correct state and retrieve valid
information from the database
Three Important Properties of a Relation

• Property 1: imposes following rules on an attribute of the relation


• Each attribute in a relation has a unique name
• Sequence of attributes in a relation is immaterial
• Property 2: governs following rules on a tuple of a relation
• Each tuple in a relation is distinct. For example, data values in no two tuples of
relation ATTENDANCE can be identical for all the attributes. Thus, each tuple of
a relation must be uniquely identified by its contents
• Sequence of tuples in a relation is immaterial. The tuples are not considered to
be ordered, even though they appear to be in tabular form.
• Property 3: imposes following rules on the state of a relation
• All data values in an attribute must be from the same domain (same data type).
• Each data value associated with an attribute must be atomic (cannot be further
divisible into meaningful subparts). For example, GPhone of relation GUARDIAN has
ten digit numbers which is indivisible.
• No attribute can have many data values in one tuple. For example, Guardian cannot
specify multiple contact numbers under GPhone attribute.
• A special value “NULL” is used to represent values that are unknown or non-applicable
to certain attributes. For example, if a guardian does not share his or her contact
number with the school authorities, then GPhone is set to NULL (data unknown).
Keys in a relational database
• relational data model imposes some restrictions or constraints on the values of
the attributes and how the contents of one relation be referred through
another relation
• These restrictions are specified at the time of defining the database through
different types of keys as given below:
• Candidate key
• Primary key
• Composite primary key
• Foreign key
Candidate key
• A relation can have one or more attributes that takes distinct values
• Any of these attributes can be used to uniquely identify the tuples in
the relation
• Such attributes are called candidate keys as each of them are
candidates for the primary key.
• As shown in Figure 8.4, the relation GUARDIAN has four attributes out
of which GUID and GPhone always take unique values
• No two guardians will have same phone number or same GUID
• Hence, these two attributes are the candidate keys as they both are
candidates for primary key.
Primary key
• Out of one or more candidate keys, the attribute chosen by the
database designer to uniquely identify the tuples in a relation is called
the primary key of that relation
• In the relation GUARDIAN, suppose GUID is chosen as primary key,
then GPhone will be called the alternate key
Composite Primary Key
• If no single attribute in a relation is able to uniquely distinguish the tuples, then
more than one attribute are taken together as primary key
• Such primary key consisting of more than one attribute is called Composite
Primary key
• Example:
• In relation ATTENDANCE, Roll Number cannot be used as primary key as roll number
of same student will appear in another row for a different date
• Similarly, in relation Attendance, AttendanceDate cannot be used as primary key
because same date is repeated for each roll number
• However combination of these two
attributes RollNumber and AttendanceDate together would always
have unique value in ATTENDANCE table as on any working day, of a
student would be marked attendance only once. Hence {RollNumber,
AttendanceDate} will make the of ATTENDANCE relation composite
primary key
Foreign Key
• A foreign key is used to represent the relationship between two relations.
• A foreign key is an attribute whose value is derived from the primary key of
another relation.
• This means that any attribute of a relation (referencing), which is used to refer
contents from another (referenced) relation, becomes foreign key if it refers to
the primary key of referenced relation
• The referencing relation is called Foreign Relation
• In some cases, foreign key can take NULL value if it is not the part of primary
key of the foreign table
• The relation in which the referenced primary key is defined is called
primary relation or master relation.
• In Figure 8.5, two foreign keys in Student Attendance database are
shown using schema diagram where the foreign key is displayed as a
directed arc (arrow) originating from it and ending at the
corresponding attribute of the primary key of the referenced table
• The underlined attributes make the primary key of that table.
Alternate key
• The remaining attributes in the list of candidate keys are called
the alternate keys
Structured Query Language
• For database management systems there are special kinds of
languages called query language that can be used to access and
manipulate data from the database
• The Structured Query Language (SQL) is the most popular query
language used by major relational database management systems
such as MySQL, ORACLE, SQL Server, etc
data types and constraints in MySQL
• Each attribute has a data type in a relation
• Data type of an attribute indicates the type of data value that an attribute can
have
• It also decides the operations that can be performed on the data of that
attribute
• For example, arithmetic operations can be performed on numeric data but not
on character data
• Commonly used data types in MySQL are numeric types, date and time types,
and string types as shown in Table 9.1
• We can also specify constraints for each attribute of a relation
Constraints
• Constraints are the certain types of restrictions on the data values that
an attribute can have.
• Table 9.2 lists some of the commonly used constraints in SQL.
• They are used to ensure correctness of data.
• However, it is not mandatory to define constraints for each attribute of
a table.
Classification of SQL statements
• SQL provides different types of commands used for different purposes
• Data Definition Lanuage (DDL ) commands
• Data Manipulation Language (DML) commands
• Transaction Control Language (TCL) commands
1. Data Definition Language
• In order to be able to store data we need to first define the relation
schema
• Defining a schema includes
• Creating a relation and
• Giving name to a relation
• Identifying the attributes in a relation
• Deciding upon the datatype for each attribute and
• Specify the constraints as per the requirements
• Sometimes, we may require to make changes to the relation schema
also
• SQL allows us to write statements for defining, modifying and deleting
relation schemas (create, alter and drop)
• These are part of Data Definition Language (DDL).
1.1 CREATE Database
• To create a database, we use the CREATE DATABASE statement as
shown in the following syntax:
CREATE DATABASE databasename;
• To create a database called StudentAttendance, we will type following
command at mysql prompt
mysql> CREATE DATABASE StudentAttendance;
• A DBMS can manage multiple databases on one computer
• Therefore, we need to select the database that we want to use
• To know the names of existing databases, we use the statement SHOW
DATABASES
• From the listed databases, we can select the database to be used
• Once the database is selected, we can proceed with creating tables or
querying data.
• In order to use the StudentAttendance database, the following SQL statement
is required.
mysql> USE StudentAttendance;
• Database changed
Initially, the created database is empty. It can be checked by using the show
tables statement that lists names of all the tables within a database.
• mysql> SHOW TABLES;

1.2 Create table
• After creating a database StudentAttendance, we need to define relations in this
database and specify attributes for each relation along with data type and constraint
(if any) for each attribute. This is done using the CREATE TABLE statement.
Syntax:
CREATE TABLE tablename(
• attributename1 datatype constraint,
• attributename2 datatype constraint,
• :
• attributenameN datatype constraint);

• Once data types and constraints are identified, let us create tables
without specifying constraints along with the attribute name for
simplification
1.3 Describe table
• We can view the structure of an already created table using the
DESCRIBE statement or DESC statement
• We can use the SHOW TABLES statement to see the tables in the
StudentAttendance database. So far, we have only the STUDENT table.
mysql> SHOW TABLES;
• +------------------------------+
• | Tables_in_studentattendance |
• +------------------------------+
• | student |
• +------------------------------+
• 1 row in set (0.00 sec)

1.4 Alter table
• After creating a table, we may realise that we need to add/remove an
attribute or to modify the datatype of an existing attribute or to add
constraint in attribute.
• In all such cases, we need to change or alter the structure (schema) of
the table by using the alter statement.
(A) Add primary key to a relation
• The following MySQL statement adds a primary key to the GUARDIAN
relation:
mysql> ALTER TABLE GUARDIAN ADD PRIMARY KEY (GUID);

To add the primary key to the ATTENDANCE relation. The primary key of
this relation is a composite key made up of two attributes -
AttendanceDate and RollNumber.
• mysql> ALTER TABLE ATTENDANCE
• -> ADD PRIMARY KEY(AttendanceDate,
• RollNumber);

(B) Add foreign key to a relation
• Once primary keys are added, the next step is to add foreign keys to
the relation (if any)
• Following points need to be observed while adding foreign key to a
relation:
• The referenced relation must be already created
• The referenced attribute(s) must be part of the primary key of the referenced
relation
• Data types and size of referenced and referencing attributes must be the
same.
• Syntax:
ALTER TABLE table_name ADD FOREIGN KEY(attribute
• name) REFERENCES referenced_table_name
(attribute name);

• Example:
• mysql> ALTER TABLE STUDENT
• -> ADD FOREIGN KEY(GUID) REFERENCES
• -> GUARDIAN(GUID);

(C) Add constraint UNIQUE to an existing
attribute
• In GUARDIAN table, the attribute GPhone has a constraint UNIQUE
which means no two values in that column should be the same.
Syntax:
ALTER TABLE table_name ADD UNIQUE (attribute name);

Let us now add the constraint UNIQUE with the attribute GPhone of the
table GUARDIAN as shown at table 9.4.
• mysql> ALTER TABLE GUARDIAN
• -> ADD UNIQUE(GPhone);

(D) Add an attribute to an existing table
• Sometimes, we may need to add an additional attribute in a table
• It can be done using the ADD attribute statement as shown in the following Syntax:
ALTER TABLE table_name ADD attribute name DATATYPE;
• Suppose, the principal of the school has decided to award scholarship to some needy
students for which income of the guardian must be known
• But, the school has not maintained the income attribute with table GUARDIAN so far
• Therefore, the database designer now needs to add a new attribute Income of data
type INT in the table GUARDIAN
mysql> ALTER TABLE GUARDIAN
-> ADD income INT;

(E) Modify datatype of an attribute
• We can change data types of the existing attributes of a table using the
following ALTER statement.
Syntax:
ALTER TABLE table_name MODIFY attribute DATATYPE;

Suppose we need to change the size of the attribute GAddress from
VARCHAR(30) to VARCHAR(40) of the GUARDIAN table. The MySQL
statement will be:
• mysql> ALTER TABLE GUARDIAN
• -> MODIFY GAddress VARCHAR(40);
(F) Modify constraint of an attribute
• When we create a table, by default each attribute takes NULL value except for
the attribute defined as primary key.
• We can change an attribute’s constraint from NULL to NOT NULL using an alter
statement.
Syntax:
ALTER TABLE table_name MODIFY attribute DATATYPE
• NOT NULL;
To associate NOT NULL constraint with attribute SName of table STUDENT (table
9.3), we write the following MySQL statement:
• mysql> ALTER TABLE STUDENT
• -> MODIFY SName VARCHAR(20) NOT NULL;

(G) Add default value to an attribute
• If we want to specify default value for an attribute, then use the
following syntax:
ALTER TABLE table_name MODIFY attribute DATATYPE DEFAULT default_value;
• To set default value of SDateofBirth of STUDENT to 15th May 2000,
write the following statement:
mysql> ALTER TABLE STUDENT
• -> MODIFY SDateofBirth DATE DEFAULT ‘2000-05-15’;

(H) Remove an attribute
• Using ALTER, we can remove attributes from a table, as shown in the
following syntax:
ALTER TABLE table_name DROP attribute;
• To remove the attribute income from table GUARDIAN (Table 9.4),
write the following MySQL statement:

• mysql> ALTER TABLE GUARDIAN DROP income;



(I) Remove primary key from the table
• Sometime there may be a requirement to remove primary key constraint
from the table
• In that case, Alter table command can be used in the following way:
Syntax:
ALTER TABLE table_name DROP PRIMARY KEY;

To remove primary key of table GUARDIAN (Figure 9.4), write the following
MySQL statement:
• mysql> ALTER TABLE GUARDIAN DROP PRIMARY KEY;

1.5 DROP Statement
• Sometimes a table in a database or the database itself needs to be removed
• We can use a DROP statement to remove a database or a table permanently
from the system
• However, one should be very cautious while using this statement as it cannot
be undone

Syntax to drop a table:


DROP TABLE table_name;

Syntax to drop a database:


• DROP DATABASE database_name;

2. Data Manipulation Language (DML)
• When we create a table, only its structure is created but the table has
no data
• To populate records in the table, INSERT statement is used
• Also, table records can be deleted or updated using DELETE and
UPDATE statements
• These SQL statements are part of Data Manipulation Language (DML)
2.1 INSERTION of Records
• INSERT INTO statement is used to insert new records in a table
• Its syntax is:
INSERT INTO tablename
• VALUES(value 1, value 2,....);

• Here, value 1 corresponds to attribute 1, value 2 corresponds to attribute
2 and so on
• Note that we need not to specify attribute names in the insert
statement if there are exactly the same numbers of values in the INSERT
statement as the total number of attributes in the table
• Note: Whileinserting records in a table with foreign key, ensure that
records in referenced tables are already inserted
• The following insert statement adds the first record in the table:
mysql> INSERT INTO GUARDIAN
• -> VALUES (444444444444, 'Amit Ahuja',
-> 5711492685, 'G-35,Ashok vihar, Delhi' );
• We can use the SQL statement SELECT * from table_name to view the inserted records
• mysql> SELECT * from GUARDIAN;
• +--------------+---------------+------------+---------------------------+
• | GUID | GName | Gphone | GAddress |
• +--------------+---------------+------------+---------------------------+
• | 444444444444 | Amit Ahuja | 5711492685 | G-35, Ashok vihar, Delhi |
• +--------------+---------------+------------+---------------------------+
• If we want to insert values only for some of the attributes in a table (supposing
other attributes having NULL or any other default value), then we shall specify
the attribute names in which the values are to be inserted using the following
syntax of INSERT INTO statement.
• Syntax:
• INSERT INTO tablename (column1, column2, ...)
• VALUES (value1, value2, ...);
• In this case, we have to specify the names of attributes in which we want to
insert values
• The values must be given in the same order in which attributes are written in
INSERT statement.
mysql> INSERT INTO GUARDIAN(GUID, GName, GAddress)
• -> VALUES (333333333333, 'Danny Dsouza',
-> 'S -13, Ashok Village, Daman' );
• Query OK, 1 row affected (0.03 sec)

• Note: Text and date values must be enclosed in ‘ ’ (single quotes).
• mysql> SELECT * from GUARDIAN;
• +--------------+--------------+-----------+---------------------------+
• | GUID | GName | Gphone | GAddress |
• +--------------+--------------+-----------+---------------------------+
• | 333333333333 | Danny Dsouza | NULL | S -13, Ashok Village,Daman|
• | 444444444444 | Amit Ahuja | 5711492685| G-35, Ashok vihar, Delhi |
• +--------------+--------------+-----------+---------------------------+
• 2 rows in set (0.00 sec)
• we can put NULL value for GUID and insert the record by using the
following statement:
mysql> INSERT INTO STUDENT
-> VALUES(3, 'Taleem Shah','2002-02-28', NULL);
2.2 Select statement
• The SQL statement SELECT is used to retrieve data from the tables in a
database and the output is also displayed in tabular form.
• Syntax:
SELECT attribute1, attribute2, ...
FROM table_name
WHERE condition;
• Here, attribute1, attribute2, ... are the column names of the table
table_name from which we want to retrieve data
• The FROM clause is always written with SELECT clause as it specifies
the name of the table from which data is to be retrieved
• The WHERE clause is optional and is used to retrieve data that meet
specified condition(s)
• To select all the data available in a table, we use the following select
statement:
SELECT * FROM table_name;
Example 9.2 The following query retrieves the name and date of birth of
student with roll number 1:
mysql> SELECT SName, SDateofBirth
-> FROM STUDENT
-> WHERE RollNumber = 1;
+--------------+--------------+
| SName | SDateofBirth |
+--------------+--------------+
| Atharv Ahuja | 2003-05-15 |
+———————+--------------+
(A) Retrieve selected columns
• The following query selects employee numbers of all the employees:
mysql> SELECT EmpNo FROM EMPLOYEE;
+-------+
| EmpNo |
+-------+
| 101 |
| 102 |
| 103 |
| 104 |
| 105 |
| 106 |
| 107 |
| 108 |
| 109 |
| 110 |
+-------+
10 rows in set (0.41 sec)
• The following query selects the employee number and employee name of all the employees, we write:
mysql> SELECT EmpNo, Ename FROM EMPLOYEE;
+-------+----------+
| EmpNo | Ename |
+-------+----------+

| 101 | Aaliya |

| 102 | Kritika |

| 103 | Shabbir |

| 104 | Gurpreet |

| 105 | Joseph |
| 106 | Sanya |

| 107 | Vergese |

| 108 | Nachaobi |

| 109 | Daribha |
| 110 | Tanya |
+-------+----------+
10 rows in set (0.00 sec)
(B) Renaming of columns
• In case we want to rename any column while displaying the output, it can be done by using the alias 'AS'
• The following query selects Employee name as Name in the output for all the employees:
mysql> SELECT EName as Name FROM EMPLOYEE;
+----------+
| Name |
+----------+
| Aaliya |
| Kritika |
| Shabbir |
| Gurpreet |
| Joseph |
| Sanya |
| Vergese |
| Nachaobi |
| Daribha |
| Tanya |
+----------+
10 rows in set (0.00 sec)
• Example: Select names of all employees along with their annual income
(calculated as Salary*12). While displaying the query result, rename the
column EName as Name
mysql> SELECT EName AS Name, Salary*12 FROM EMPLOYEE;
• Observe that in the output, Salary*12 is displayed as the column name
for the Annual Income column. In the output table, we can use alias to
rename that column as Annual Income as shown below:
mysql> SELECT Ename AS Name, Salary*12 AS ‘Annual Income’
• Note: Annual Income will not be added as a new column in the database
table. It is just for displaying the output of the query
• If an aliased column name has space as in the case of Annual Income, it
should be enclosed in quotes as 'Annual Income’
(C) DISTINCT clause
• The SELECT statement when combined with DISTINCT clause, returns
records without repetition (distinct records)
• For example, while retrieving a department number from employee
relation, there can be duplicate values as many employees are
assigned to the same department
• To select unique department number for all the employees, we use
DISTINCT as shown below
mysql> SELECT DISTINCT DeptId FROM EMPLOYEE;
(D) WHERE clause
• The WHERE clause is used to retrieve data that meet some specified conditions
• Following query gives distinct salaries of the employees working in the
department number D01:
mysql> SELECT DISTINCT Salary
-> FROM EMPLOYEE
-> WHERE Deptid='D01';
• Relational operators (=,<, <=, >, >=, !=) can be used to specify such conditions
• The logical operators AND, OR, and NOT are used to combine multiple
conditions
• Examples:
• Display all the details of those employees of D03 department who
earn more than 5000
mysql> SELECT * FROM EMP
-> WHERE Salary > 5000 AND DId = 'D03';
• The following query selects records of all the employees except
Aaliya.

mysql> SELECT * FROM EMP


-> WHERE NOT Ename = 'Aaliya'
• Display the name and department number of all those employees who are
earning salary between 20000 and 50000 (both values inclusive)
mysql > SELECT Ename, Did
-> FROM EMP
-> WHERE Salary>=20000 AND Salary<=50000;

• The above query can also be checked using a comparison operator


BETWEEN, as shown below:
mysql> SELECT Ename, Did
-> FROM EMP
-> WHERE Salary BETWEEN 20000 AND 50000;
• Write query to display the details of all the employees who work in
the departments having deptid D01 or D03
• mysql> SELECT *

-> FROM EMP

-> WHERE Did = 'D01' OR DeptId = ‘D03’;


(E) Membership Operator IN
• The IN operator compares a value with a set of values and returns
true if the value belongs to that set
• Write query to display the details of all the employees who work in
the departments having deptid D01, D02 or D04
mysql> SELECT * FROM EMP
-> WHERE DID IN ('D01', 'D02');
• Display details of all the employees except those working in
department number D01 or D02
• mysql > SELECT * FROM EMPLOYEE
-> WHERE DeptId NOT IN('D01', 'D02');
(F) ORDER BY Clause
• ORDER BY clause is used to display data in an ordered form with
respect to a specified column
• By default, ORDER BY displays records in ascending order of the
specified column’s values
• To display the records in descending order, the DESC (means
descending) keyword needs to be written with that column
• The following query selects details of all the employees in ascending order of
their salaries.
mysql> SELECT * FROM EMP

-> ORDER BY Salary;

• Select details of all the employees in descending order of their salaries.

mysql> SELECT * FROM EMP

-> ORDER BY Salary DESC;


(G) Handling NULL values
• SQL supports a special value called NULL to represent a missing or
unknown value
• In order to check for NULL value in a column, we use IS NULL operator
• The following query selects details of employees who have not been
given a bonus
mysql> SELECT * FROM EMP
-> WHERE Bonus IS NULL;
• The following query selects names of all employees who have been
given a bonus (i.e., Bonus is not null) and works in the department
D01
mysql > SELECT EName FROM EMP
-> WHERE Bonus IS NOT NULL
-> AND DeptID = ‘D01’;
(H) Substring pattern matching
• SQL provides a LIKE operator that can be used with the WHERE clause
to search for a specified pattern in a column
• The LIKE operator makes use of the following two wild card characters:
• % (per cent)- used to represent zero, one, or multiple characters
• _ (underscore)- used to represent exactly a single character
• The following query selects details of all those employees whose name starts
with ‘K'
mysql> SELECT * FROM EMP
-> WHERE Ename like 'K%';
• The following query selects details of all those employees whose name ends
with 'a', and gets a salary more than 45000
mysql> SELECT * FROM EMP
-> WHERE Ename like ‘%a'
-> AND Salary > 45000;
• The following query selects details of all those employees whose
name consists of exactly 5 letters and starts with any letter but has
‘ANYA’ after that
mysql> SELECT * FROM EMP
-> WHERE Ename like '_ANYA';
• The following query selects names of employees containing 'se' as a
substring in name
mysql> SELECT Ename FROM EMP
-> WHERE Ename like '%se%';
• The following query selects names of all employees containing 'a' as
the second character
mysql> SELECT EName FROM EMP
-> WHERE Ename like '_a%';
UPDATE Statement
• The UPDATE statement is used to make such modifications in existing
data
• Syntax:
UPDATE table_name
SET attribute1 = value1, attribute2 = value2, …
WHERE condition;
• In order to update or change value of a particular row (record), we
need to specify that record using WHERE clause
• Caution : If we miss the where clause in the UPDATE statement then
the column value of all the records will be changed
• Example:
mysql> UPDATE STUDENT
-> SET GUID = 101010101010
-> WHERE RollNumber = 3;
• We can also update values for more than one column using the
UPDATE statement. Suppose, the guardian with GUID 466444444666
has requested to change Address to 'WZ - 68, Azad Avenue, Bijnour,
MP' and Phone number to ‘9010810547’
mysql> UPDATE GUARDIAN
-> SET GAddress = 'WZ - 68, Azad Avenue,
-> Bijnour, MP', GPhone = 9010810547
-> WHERE GUID = 466444444666;
DELETE Statement
• DELETE statement is used to delete/remove one or more records from
a table
• Syntax:
DELETE FROM table_name
WHERE condition;
• Example:
• mysql> DELETE FROM STUDENT WHERE Rollno= 2;
• Above query deletes the student record whose roll number is 2
• Caution: Like UPDATE statement, we need to be careful to include the
WHERE clause while using a DELETE statement to delete records in a
table. Otherwise, all the records in the table will get deleted
Aggregate functions
• Aggregate functions are also called Multiple Row functions
• These functions work on a set of records as a whole and return a single value
for each column of the records on which the function is applied
• Aggregate functions are:
• Max
• Min
• Sum
• Avg
• Count
• count(*)
GROUP BY CLAUSE
• To fetch a group of rows on the basis of common values in a column
• This can be done using a group by clause
• It groups the rows together that contains the same values in a
specified column
• We can use the aggregate functions (COUNT, MAX, MIN, AVG and
SUM) to work on the grouped values
• HAVING Clause in SQL is used to specify conditions on the rows with
Group By clause
• Consider the SALE table from the CARSHOWROOM database:
• CarID, CustID, SaleDate, PaymentMode, EmpID, SalePrice are the
columns that can have rows with the same values in it
• So, Group by clause can be used in these columns to find the number
of records of a particular type (column), or to calculate the sum of the
price of each car type
• Example 1: Display the number of Cars purchased by each Customer
from SALE table
• mysql> SELECT CustID, COUNT(*) as "Number of Cars” FROM SALE
GROUP BY CustID;
• Example 2:Display the Customer Id and number of cars purchased if the
customer purchased more than 1 car from SALE table
• mysql> SELECT CustID, COUNT(*) FROM SALE GROUP BY CustID
HAVING Count(*)>1;
• Example 3: Display the number of people in each category of payment mode
from the table SALE
mysql> SELECT PaymentMode, COUNT(PaymentMode)
FROM SALE GROUP BY Paymentmode ORDER BY Paymentmode;
• Display the PaymentMode and number of payments made using that
mode more than once.
SQL JOINS
An SQL join is a query that fetches data from two or more tables whose
records are joined with one another based on condition
Syn:
SELECT <FIELD LIST>
FROM <TABLE1>,<TABLE2>...<TABLEN>
WHERE <JOIN CONDITION FOR THE TABLES>
There can be many types of joins possible. these are
Cartesian product
equi join
natural join
Cartesian product on two tables
• Cartesian product operation combines tuples from two relations
• It results in all pairs of rows from the two input relations, regardless of
whether or not they have the same values on common attributes
• It is denoted as ‘X’
• The degree of the resulting relation is calculated as the sum of the
degrees of both the relations under consideration
• The cardinality of the resulting relation is calculated as the product of
the cardinality of relations on which cartesian product is applied
• When more than one table is to be used in a query, then we must
specify the table names by separating commas in the FROM clause
• On execution of such a query, the DBMS (MySql) will first apply
cartesian product on specified tables to have a single table
• Example : Display all possible combinations of tuples of relations
DANCE and MUSIC
mysql> SELECT * FROM DANCE, MUSIC;
EQUI JOIN
• An SQL join query that joins two or more tables based on condition using
equality operator
• example:
● Query to display first name and salary from workers and design table for each
worker
mysql>select firstname,salary from workers,design where
workers.w_id=desig.w_id
(or)
mysql> select firstname,salary from workers w, desig d where
w.w_id=d.w_id
(or)
mysql> select firstname,salary from workers w join desig d on
w.w_id=d.w_id
Output:
+-----------+--------+
| firstname | salary |
+-----------+--------+
| Sam | 75000 |
| Sarah | 85000 |
| Manila | 70000 |
| George | 75000 |
| Mary | 50000 |
| Robert | 45000 |
| Henry | 40000 |
| Pat | 28000 |
+-----------+--------+
8 rows in set (0.00 sec)
NATURAL JOIN
● A natural join is a type of equi join where the join condition
compares all the same names columns in both tables
● example:
○ Query to display w_id,firstname, address,salary and city of all
employees from the table workers and desig
■ mysql> select w_id,firstname,address,salary,city from workers
natural join desig;
OUTPUT
+------+-----------+-------------------+--------+--------------+
| w_id | firstname | address | salary | city |
+------+-----------+-------------------+--------+--------------+
| 102 | Sam | 33 Elm St | 75000 | Paris |
| 105 | Sarah | U.S. 110 | 85000 | New york |
| 144 | Manila | 24 Friends Street | 70000 | New Delhi |
| 210 | George | 83 First Street | 75000 | Howard |
| 255 | Mary | 842, Vine Ave. | 50000 | Losantiville |
| 300 | Robert | 9 Fifth Cross | 45000 | Washington |
| 335 | Henry | 12 Moore Street | 40000 | Boston |
| 451 | Pat | 11 Red Road | 28000 | Paris |
+------+-----------+-------------------+--------+--------------+
8 rows in set (0.00 sec)

You might also like