DBMS Unit-1
DBMS Unit-1
INTRODUCTION:
 What is data?
       Data is nothing but facts and statistics stored or free flowing over a network,
       generally it's raw and unprocessed.
What is database?
  •    The database is a collection of inter-related data which is used to retrieve, insert and
       delete the data efficiently.
  •    It is also used to organize the data in the form of a table, schema, views, and reports,
       etc.
• Using the database, you can easily retrieve, insert, and delete the information.
 •    For example: The college Database organizes the data about the admin, staff, students
      and faculty etc.
 What is dbms?
         A database-management system (DBMS) consists of a collection of interrelated
 data and a set of programs to access those data. The collection of data, usually referred to
 as the database, contains information about one particular enterprise. The primary goal of
 a DBMS is to provide an environment that is both convenient and efficient to use in
 retrieving and storing database information.
        The management of data involves both the definition of structures for the storage of
 information and the provision of mechanisms for the manipulation of information. The
 database system must also provide for the safety of the information stored, despite system
 crashes or attempts at unauthorized access.
          The main purpose of database systems is to manage the data. Consider a university
 that keeps the data of students, teachers, courses, books etc. To manage this data we need to
 store this data somewhere where we can add new data, delete unused data, update outdated
 data, retrieve data, to perform these operations on data we need a Database management
 system that allows us to store the data in such a way so that all these operations can be
 performed on the data efficiently.
Characteristics of DBMS:
•       Data stored into Tables: Data is never directly stored into the database. Data is stored
        into tables, created inside the database.
•       Reduced Redundancy: In the modern world hard drives are very cheap, but earlier when
        hard drives were too expensive, unnecessary repetition of data in database was a big
        problem. But DBMS follows Normalisation which divides the data in such a way that
        repetition is minimum.
•       Data Consistency: On Live data, i.e. data that is being continuosly updated and added,
        maintaining the consistency of data can become a challenge. But DBMS handles it all by
        itself.
•       Support Multiple user and Concurrent Access: DBMS allows multiple users to work
        on it(update, insert, delete data) at the same time and still manages to maintain the data
        consistency.
•       Query Language: DBMS provides users with a simple Query language, using which data can
        be easily fetched, inserted, deleted and updated in a database.
Advantages of DBMS:
    •     Controls database redundancy: It can control data redundancy because it stores all
         the data in one single database file and that recorded data is placed in the database.
    •    Data sharing: In DBMS, the authorized users of an organization can share the data
         among multiple users.
    •    Easily Maintenance: It can be easily maintainable due to the centralized nature of the
         database system.
    •    Backup: It provides backup and recovery subsystems which create automatic backup of
         data from hardware and software failures and restores the data if required.
    •    Multiple User Interface: It provides different types of user interfaces like graphical user
         interfaces, application program interfaces
Disadvantages of DBMS:
    •    Cost of Hardware and Software: It requires a high speed of data processor and large
         memory size to run DBMS software.
• Size: It occupies a large space of disks and large memory to run them efficiently.
    •    Higher impact of failure: Failure is highly impacted the database because in most of the
         organization, all the data stored in a single database and if the database is damaged due
         to electric failure or database corruption then the data may be lost forever.
 APPLICATIONS OF DBMS:
•   Telecom: There is a database to keeps track of the information regarding calls made,
    network usage, customer details etc.
•   Industry: Where it is a manufacturing unit, warehouse or distribution centre, each one
    needs a database to keep the records of ins and outs
•   Banking System: For storing customer info, tracking day to day credit and debit
    transactions, generating bank statements etc.
•   Sales: To store customer information, production information and invoice details.
•   Airlines: To travel though airlines, we make early reservations; this reservation
    information along with flight schedule is stored in database.
•   Education sector: Database systems are frequently used in schools and colleges to store
    and retrieve the data regarding student details, staff details, course details, exam details,
    payroll data, attendance details, fees details etc.
VIEW OF DATA
 A major purpose of a database system is to provide users with an abstract view of the data.
 That is, the system hides certain details of how the data are stored and maintained.
         Data Abstraction: For the database system to be usable, it must retrieve data
 efficiently. This concern has led to the design of complex data structures for the representation
 of data in the database. Since many database-system users are not computer trained, developers
 hide the complexity from users through several levels of abstraction, to simplify user‟s
 interactions with the system:
         • Physical level: The lowest level of abstraction describes how the data are actually
 stored, which involves complex low-level data structures.
         • Logical level: The next-higher level of abstraction describes what data are stored
 in the database, and what relationships exist among those data. The logical level of abstraction
 is used by database administrators, who must decide what information is to be kept in the
 database.
       • View level: The highest level of abstraction describes only part of the entire
database. Users need to access only a part of the database. So that their interaction with the
system is simplified, the view level of abstraction is defined. The system may provide many
views for the same database.
        Instances and Schemas: Database change over time as information is inserted and
deleted. The collection of information stored in the database at a particular moment is called
an instance of the database. The overall design of the database is called the database schema.
Schemas are changed infrequently, if at all.
       A database schema corresponds to the programming-language type definition. A
variable of a given type has a particular value at a given instant. Thus, the value of a variable
in programming languages corresponds to an instance of a database schema.
        Database systems have several schemas. At the lowest level is the physical schema; at
the intermediate level is the logical schema; and at the highest level is a subschema. In general,
database systems support one physical schema, one logical schema, and several subschemas.
        Data independence: The ability to modify a schema definition in one level without
affecting a schema definition in the next higher level is called data independence. There are
two levels of data independence:
       1.      Physical data independence is the ability to modify the physical schema without
causing application programs to be rewritten. Modifications at the physical level are
occasionally necessary to improve performance.
       2.     Logical data independence is the ability to modify the logical schema without
causing application programs to be rewritten. Modifications at the logical level are necessary
whenever the logical structure of the database is altered.
        Logical data independence is more difficult to achieve than is physical data
independence, since application programs are heavily dependent on the logical structure of the
data that they access.
       • In this type of architecture, the database is readily available on the client machine,
any request made by client doesn‟t require a network connection to perform the action on the
database.
       • Any changes done here will directly be done on the database itself. It doesn't
provide a handy tool for end users.
       • The 1-Tier architecture is used for development of the local application, where
programmers can directly communicate with the database for the quick response.
Two tier architecture:
        • In two-tier architecture, the Database system is present at the server machine and
the DBMS application is present at the client machine, these two machines are connected
with each other through a reliable network.
        • Whenever client machine makes a request to access the database present at server
using a query language like sql, the server perform the request on the database and returns the
result back to the client.
        • The application connection interface such as JDBC, ODBC are used for the
interaction between server and client.
Three-Tier Architecture:
           -tier architecture, another layer is present between the client machine and server
machine.
systems present at the server machine, rather the client application communicates with server
application and the server application internally communicates with the database system present
at the server.
DBMS languages:
    Database languages are used to read, update and store data in a database. There are several
    such languages that can be used for this purpose; one of them is SQL (Structured Query
    Language).
 CREATE DATABASE:
 A Database is defined as a structured set of data. So, in SQL the very first step to store the
 data in a well structured manner is to create a database. The CREATE DATABASE
 statement is used to create a new database in SQL.
 Syntax:
 CREATE DATABASE database_name;
 Example:
 SQL> CREATE DATABASE Employee;
 In order to get the list of all the databases, you can use SHOW DATABASES statement.
 Example –
 SQL> SHOW DATABASES;
CREATE TABLE:
The CREATE TABLE statement is used to create a table in SQL. We know that a table
comprises of rows and columns. So while creating tables we have to provide all the
information to SQL about the names of the columns, type of data to be stored in columns,
size of the data etc. Let us now dive into details on how to use CREATE TABLE statement to
create tables in SQL.
Syntax:
CREATE TABLE table_name (
column1 data_type(size),
column2 data_type(size),
column3 data_type(size),
....
);
Example Query: This query will create a table named Students with three columns,
ROLL_NO, NAME and SUBJECT.
CREATE TABLE Students
(
ROLL_NO int(3),
NAME varchar(20),
SUBJECT varchar(20),
);
DROP:
DROP is used to delete a whole database or just a table.The DROP statement destroys the
objects like an existing database, table, index, or view.
A DROP statement in SQL removes a component from a relational database management
system (RDBMS).
Syntax:
DROP object object_name;
Examples:
DROP TABLE table_name;
table_name: Name of the table to be deleted.
DROP DATABASE database_name;
database_name: Name of the database to be deleted.
TRUNCATE
It is used to remove all records from a table, including all spaces
The TRUNCATE TABLE mytable statement is logically (though not physically) equivalent
to the DELETE FROM mytable statement (without a WHERE clause).
Syntax:
TRUNCATE TABLE table_name;
DROP vs TRUNCATE
• Truncate is normally ultra-fast and its ideal for deleting data from a temporary table.
• Truncate preserves the structure of the table for future use, unlike drop table where the
  table is deleted with its full structure.
• Table or Database deletion using DROP statement cannot be rolled back, so it must be
  used wisely.
To delete the whole database,
DROP DATABASE student_data;
     DROP                              TRUNCATE
     The DROP command in               The TRUNCATE command is
     SQL removes an entire             used to remove all of the rows from
     table from a database             a table, regardless of whether or
     including its definition,         not any conditions are met and
     indexes, constraints, data        resets the table definition.
     etc.
     It is a                           It is also a DDL(Data
      DDL(Data                            Definition Language)
      Definition Language)             command.
     command.
     The table space is                The table still exists in the
     completely freed from the         memory.
     memory.
     All the integrity                 The integrity constraints still exist
     constraints are removed.          in the table.
QUERY:
To ADD 2 columns AGE and COURSE to table Student.
ALTER TABLE Student ADD (AGE number(3),COURSE varchar(40));
MODIFY column COURSE in table Student
ALTER TABLE Student MODIFY COURSE varchar(20);
Comments
As is any programming languages comments matter a lot in SQL also. In this set we will
learn about writing comments in any SQL snippet.
Comments can be written in the following three formats:
        • Single line comments.
        • Multi line comments
        • In line comments
DML(Data Manipulation Language) : The SQL commands that deals with the
manipulation of data present in the database belong to DML or Data Manipulation Language
and this includes most of the SQL statements.
SELECT Statement
SELECT statement is used to fetch data from relational database. A relational database is
organized collection of data. As we know that data is stored inside tables in a database. SQL
select statement or SQL select query is used to fetch data from one or more than one tables.
SELECT Syntax:
One column: Here column_name is the name of the column for which we need to fetch data
and table_name is the name of the table in the database.
        SELECT column_name FROM table_name;
More than one columns:
        SELECT column_name_1, column_name_2, ... FROM table_name;
To fetch the entire table or all the fields in the table:
SELECT * FROM table_name;
Example:
SELECT EMP_NAME FROM EMPLOYEES;
To fetch the entire EMPLOYEES table:
SELECT * FROM EMPLOYEES;
Query to fetch the fields ROLL_NO, NAME, AGE from the table Student:
SELECT ROLL_NO, NAME, AGE FROM Student;
DELETE Statement
The DELETE Statement in SQL is used to delete existing records from a table. We can delete
a single record or multiple records depending on the condition we specify in the WHERE
clause.
Basic Syntax:
DELETE FROM table_name WHERE some_condition;
Deleting single record: Delete the rows where NAME = „Ram‟. This will delete only the first
row.
DELETE FROM Student WHERE NAME = 'Ram';
Deleting multiple records: Delete the rows from the table Student where Age is 20. This
will delete 2 rows(third row and fifth row).
DELETE FROM Student WHERE Age = 20;
Delete all of the records: There are two queries to do this as shown below,
query1: "DELETE FROM Student";
query2: "DELETE * FROM Student";
DCL(Data Control Language) : DCL includes commands such as GRANT and REVOKE
which mainly deals with the rights, permissions and other controls of the database system.
Examples of DCL commands:
TCL(transaction Control Language) : TCL commands deals with the transaction within the
database.
Examples of TCL commands:
        Database Users and User Interfaces: There are four different types of database-
 system users.
        • Application programmers are computer professionals who interact with the system
 through DML calls, which are embedded in a program written in a host language. These
 programs are referred to as application programs. A special preprocessor called the DML
 precompiler, converts the DML statements to normal procedure calls in the host language.
         • Sophisticated users interact with the system without writing programs. Instead,
 they form their requests in a database query language. Each such query is submitted to a query
 processor whose function is to break down DML statement into instructions that the storage
 manager understands.
         • Specialized users are sophisticated users to write specialized database applications
 that do not fit into the traditional data-processing framework. Among these applications are
 computer-aided design systems, knowledge base and expert systems, systems that store data
 with complex data types, and environment-modeling systems.
       • Naive users interact with the system by invoking one of the permanent application
 programs that have been written previously.
        Database Administrator: The person who has central control over the database
 system is called the database administrator (DBA). The functions of the DBA:
         • Schema definition. The DBA creates the original database schema by writing a set
 of definitions that is translated by the DDL compiler to a set of tables that is stored permanently
 in the data dictionary.
         • Storage structure and access-method definition. The DBA creates appropriate
 storage structures and access methods by writing a set of definitions, which is translated by
 the data-storage and data-definition-language compiler.
         • Schema and physical-organization modification. The DBA carries out changes to
 the database schema and the physical storage organization by writing a set of definitions that
 is used by either the DDL compiler or the data-storage and data-definition-language compiler
 to generate modifications to the appropriate internal system tables.
         • Granting of authorization for data access. The granting of different types of
 authorization allows the database administrator to regulate which parts of the database various
 users can access. This information is kept in a special system structure that is consulted by the
 database system whenever access to the data is attempted in the system.
         • Integrity-constraint specification. The data values stored in the database must
 satisfy certain consistency constraints, and such constraints must be specified explicitly by the
 database administrator. The integrity constraints are kept in a special system structure that is
 consulted by the database system whenever an update takes place in the system.
TRANSACTION MANAGEMENT
 ACID Properties:
        ACID Properties are used for maintaining the integrity of database during transaction
 processing. ACID in DBMS stands for Atomicity, Consistency, Isolation, and Durability.
             • In two-tier architecture, the application is partitioned into a component that resides at the
 client machine, which invokes database system functionality at the server machine through query language
 statements. E.g. client programs using ODBC/JDBC to communicate with a database.
             • In three-tier architecture, the client machine acts as a front end and does not contain any direct
 database calls. It communications with an application server through a forms interface. The application
 server in turn communicates with a database system to access data. E.g. web-based applications and
 applications built using “middleware”.
DATABASE SCHEMA:
         A database schema defines how data is organized within a relational database; this is inclusive of
 logical constraints such as, table names, fields, data types, and the relationships between these entities.
 Schemas commonly use visual representations to communicate the architecture of the database, becoming
 the foundation for an organization‟s data management discipline. This process of database schema design
 is also known as data modeling.
                 These data models serve a variety of roles, such as database users, database administrators, and
 programmers. For example, it can help database administrators manage normalization processes to avoid data
 duplication. Alternatively, it can enable analysts to navigate these data structures to conduct reporting or other
 valuable business analyses. These diagrams act as valuable documentation within the database management
 system (DBMS), ensuring alignment across various stakeholders.
KEYS:
         KEYS in DBMS is an attribute or set of attributes which helps you to identify a row(tuple) in a
 relation(table). They allow you to find the relation between two tables. Keys help you uniquely identify a
 row in a table by a combination of one or more columns in that table. Key is also helpful for finding unique
 record or row from the table. Database key is also helpful for finding unique record or row from the table.
Here are some reasons for using sql key in the DBMS system.
  •   Keys help you to identify any row of data in a table. In a real-world application, a table could contain
      thousands of records. Moreover, the records could be duplicated. Keys ensure that you can uniquely
      identify a table record despite these challenges.
  • Allows you to establish a relationship between and identify the relation between tables
  • Help you to enforce identity and integrity in the relationship.
TYPES OF KEYS:
  There are mainly seven different types of Keys in DBMS and each key has its different functionality:
 • Super Key - A super key is a group of single or multiple keys which identifies rows in a table.
 • Primary Key - is a column or group of columns in a table that uniquely identify every row in that
    table.
•   Candidate Key - is a set of attributes that uniquely identify tuples in a table. Candidate Key is a
    super key with no repeated attributes.
•   Alternate Key - is a column or group of columns in a table that uniquely identify every row in that
    table.
•   Foreign Key - is a column that creates a relationship between two tables. The purpose of Foreign keys
    is to maintain data integrity and allow navigation between two different instances of an entity.
•   Compound Key - has two or more attributes that allow you to uniquely recognize a specific
    record. It is possible that each column may not be unique by itself within the database.
•   Composite Key - An artificial key which aims to uniquely identify each record is called a surrogate key.
    These kind of key are unique because they are created when you don't have any natural primary key.
•   Surrogate Key - An artificial key which aims to uniquely identify each record is called a surrogate key.
    These kind of key are unique because they are created when you don't have any natural primary key.
RELATIONAL DATABASES:
        A relational database is a type of database that stores and provides access to data points that are
related to one another. Relational databases are based on the relational model, an intuitive, straightforward
way of representing data in tables. In a relational database, each row in the table is a record with a unique
ID called the key. The columns of the table hold attributes of the data, and each record usually has a value
for each attribute, making it easy to establish the relationships among data points.
Relational schema:
A relational schema specifies the relation‟ name, its attributes and the domain of each attribute. If R is the
name of a relation and A1,A2,… and is a list of attributes representing R then R(A1,A2,…,an) is called a
relational schema. Each attribute in this relational schema takes a value from some specific domain called
domain(Ai).
Example:
PERSON(PERSON_IDinteger,NAME: STRING,AGE:INTEGER,ADDRESS:string)
Total number of attributes in a relation denotes the degree of a relation.since the PERSON relation
schemea contains four attributes ,so this relation is of degree 4.
      SQL stands for Structured Query Language.SQL lets you access and manipulate databases
. In 1986, the American National Standards Institute (ANSI) and the International organization
for standardization (ISO) published an SQL Standard, called SQL-86. IBM published its own
corporate SQL standard, the systems Application Architecture Database interface (SAA-SQL)
in 1987. ANSI Published on extended standard for SQL, SQL-89, in 1989. The next version of
the standard was SQL-92, and the most recent version is SQL:1999.
          •   Data-Definition language (DDL): The SQL DDL provides commands for defining
              relation schemas, deleting relations, and modifying relation schemas.
          •   Interactive data – manipulation language (DML): The SQL DML includes a query
              language based on both the relational algebra and the tuple relational calculus. It
              includes also commands to insert tuples into, delete tuples from, and modify tuples
              in the database.
          •   View definition: The SQL DDL includes commands for defining views.
        •      Transaction control: SQL includes commands for specifying the beginning and
               ending of transactions.
        •      Embedded SQL and dynamic SQL: Embedded and SQL dynamic SQL define how
               SQL statements can be embedded within general– purpose programming
               languages, such as C, C++, Java, PL/I, Cobol, Pascal, and FORTRAN.
        •      Integrity: The SQL DDL includes commands for specifying integrity constraints
               that the data stored in the databases must satisfy. Updates that violated integrity
               constraints are disallowed.
        •      Authorization: The SQL DDL includes commands for specifying access rights to
               relations and views.
Data Definition:
DDL is short name of Data Definition Language, which deals with database schemas and
descriptions, of how the data should reside in the database.
 1) CREATE - to create a database and its objects like (table, index, views, store procedure,
 function, and triggers)
     Syntax
     CREATE TABLE table_name (column1datatype,column2datatype,column3datatype, ...... );
     The column parameters specify the names of the columns of the table.The datatype
     parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).
     The following example creates a table called "Persons" that contains five columns:
     PersonID, LastName, FirstName, Address, and City:
     Example
     CREATE TABLE Persons(PersonIDint,LastNamevarchar(255),FirstNamevarchar(255),
     Addressvarchar(255),Cityvarchar(255));
Example:
 Any text between -- and the end of the line will be ignored (will not be
 executed).The following example uses a single-line comment as an explanation:
 --Select all:
The following example uses a single-line comment to ignore the end of a line:
         Example:
         RENAME EMPLOYEE1 TO EMPLOYEE2;
         Or
         ALTER EMPLOYEE1 RENAME TO EMPLOYEE2;
Domain types:
A tuple variable is defined in the from clause by placing it after the name of
the relation with which it is associated, with the keyword as in between (the
keyword as is optional).
Tuple variables are most useful for comparing two tuples in the same relation.
The following example finds the names of all branches that have assets greater
than at least one branch located in Brooklyn.
select distinct T.branch–name from branch as T,
branch as S where T.assets > S.assets and S.branch-
city = „Brooklyn‟
         •   String Operations: SQL specifies strings by enclosing them in single
             quotes. A single quote character that is part of a string can be
             specified by using two single quote characters; for example the
             string “It‟s right” can be specified by „It‟‟s right‟.
The most commonly used operation on strings is pattern matching using the
operator like. Patterns are described by using two special characters:
         •   Percent (%): The % character matches any substring.
         •   Underscore (_): The _ character matches any character.
Patterns are case sensitive; i.e., uppercase characters do not match lowercase
characters, or vice versa. To illustrate pattern matching, consider the following
examples:
         •   „Perry%‟ matches any string beginning with “Perry”.
For patterns to include the special pattern characters (% and _), SQL allows the
specification of an escape character. The escape character is used immediately
before a special pattern character to indicate that the special character is to be
treated like a normal character. To illustrate, consider the following patterns,
which use a backslash (\) as the escape character:
         •    like „ab\%cd%‟ escape „\‟ matches all strings beginning with “ab%cd”.
         •    like „ab\\cd%‟ escape „\‟ matches all strings beginning with “ab\cd”.
SQL allows us to search for mismatches instead of matches by using the not
like comparison operator. SQL also permits a variety of functions on character
strings, such as concatenation (using “||”), extracting substrings, finding the
length of strings, converting between uppercase and lowercase, and so on.
SQL:1999 also offers a similar to operation, which provides more powerful
pattern matching than the like operation.
         •    Ordering the Display of Tuples: The order by clause causes the
              tuples in the result of a query to appear in sorted order. By default,
              the order by clause lists items in ascending order. To specify the sort
              order, use desc for descending order or asc for ascending order.
              Ordering can also be performed on multiple attributes.
Suppose to list the entire loan relation in descending order of amount, and if
several loans have the same amount, then to order them in ascending order by
loan number, the query can be written as
select * from loan order by amount desc, loan-number asc
Since sorting a large number of tuples may be costly, it should be done only when
necessary.
         •    Duplicates: SQL formally defines not only what tuples are in the
              result of a query, but also how many copies of each of those tuples
              appear in the result. The duplicate semantics of an SQL query can
            be defined using multiset versions of the relational operators.
Let r1 (R1) and r2 (R2) be relations with primary keys K 1 and K2, respectively.
A subset  of R2 is a foreign key referencing K1 in relation r1 if it is required
that, for every tuple t2 in r2, there must be a tuple t1 in r1 such that t1 [K1] = t2
[]. Requirements of this form are called referential integrity constraints or
subset dependencies, because the referential integrity constraint can be written
as  (r2)  K1 (r1). The symbol  is used to indicate the projection operation.
Database modifications can cause violations of referential integrity. The following
list of tests must be made for each type of database modification to preserve the
following integrity constraint:
 (r2)  K (r1)
        •   Insert. If a tuple t2 is inserted into r2, the system must ensure that there is a
            tuple t1
                 in r1 such that t1 [K] = t2 []. i.e. t2 []  K (r1).
        •   Delete. If a tuple t1 is deleted from r1, the system must compute the
                set of tuples in r2 that reference t1:   = t1 [K] (r2). If this set is not
                empty, either the delete command is rejected as an error, or the
                tuples that reference t1 must themselves be deleted.
        •   Update. Consider two cases for update: updates to the referencing
               relation (r2), and updates to the referenced relation (r1).
        ❑   If a tuple t2 is updated in relation r2, and the update modifies values
            for the foreign key , then the system must ensure that t2 []  K
            (r1), where t2 denotes the new value of tuple t2.
        ❑   If a tuple t1 is updated in r1, and the update modifies values for the
            primary key (K), then the system must compute   = t1 [K] (r2) using
            the old value of t1 (the value before the update is applied). If this set
            is not empty, the update is rejected as an error, or the update is
            cascaded in a manner similar to delete.
Foreign keys can be specified as part of the SQL create table statement by
using the foreign key clause. By default, a foreign key references the primary
key attributes of the referenced table. SQL also supports a version of the
references clause where a list of attributes of the referenced relation can be
specified explicitly. The specified list of attributes must be declared as a
candidate key of the referenced relation.
Consider the definition of an integrity constraint on the relation account with
the referenced relation branch:
create table branch (branch-name char (15), branch-city char (30), assets
integer, primary key (branch-name), check (assets >= 0))
create table account (account-number char (10), branch-name char (15),
balance integer, primary key (account-number), foreign key (branch-name)
references branch on delete cascade on update cascade, check (balance >= 0))
When a referential integrity constraint is violated, the normal procedure is to
reject the action that caused the violation.
Because of the clause on delete cascade associated with the foreign key
declaration, if a delete of a tuple in branch results in this referential integrity
constraint being violated, the system does not reject the delete. Instead, the
delete “cascades” to the account relation, deleting the tuple that referes to the
branch that was deleted.
Similarly, the system does not reject an update to a field referenced by the
constraint if it violates the constraint; instead, the system updates the field
branch-name in the referencing tuples in account to the new value.
SQL also allows the foreign key clause to specify actions other than cascade,
if the constraint is violated. The referencing field branch-name can be set to null
(by using set null in place of cascade), or to the default value for the domain (by
using set default).
If there is a chain of foreign key dependencies across multiple relations, a
deletion or update at one end of the chain can propagate across the entire chain.
When the foreign key constraint on a relation references the same relation, then if
a cascading update or delete causes a constraint violation that cannot be handled
by a further cascading operation, the system aborts the transaction, and all the
changes caused by the transaction and its cascading actions are undone.
Set Operations:
The SQL operations union, intersect, and except operate on relations and
correspond to the relational algebra operations , , and −. The relations
participating in the operations must have the same set of attributes.
 1) The Union Operation: The union operation automatically eliminates
 duplicates. The following query finds all customers having a loan, an account,
 or both at the bank. If a customer has several accounts or loans (or both) at
 the bank, then that customer will appear only once in the result.
(select customer-name from depositor) union (select customer-name
from borrower) If all duplicates are to be retained, then write union all
in place of union.
(select customer-name from depositor) union all (select customer-name from borrower)
The number of duplicate tuples in the result is equal to the total number of
duplicates that appear in both depositor and borrower. Thus, if a customer has
three accounts and two loans at the bank, then there will be five tuples with the
same customer name in the result.
Syntax
Example:
 The First table
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
    3                           Jackson
    4                           Stephan
    5                           David
 Union SQL query will
         be: SELECT *
         FROM First
         UNION
        SELECT * FROM
Second; The resultset table
will look like:
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
 2) Union All:
Union All operation is equal to the Union operation. It returns the set
without removing duplication and sorting the data.
Syntax:
         SELECT column_name
         FROM table1 UNION ALL
        SELECT column_name FROM table2;
Example: Using the above First and Second
table. Union All query will be like:
         SELECT * FROM
         First UNION ALL
        SELECT * FROM
Second; The resultset table
will look like:
 ID                            NAME
   1                           Jack
    2                          Harry
    3                          Jackson
    3                          Jackson
    4                          Stephan
    5                          David
 3) Intersect:
    o    It is used to combine two SELECT statements. The Intersect
         operation returns the common rows from both the SELECT
         statements.
    o    In the Intersect operation, the number of datatype and columns must be the same.
    o    It has no duplicates and it arranges the data in ascending order by default.
Syntax
         SELECT column_name
         FROM table1 INTERSECT
         SELECT column_name FROM table2;
Example:
 Using the above First and Second table.
Intersect query will be:
         SELECT * FROM
         First INTERSECT
        SELECT * FROM
Second; The resultset table
will look like:
 ID                               NAME
     3                           Jackson
 4) EXCEPT OR MINUS:
      o    It combines the result of two SELECT statements. Minus operator is
           used to display the rows which are present in the first query but absent
           in the second query.
      o    It has no duplicates and data arranged in ascending order by default.
Syntax:
           SELECT column_name
           FROM table1 MINUS
           SELECT column_name FROM table2;
Example
 Using the above First and Second table.
Minus query will be:
           SELECT * FROM
           First MINUS
          SELECT * FROM
Second; The resultset table
will look like:
ID NAME
1 Jack
2 Harry
Aggregate Functions:
In database management an aggregate function is a function where the values
of multiple rows are grouped together as input on certain criteria to form a
single value of more significant meaning.
Various Aggregate Functions
 1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
Count():
 Count(*): Returns total number of records .i.e 6.
 Count(salary): Return number of Non Null values over the column salary. i.e 5.
 Count(Distinct Salary): Return number of distinct Non Null values over the column
 salary. i.e 4
Sum():
 sum(salary): Sum all Non Null values of Column salary i.e., 310.
 sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.
Avg():
 Avg(salary) =     Sum(salary) / count(salary) = 310/5
 Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4
Min():
  Min(salary): Minimum value in    the salary column except NULL           i.e.,   40.
  Max(salary): Maximum value in the salary i.e., 80.
Null Values:
The term NULL in SQL is used to specify that a data value does not exist in
the database. It is not the same as an empty string or a value of zero, and it
signifies the absence of a value or the unknown value of a data field.
Some common reasons why a value may be NULL −
    •    The value may not be provided during the data entry.
       •   The value is not yet known.
It is important to understand that you cannot use comparison operators such as
“=”, “<”, or “>” with NULL values. This is because the NULL values are
unknown and could represent any value. Instead, you must use “IS NULL” or
“IS NOT NULL” operators to check if a value is NULL.
Syntax
The basic syntax of NULL while creating a
table. SQL> CREATE TABLE
CUSTOMERS(
      ID INT        NOT NULL,
      NAME VARCHAR (20) NOT
      NULL, AGE INT         NOT
      NULL, ADDRESS CHAR (25) ,
      SALARY DECIMAL (18,
      2), PRIMARY KEY (ID)
);
Here, NOT NULL signifies that column should always accept an explicit value
of the given data type. There are two columns where we did not use NOT
NULL, which means these columns could be NULL.
A field with a NULL value is the one that has been left blank during the record creation.
Example
Let us create a table with the name CUSTOMERS in the SQL database using
the CREATE statement as shown in the query below −
     SQL> CREATE TABLE
      CUSTOMERS( ID INT NOT
      NULL,
IS NULL Query
Let us try to retrieve the records present in the table that are null using the IS NULL
operator
−
 SQL> SELECT ID, NAME, AGE, ADDRESS,
   SALARY FROM CUSTOMERS
Verification
Let us try to verify whether the specified record(s) in the table is updated or not
using the following query −
SQL> SELECT * FROM CUSTOMERS;
On executing the above query, the output is displayed as follows −
Output
You will get the following output −
2 Bob 3 1.44
3 Jam 1 3.24
4 Lucky 2 2.67
     5     Ram                      2                      4.56
Teacher table
The teacher table is created as follows −
Example
Create table teacher(id number(10), name varchar(20), subject varchar2(10),
classID number(10), salary number(30));
Insert into teacher values(1,‟bhanu‟,‟computer‟,3,5000);
Insert into teacher values(2,'rekha','science',1,5000);
Insert into teacher values(3,'siri','social',NULL,4500);
Insert into teacher values(4,'kittu','mathsr',2,5500);
select * from teacher;
Output
You will get the following output −
       I   Name          Subject          classID      Salary
       d
       1   Bhanu         Computer         3            5000
Class table
The class table is created as follows −
Example
Create table class(id number(10), grade number(10), teacherID
number(10), noofstudents number(10));
insert into class
values(1,8,2,20); insert into
class values(2,9,3,40); insert
into class values(3,10,1,38);
select * from class;
Output
You will get the following output –
 ID        Grade          teacherID           No.ofstudents
1 8 2 20
2 9 3 40
3 10 1 38
 Example 2
 SELECT * FROM
 student WHERE
 classID = (
    SELECT id
    FROM class
    WHERE noofstudents = (
      SELECT
      MAX(noofstudents)
      FROM class));
 Output
 You will get the following
 output − 4|lucky |2|2.67
 5|ram |2|4.56
 Complex Queries:
 Complex queries are often impossible to write as a single SQL block or a union /
 intersection
 / difference of SQL blocks. There are two ways of composing multiple SQL
 blocks to express a complex query.
 Derived Relations: SQL allows a subquery expression to be used in the from
clause. If such an expression is used, then the result relation must be given a
name, and the attributes can be renamed. This renaming is done using the as
clause. Consider the subquery
 select branch-name,avg (balance) from account group by branch-name)
 as result (branch-name, avg-balance);
 This subquery generates a relation consisting of the names of all branches and
their corresponding average account balances. The subquery result is named
result, with the attributes branch-name and avg-balance.
The following query finds the average account balance of those branches where
the average account balance is greater then $1200.
(select branch-name, avg-balance
from (select branch-name, avg
(balance) from account
group by branch-name)
as branch-avg (branch-name, avg-
balance) where avg-balance > 1200
The subquery in the from clause computes the average balance, and it
result is named as branch-avg. The attributes of branch-avg can be used
directly in the where clause.
The query shown below finds the maximum across all branches of the total
balance at each branch.
select max (tot-balance)
from (select branch-name, sum
(balance) from account group by
branch-name)
as branch-total (branch-name, tot-balance)
The With Clause: The with clause provides a way of defining a temporary
view whose definition is available only to the query in which the with clause
occurs. Consider the following query, which selects accounts with the
maximum balance; if there are many accounts with the same maximum
balance, all of them are selected.
with max-balance (value)
as select max (balance)
from account
select account-number
from account, max-balance
where account.balance = max-balance.value
The with clause makes the query logic clearer; it also permits a view
definition to be used in multiple places within a query.
The following query is to find all branches where the total account deposit
is less than the average of the total account deposits at all branches.
with branch-total (branch-name, value) as select branch-name, sum (balance)
from account
group by branch-name
with branch-total-avg (value) as select avg (value)
from branch-total select branch-name
from branch-total, branch-total-avg
where branch-total.value < branch-total-avg.value;
Views:
 o   Views in SQL are considered as a virtual table. A view also contains rows
     and columns.
 o   To create the view, we can select the fields from one or more tables
     present in the database.
A view can either have specific rows based on certain condition or all the
rows of a table.
Sample table: Student_Detail
 Student_Marks
         STU_ID               NAME                   MARKS                 AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1.   Creating view
A view can be created using the CREATE VIEW statement. We can create
a view from a single table or multiple tables.
     Syntax:
     CREATE VIEW view_name AS SELECT column1, column2.....
     FROM table_name WHERE condition;
2. Creating    View from a single
     table Query:
     CREATE VIEW DetailsView AS SELECT NAME, ADDRESS
     FROM Student_Details WHERE STU_ID < 4;
     Just like table query, we can query the view to view the data. SELECT *
     FROM DetailsView;
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
View from multiple tables can be created by simply include multiple tables
in the SELECT statement.
In the given example, a view is created named MarksView from two tables
Student_Detail and Student_Marks.
Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME,
       Student_Detail.ADDRESS,
       Student_Marks.MARKS FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;
To display data of View MarksView: SELECT * FROM MarksView;
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
          Alina                   Gurugram                   90
4.   Deleting View
     A view can be deleted using the Drop View statement.
     Syntax
      1. DROP VIEW view_name;
     Example:
     If we want to delete the View MarksView, we can do this as:
            1.   DROP VIEW MarksView;
     Uses of a View :
     A good database should contain views due to the given reasons:
     1.    Restricting data access –
     Views provide an additional level of table security by restricting access to a
     predetermined set of rows and columns of a table.
      2.   Hiding data complexity –
     A view can hide the complexity that exists in a multiple table join.
      3.   Simplify commands for the user –
     Views allows the user to select information from multiple tables without
     requiring the users to actually know how to perform a join.
     4.    Store complex queries –
     Views can be used to store complex queries.
     5.    Rename Columns –
     Views can also be used to rename the columns without affecting the base tables
     provided the number of columns in view must match the number of columns
     specified in select statement. Thus, renaming helps to to hide the names of the
     columns of the base tables.
     6.    Multiple view facility –
     Different views can be created on the same table for different users.
     Joined relations:
     Join is a combination of a Cartesian product followed by a selection process.
     A Join operation pairs two tuples from different relations, if and only if a given
     join condition is satisfied.
     We will briefly describe various join types in the following
     sections. Example:
EMPLOYEE
    EMP_CODE                          EMP_NAME
     101                            Stephan
     102                            Jack
     103                            Harry
    SALARY
EMP_CODE SALARY
101 50000
102 30000
     103                                    25000
     1. Operation: (EMPLOYEE ⋈ SALARY)
Result:
PlayNext
Unmute
Current Time 0:00
/
Duration 18:10
Loaded:
0.37% Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
1. Natural Join:
EMP_NAME SALARY
Stephan 50000
Jack 30000
   Harry                                         25000
2.Outer Join:
The outer join operation is an extension of the join operation. It is used to
deal with missing information.
Example:
 EMPLOYEE
 Input:
    1.   (EMPLOYEE ⋈ FACT_WORKERS)
Output:
    o    Left outer join contains the set of tuples of all combinations in R and
         S that are equal on their common attribute names.
    o    In the left outer join, tuples in R have no matching tuples in S.
    o    It is denoted by ⟕.
Example: Using the above EMPLOYEE table and FACT_WORKERS table
Input:
    1. EMPLOYEE ⟕ FACT_WORKERS
    o    Right outer join contains the set of tuples of all combinations in R and
         S that are equal on their common attribute names.
    o    In right outer join, tuples in S have no matching tuples in R.
    o    It is denoted by ⟖.
Example: Using the above EMPLOYEE table and FACT_WORKERS Relation
Input:
    1. EMPLOYEE ⟖ FACT_WORKERS
Output:
Example:
 CUSTOMER RELATION
CLASS_ID NAME
1 John
2 Harry
   3                                             Jackson
PRODUCT
PRODUCT_ID CITY
   1                                                     Delhi
   2                                                     Mumbai
3 Noida
 Input:
    2.   CUSTOMER ⋈ PRODUCT
 Output:
 CLASS_ID              NAME            PRODUCT_ID                  CITY
   1                     John            1                         Delhi
   2                     Harry           2                         Mumbai
3 Harry 3 Noida