Unit 3 (DBMS)
Unit 3 (DBMS)
SQL stands for Structured Query Language. People often pronounce it as either “S-Q-L” or
“sequel.” SQL is used in programming and is designed for managing data stored in a database
using SQL queries.
The most common type of database management system (DBMS) is a relational database
management system (RDBMS), where we store structured data, i.e., data incorporating relations
among entities and variables. These entities and variables are organized as a set of tables with
columns and rows. Some of the most popular RDBMS are MYSQL, Oracle, IBM DB2, and Microsoft
SQL Server database.
The data in RDBMS is stored in a database object called table. A database often contains several
tables. Each table is identified by a unique name and contains a collection of related data entries
structured as rows and columns.
A column is a vertical entity; they are called fields and contain all information associated with a
specific field in a table. Each row in a table is known as a record; it is the horizontal entity in the
table.
The structure of a database can feel very similar to Excel. However, databases, in general, are more
powerful than Excel spreadsheets. Here are three reasons why you could say so:
SQL Constraints:
In a database table, we can add rules to a column known as constraints. These
rules control the data that can be stored in a column.
For example, if a column has             NOT NULL   constraint, it means the column cannot
store    NULL   values.
The constraints used in SQL are:
Constraint Description
Here, the       college_id   and the   college_code   columns of the        Colleges   table won't
allow    NULL   values.
UNIQUE Constraint
The    UNIQUE   constraint in a column means that the column must have unique value.
For example,
CREATE TABLE Colleges (
   college_id INT NOT NULL UNIQUE,
   college_code VARCHAR(20) UNIQUE,
   college_name VARCHAR(50)
);
Run Code
Here, the value of the        college_code   column must be unique. Similarly, the value
of   college_id   must be unique as well as it cannot store       NULL   values.
Here, the value of the        college_id   column is a unique identifier for a row. Similarly, it
cannot store       NULL   value and must be     UNIQUE .
Here, the value of the      college_code   column references the row in another table
named       Customers .
It means that the value of       customer_id    in the   Orders   table must be a value from
the   id   column of the   Customers   table.
CHECK Constraint
The   CHECK   constraint checks the condition before allowing values in a table. For
example,
CREATE TABLE Orders (
   order_id INT PRIMARY KEY,
   amount int CHECK (amount >= 100)
);
Run Code
Here, the value of the      amount   column must be greater than or equal to 100. If not,
the SQL statement results in an error.
DEFAULT Constraint
The   DEFAULT   constraint is used to set the default value if we try to store            NULL   in a
column. For example,
CREATE TABLE College (
   college_id INT PRIMARY KEY,
   college_code VARCHAR(20),
   college_country VARCHAR(20) DEFAULT 'US'
);
Run Code
-- create index
CREATE INDEX college_index
ON Colleges(college_code);
Run Code
A Trigger in Structured Query Language is a set of procedural statements which are executed
automatically when there is any response to certain events on the particular table in the database.
Triggers are used to protect the data integrity in the database.
In Structured Query Language, triggers are called only either before or after the below
events:
   1. INSERT Event: This event is called when the new row is entered in the table.
   2. UPDATE Event: This event is called when the existing record is changed or modified in
       the table.
   3. DELETE Event: This event is called when the existing record is removed from the table.
The following query creates the Student_Trigger table in the SQL database:
   1. DESC Student_Trigger;
Output:
The following query inserts the record into Student_Trigger table:
To check the output of the above INSERT statement, you have to type the following SELECT
statement
   1. SQL provides an alternate way for maintaining the data and referential integrity in the tables.
   2. Triggers helps in executing the scheduled tasks because they are called automatically.
   3. They catch the errors in the database layer of various businesses.
   4. They allow the database users to validate values before inserting and updating.
Disadvantages of Triggers in SQL
Following are the main disadvantages of triggers in Structured Query Language:
       •     SELECT specifies which columns are to appear in the output DISTINCT eliminates
             duplicate
       •     FROM specifies the tables to be used
       •     WHERE filters the rows according to the condition The where condition is a boolean
             combination (using AND, OR, and NOT) of conditions of the form expression op
             expression where op is one of the comparison operators (<=, =, <>, >=, >)
       •     GROUP BY forms groups of rows with the same column value
       •     HAVING filters the group
       •     ORDER BY sorts the order of the output
    Set Operations:
            Union,
            Except(minus) Intersect
           Aijay       A1
                                                Vishal      L1
           Vijay       A2
                                                Ram         L2
           Ram         A3
                 student1                             student2
 Union (U):- it is the binary operation between the two relations r and s. denoted by r U s. It is the
  union of set of tuples of the two relations. Duplicate tuples are automatically removed from the
 result. A tuple will appear in r U s if it exists in r or in s or both for U to be possible, r and s must
 be compatible.
           a) r and s must be of same degree i.e. they must have same no of attributes
           b) For all i, the domain of ith attribute of r must be same as the domain of the ith attribute
              of s.
 Query:-. Get the names of those students who have either account or loan or both at the bank
 SQL: select sname from student1 union select sname from student2;
 Result:
                          Sname
Aijay
Vijay
Ram
Vishal
Except (-): The set difference operation (r -s) between two relations r and s produced a relation
with tuples which are in r but not there in s. To possible r-s, r and s must be compatible
     Cardinality of r-s = cardinality (r) – cardinality (r ∩ s)
     Query:. Get the names of those students who have account in the bank but do not have loan
     SQL: select sname from student1 minus select sname from student2;
     Result:
                          Sname
Ajay
Vijay
Intersect (∩): his operation r ∩ s between the relations r and s produced a relation with tuples
 which are there in r as well as s. For is to be possible, relations r and s must be compatible
     Query: get the names of those students who have account as well as loan
     SQL: select sname from student1 intersect select sname from student2;
     Result:
                          Sname
                       Aijay
Vijay
Data types:-
               Each value in oracle is maintained by a data type.
               The value of one data type is different from other data type.
               The data type defines the domain of values that each column can contain
Character data types:-
 This data type is used to store character data. Different character data types are
          1.char
           2. varchar2
1. Char data type: - it specifies fixed length character string. Size should be specified. If the
   data is less then original specific size, blank spaces are applied. The default length is 1byte
   and maximum length is 200 bytes.
           Ex: - char (10);
2. Varchar2 data types: - it specifies the variable length character string. It occupies only that
   space for which the data is supplied. The maximum size is 1byte and the maximum size is
   400 bytes.
          Ex: - varchar2 (10);
        a) number(P, S)
                         i. P is precision, range is 1 to 38
                         ii. S is scale; range is -84 to 12
                         iii. Ex: - number (8, 3);
        b) Float: - it is used to specify floating point values. It specifies decimal precision 38.
        c) Long data types: - these are used to store very large text strings. A single table can
           have only one long column.
4.   Date and time data type:-
        • Date: - it is used to store date information. The default date format in oracle is DD-
          MM-YYY Ex:- 29-07-2019
        • Time: this is used to store time information. It has atleast 8 positions embedded in
           single quotes. „HH:MM:SS‟ Ex: - 11:07:05
          • Time stamp: - it includes both time and date along with minimum 6digits
             representing decimal fraction of seconds. The format is „DD-MM-YYYY
             HH:MM: SS‟
             Ex: - ‟31-05-1950 01:02:05 123456‟
      5. Large object data types: - these can store large and unstructural data like text, image,
         video and special data. the max size is up to 4 GB
            The types are
               • BLOB(binary large object)
               • CLOB(character large object) Maximum size is 4 GB
      6. Raw and long raw data types: - these are used to store binary data or byte strings. These
         are variable length data types. They are mostly used to store graphics, sound documents
         etc.
SQL:
Structured Query Language is used to perform operations on the records stored in the database
such as updating records, deleting records, creating and modifying tables, views, etc.
SQL is just a query language; it is not a database. To perform SQL queries, you need to install any
database, for example, Oracle, MySQL, MongoDB, PostGre SQL, SQL Server, DB2, etc.
            1. Insert
            2. Update
            3. Delete
    Syntaxes and examples:-
3. Data query language (DQL):- It is used to extract data from database tables.
      1. Select
          Syntax:- Select <col-list>, <group functions>from <table-name> where
          <condition> groupby <column>having<group condition>orderby<column-name>
          Ex:- Select deptno, sum(sal), max(sal), min(sal), avg(sal) from emp
          Where job=‟clerk‟ group by deptno having avg(sal)>1000 order by deptno;
4. Data control languages: - These commands control the user access to the database.
      The commands comes under these languages are
              1. Grant
              2. Revoke
          Grant: - used to grant the permissions to the user on the db tables. Syntax: - grant
             <priviliges-name>ON <object name>to<user-name>
                  Ex: - grant select, insert, delete on emp to operators; Revoke:
   - used to take back the permissions from the user.
               Syntax: - revoke<priviliges-name>ON <object name>from<user-name>
                  Ex: - revoke insert, delete on emp from operators;
5. Data administrative language(DAL):- These commands are used for audit, the
     commands are
                            1. Start audit;
                            2. Sleep audit;
6. Transaction control language (TCL): -These commands are used to control the transactions
                         1. Commit
                         2. Rollback
                         3. Savepoint
  Syntaxes:-
                      1.       commit;
                      2.       rollback;
                      3.       rollback to<save point name>; Relational set operators:-
   1. union:- merges the output of two or more queries into a single set of rows and columns.
       Ex:-select job from emp where deptno=10 union select job from emp where deptno=30;
   2. union all:- union suppresses the duplicates where as union all will also display
      duplicates.
         Ex:- select empno, ename from emp where deptno=10 union all select empno, ename
                                                            from emp where deptno=30;
   3. intersect:- this operator returns the common rows that are common between two
      queries.
      Ex:- select job from emp where deptno=20 intersect select job from emp where
      deptno=30;
   1) Single row subquery: - These returns only one row from inner select statement.
      It uses only single row operator. (>,=,<,<=,>=)
       Ex: - select ename, sal, job from emp where sal>(select sal from emp where
                                                       empno=7566);
   2) Multiple row subquery: - The subqueries return more than one row are called multiple
      row sub queries. In this case multiple row operators are used.
                    4) Inline subquery:-in this the subquery may be applied in select list and inform clause.
                       Ex:- Select ename, sal, deptno from (select ename, sal, deptno, mgr, hiredate from emp);
                   1. max():- used to get max value from the list of values ex:- select max(sal) from emp;
                       output:- MAX(sal)
                         ------------
                         10000
                           Output:- MIN(sal)
                          ------------
                         800
                   3. sum():- used to get the total sum of values.
                           ex:- select sum(sal)from emp;
            output:- SUM(sal)
        ------------
      37525
4. avg ():- used to get the average value of the given values.
            Ex:- select avg(sal) from emp;
            Output:- AVG(sal)       ------
---------
      2680.35714
5. count():- used to count the list of values
            ex:- selsct count(sal)from emp;
            output:- COUNT(sal)
        ----------------
               14
6. Order by clause:- it is used sort the values of column in ascending or descending oreder.
            Ex:- select ename from emp order by ename;
            Output:-
            ENAME
            ------------
            Adems Allen Blake Clerk Ford James Jhons King Martin Miller Scort Smith Turner
                                                                Ward
            8 rows are selected
            Ex:- select sal from emp order by sal desc;
            Output:-
            SAL
            -------
            10000
            5000 3000                   By default order by clause sort the values in ascending order
            3000 2975 2850
            2450
            7 rows selected
            Group by clause:-this is used to display the group wise data i.e. department, job wise
Select deptno, count(*) from emp group by deptno;
                      Output:-
                        DEPTNO                                              COUNT (*)
                      -------------                                         ---------------
                        30                                                  6
                        20                                                  5
                        10                                                  3
            Having clause:
          It is used to define conditions on a grouping column. Where clause defines conditions     on the
                       selected columns where has the having clause places conditions on groups created by
                       the group by clause.
                         Ex: - select deptno, min(sal) from emp group by deptno having min(sal)>800;
               DEPTNO                                                      MIN (sal)
                -------------                                               --------------
                30                                                          950
                10                                                          1300
                Ex:- select job, min(sal)from emp group by job having min(sal)>800; Output:-
                JOB                                              MIN (SAL)
                ---------                                        ----------------
                Salesman                                                    1250
                President                                                   5000
                Manager                                                     2450
                  analyst                                      3000
ex:- select job, sum(sal), avg(sal), min(sal), max(sal) from emp where deptno=20 group by job having
                  avg(sal)>1000 order by job;
                JOB                        SUM (SAL)                      AVG (SAL) MIN(SAL)                 MAX(SAL)
                ------------------------------------------------------------------------------------------------------------------
                ----------
                Analyst                        6000                         3000             3000                 3000
                Manager                       2976                          2975            2975                 2975
The regular operators like +, -, *, %, =, <, >, <=, >= will be fail with null values.
1. is null
             2. is not null
 Ex:- select ename from emp where column is null
 We have the following functions to handle with the null values.
1. nvl()
2. nvl2()
   3. coalesce() nvl(expr/column,
default value):-
 This function returns first argument value if the first argument is not null, if it is null then it
 return the 2nd argument value.
 Ex: - select nvl(column,0) from emp;
 In the output of above query if column is null then the default value (2 nd argument) i.e. 0 will
 be displayed, if column is not null then that value is displayed as it is.
   Output:-
   20 first not null value.
   Select coalesce (null, null, 30) from dual;
   Output:-
   30 first not null value in the argument list.
   Column1         Column2
                                 Row Selected
   Satisfied?      Satisfied?
     YES             YES              YES
     YES              NO              YES
      NO             YES              YES
      NO              NO              NO
   Column1         Column2
                                 Row Selected
   Satisfied?      Satisfied?
     YES             YES              YES
     YES              NO              NO
      NO             YES              NO
      NO              NO              NO
The following table describes how logical "NOT" operator selects a row.
   •   Transactions
           o A transaction is a sequence of queries and update statements executed as a
             single unit
           o For example, transferring money from one account to another
                 ▪ Both the deduction from one account and credit to the other account
                    should happen, or neither should
   •   Triggers
           o A trigger is a statement that is executed automatically by the system as a side
             effect of a modification to the database
•    Integrity Constraints
         o Predicates on the database that must always hold
         o Key Constraints: Specifiying something is a primary key or unique
    Joins: - joins is a query that combines rows from two or more tables or views
           if some column name appears more than one table, the name must be prefixed with
            table name.
           To join n tables together, we need a minimum of n-1 conditions.
Join types:-
      1. Simple join/equi join/inner join
      2. Non equi join
      3. Self join
      4. Cartesian product
      5. Natural join
      6. Outer join
      1. Simple join:- in this the join condition containing equality operator. Ex:- select
          E.empno,      E.ename,     D.deptno,       D.dname,   from   emp   E,   dept   D   where
          E.deptno=D.deptno;
                         Join condition
      2. Non equi join:- in this no column of one table will not corresponds to any column of
         other table means the domain of no column in a table is not same as the domain of other
         table.
                  in this type no equal operator based on common columns in the join condition.
               Ex: - select E.ename, E.sal, S.grade from emp E, salgrade S where E.sal between
                 S.losal and S.hisal;
        Student2
     Sname        loan
     Vishal ram L1
                  L2
        Student1 * stuednt2
     Student1.sname            account                  Student2.sname           loan
     Ajay                      A1                       Vishal                   L1
     Ajay                      A1                       Ram                      L2
     Vijay                     A2                       Vishal                   L1
     Vijay                     A2                       Ram                      L2
     Ram                       A3                       Vishal                   L1
     ram                       A3                       ram                      L2
 R.O.J:- it gives the full information about right side table (2nd) along with the natural join.
    sname           account           sname               loan
    Ram             A3 Null           Ram                 L2
    vishal                            vishal              L1
 R.O.J:- it will give the full information about lest and right side tables along with natural join.
       sname            account      sname               loan
       Ram              A3           Ram                 L2
       Ajay             A1           Ajay                Null
       Vijay            A2           Vijay               Null
       vishal           null         vishal              L1
SQL Queries:-
               Select * from student1 left outer join students on stydent1.sname
                 = student2.sname;
stydent1.sname=student2.sname;
                 stydent1.sname=student2.sname;
Complex integrity constraints:
 We have discussed the integrity constraints in the unit-II but we can make them more complex
 by defining a table with two or more foreign keys in a table by referring primary keys of
 different tables as shown below
 SQL> create table sailors(sid number(2)primary key,sname varchar2(10),rating num ber(2),age
         float);
 Table created. SQL> desc sailors;
  Name         Null?                                       Type
 ----------------------------------------- -------- ----------------------------
 SID           NOT NULL                                       NUMBER(2)
 SNAME                                                        VARCHAR2(10)
 RATING                                                    NUMBER(2)
     AGE                                            FLOAT(126)
     SQL> create table boats(bid number(3)primary key,bname varchar2(10),color
             varcha r2(10)); Table
     created.
     SQL> desc boats;
      Name          Null?                                        Type
     ----------------------------------------- -------- ----------------------------
     BID            NOT NULL                                      NUMBER(3)
     BNAME                                                       VARCHAR2(10)
     COLOR                                                       VARCHAR2(10)
     SQL> create table reserves(sid number(2) references sailors(sid),bid number(3)re ferences
                                                                 boats(bid),day date);
     Table created. SQL> desc reserves;
      Name Null?                                                 Type
     ----------------------------------------- -------- ----------------------------
     SID                                                          NUMBER(2)
     BID                                                          NUMBER(3)
     DAY                                              DATE
     Sid and bid in the above table are foreign keys which are referring from the tables sailors and
     boats.
 PL/SQL
  Basic Syntax of PL/SQL which is a block-structured language, this means that the PL/SQL
  programs are divided and written in logical blocks of code. Each block consists of three
  subparts
S.No                                          Sections & Description
 1
          Declarations
          This section starts with the keyword DECLARE. It is an optional section and defines
          all variables, cursors, subprograms, and other elements to be used in the program.
         Executable Commands
 2
         This section is enclosed between the keywords BEGIN and END and it is a
         mandatory section. It consists of the executable PL/SQL statements of the program.
         It should have at least one executable line of code, which may be just    a NULL
         command to indicate that nothing should be executed.
         Exception Handling
 3
         This section starts with the keyword EXCEPTION. This optional section contains
         exception(s) that handle errors in the program.
     Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other
     PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL
  DECLARE
  <declarations section>
  BEGIN
  <executable command(s)> EXCEPTION
  <exception handling> END;
  Hello World
The PL/SQL Identifiers
     PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved
     words. The identifiers consist of a letter optionally followed by more letters, numerals, dollar
     signs, underscores, and number signs and should not exceed 30 characters.
  By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent
     DECLARE
     message varchar2(20):= 'Hello, World!'; BEGIN
   dbms_output.put_line(message);
   END;
   /
Delimiter Description
        %             Attribute indicator
          '           Character string delimiter
          .           Component selector
              (,)     Expression or list delimiter
          :           Host variable indicator
          ,           Item separator
          "           Quoted identifier delimiter
          =           Relational operator
          ;           Statement terminator
              :=      Assignment operator
          =>          Association operator
              ||      Concatenation operator
              **      Exponentiation operator
       <<, >>         Label delimiter (begin and end)
               ..      Range operator
       <, >, <=, >=     Relational operators
   DECLARE
   -- variable declaration message varchar2(20):=
   'Hello, World!';
   BEGIN
   /*
   * PL/SQL executable statement(s)
   */ dbms_output.put_line(message);
   END;
   /
When the above code is executed at the SQL prompt, it produces the following result −
         Hello World
         PL/SQL procedure successfully completed.
   PL/SQL Program Units
         PL/SQL block
         Function
         Package
         Package body
         Procedure
         Trigger
         Type
         Type body
  Triggers:
        Trigger is invoked by Oracle engine automatically whenever a specified event occurs.
Trigger is stored into database and invoked repeatedly, when specific condition match. Triggers
are stored programs, which are automatically executed or fired when some event occurs.
       Classification based on the level o STATEMENT level Trigger: It fires one time for the
           specified event statement.
           o ROW level Trigger: It fires for each record that got affected in the specified
             event. (only for DML)
       Classification based on the Event
In a row level trigger, the trigger fires for each related row. And sometimes it is required to know
the value before and after the DML statement.
Oracle has provided two clauses in the RECORD-level trigger to hold these values. We can use
these clauses to refer to the old and new values inside the trigger body.
         :NEW – It holds a new value for the columns of the base table/view during the trigger
          execution
         :OLD – It holds old value of the columns of the base table/view during the trigger
          execution
      INSERT                            UPDATE                    DELETE
      : NEW                               VALID                    VALID
      : OLD                            INVALID
  Try to create a trigger using FOR EACH STATEMENT (not in oracle) create or replace
   trigger for_each_statement after insert or update or delete on client_master for each
   statement begin delete from aa; end;
   /
   It will give the following error:
   for each statement
   * ERROR at line 3:
   ORA-01912: ROW keyword expected
   If we use ROW in place of STATEMENT then
   create or replace trigger for_each_statement after insert or update or delete on client_master
   for each row begin delete from aa;
   6*
   end;
   SQL> /
  Trigger created.
  SQL> select *from aa;
  X              Y
  ---------- ----------
  12             jjjjjj
Active Database:
   A database that has the ability to spontaneously react to events occurring inside as well as
  outside the system is called active database. The ability to respond to external events is
  called—active behaviour. The active behaviour is based on the rules that—integrate a event
  with the desired effect. This behaviour is commonly defined in terms of ECA—rules allowing
  system to react to specific events.
Active Rules:
       •   The active behavior is achieved through theθ production rules/ active rules.
       •   The active rules are stored programs called triggers that are fired when an event
           occurs.
       •   Triggers are written to respond to DML(select,θ insert etc), DDL( create, alter etc) and
           Database Operations( Log-On, Log-Off )
       •   These triggers can be defined on table/view orθ the database to which event is
           associated.