SlideShare a Scribd company logo
2
Most read
3
Most read
4
Most read
SQL – Ch 13 – SQL VIEWS

                                           13. SQL - VIEWS
1   What is a view?
    1. A view is a derived table. A view does not store any rows itself. It can combine data from many tables to
       make a ‘virtual’ table. The actual table on which a view is based is called the ‘base table’.
    2. Views are useful for presenting data in different ways to different users. This saves typing in the common
       queries.
    3. A view is not a snapshot of the data returned by a particular query. A view is a copy of the SELECT
       statement itself.
    4. Every time we access a view. The query on which the view is based is run, and the data currently in the
       base tables is returned.

2   What are the advantages of a view?
    1. Security: Each user can be given permission to access the database only through a set of views. This
       restricts the user's access to stored data.
    2. Convenience: A view can take data from many tables and show it as a single table; this converts multi-
       table queries into single-table queries.
    3. Structural simplicity: The user can have a "personalized" view of the database.
    4. No changes in output as seen by user: A view can present an unchanged image of the database,
       even if the source tables are split, restructured, or renamed.
    5. Data integrity: If data is accessed and entered through a view, the DBMS can automatically check the
       data to ensure that it meets specified integrity constraints.
    6. Restricting data available to users: If we want to provide access to some small part of data store in a
       table, a view is useful.

3   What are the disadvantages of a view?
    1. Performance: If a view is defined by a complex, multi-table query, then even a simple query against the
       view becomes a complicated join, and it may take a long time to complete.
    2. Update restrictions: When a user tries to update rows of a view, the DBMS must translate the request
       into an update on rows of the underlying source tables. This is possible for simple views, but more
       complex views cannot be updated.

4   Creating a View
    The CREATE VIEW statement is used to create a view.

    Syntax:
    CREATE VIEW viewname

    •   Assign a name to each column in the view. If a list of column names is specified, it must have the
        same number of items as the number of columns in the query.
    •   Only the column names are specified; we should not give the other characteristics of columns.
    •   If the list of column names is omitted from the CREATE VIEW statement, each column in the
        view takes the name of the corresponding column in the query.
    •   The list of column names must be specified if the query includes calculated columns or if it
        produces two columns with identical names.

    Horizontal View:

    Example:
    CREATE VIEW PASSED AS
    SELECT *
    FROM STUDENTS
    WHERE RESULT = ‘P’

    A horizontal view will restrict the user’s access to only a few rows of the table. A “horizontal view” will permit
    a user to see only the records of those who have passed. A horizontal view slices the table horizontally to create
    the view. All columns are included in the view but only some of the rows are displayed.
Prof. Mukesh N. Tekwani [9869 488 356]                                                                       Page 1
SQL - Ch 13 – SQL VIEWS

     Example 2:
     Define a view for Sue (employee number 102) containing only orders placed by customers assigned
     to her.

     CREATE VIEW SUEORDERS AS
     SELECT *
     FROM ORDERS
     WHERE CUST IN
     (SELECT CUST_NUM FROM CUSTOMERS WHERE CUST_REP = 102)

     Vertical View:
     A vertical view restricts a user’s access to only certain columns of a table.

     Example 1:
     CREATE VIEW STUD_ADDRESS AS
     SELECT ROLLNO, NAME, ADD1, ADD2, CITY
     FROM STUDENTS

     Row/Column Subset View:
     This type of view is a combination of horizontal and vertical views. It will display a few selected rows
     satisfying the condition in the WHERE clause, and a few selected columns.

     Example:
     CREATE VIEW STUD_PASSED AS
     SELECT ROLLNO, NAME, PCTG
     FROM STUDENTS
     WHERE RESULT = ‘P’

     Grouped View:
     A grouped view is one in which a query includes the GROUP BY clause. Related rows of data are grouped
     together and produce one row of result for each group.

     Define a view that contains summary order data for each salesperson.
     CREATE VIEW ORD_BY_REP (WHO, HOW_MANY, TOTAL, LOW, HIGH, AVERAGE)
     AS
     SELECT REP, COUNT(*), SUM(AMOUNT), MIN(AMOUNT), MAX(AMOUNT), AVG(AMOUNT)
     FROM ORDERS
     GROUP BY REP

5    Examples of CREATE VIEW
a)   Create a view to print names of all movies in capital letters.
     CREATE VIEW Movies_upper(title)
     AS
     SELECT UPPER(movie_title)
     FROM Movies

b)   Create a view to find the total revenue from all movies.
     CREATE VIEW TRev (total_revenue)
     AS
     SELECT SUM(gross)
     FROM Movies

c)   Create a view to find all people who live in a state where a movie studio is located.
     CREATE VIEW PS
     AS
     SELECT FName, LName, StudioName, Person_State
     FROM People, Studio
     WHERE Person_State = Studio_State

Page 2                                                                               mukeshtekwani@hotmail.com
SQL – Ch 13 – SQL VIEWS


 d)   This is an example of a view with a sub-query.
      Create a view that returns the list of all the studios with an average budget of over $50 million.
      CREATE VIEW Big_Movies
      AS
      SELECT movie_title, budget, gross
      FROM Movies
      WHERE studio_id IN
      (SELECT studio_id
      FROM Movies
      GROUP BY studio_id
      HAVING AVG(budget) > 50)

6     Updating a View
      Records can be updated, inserted, and deleted though views. Views against which INSERT,
      DELETE, and UPDATE statements can be used are called as updateable views.

      The following conditions must be fulfilled for view updates:
      1. Each row in the view must map to a single row in the base table.that are used in the view.
      2. Aggregate functions, the DISTINCT operator, GROUP BY clause and HAVING clause cannot be
         used in updateable views.
      3. The WHERE clause cannot include a sub-query.
      4. The VIEW must have a single source table
      5. Calculated columns cannot be use in view updates.
      6. Updating a view is actually updating the underlying (base) table – i.e. the table mentioned in the
         SELECT clause.
      7. But it may happen that even though the base table is updated, the new record does not show up
         in the view due to the nature of the view.

7     Explain the CHECK OPTION for VIEW updates.
      If a view is defined by a query that includes a WHERE clause, only rows that meet the search
      condition are visible in the view. Other rows may be present in the source table(s) from which the
      view is derived, but they are not visible through the view.

      For example, consider the EASTREPS view contains which only few rows of the SALESREPS table:

      CREATE VIEW EASTREPS AS
      SELECT *
      FROM SALESREPS
      WHERE REP_OFFICE IN (11, 12, 13)

      We can add a new record with this updateable view:

      INSERT INTO EASTREPS (EMPL_NUM, NAME, REP_OFFICE, AGE, SALES)
      VALUES (113, 'Jake', 11, 43, 0.00)

      The DBMS will add the new row to the underlying SALESREPS table, and the row will be visible
      through the EASTREPS view. The row we are trying to insert satisfies the condition that the
      REP_OFFICE should be 11, 12, or 13.

      But suppose we add a new salesperson with this INSERT statement:

      INSERT INTO EASTREPS (EMPL_NUM, NAME, REP_OFFICE, AGE, SALES)
      VALUES (114, 'Fred’, 21, 47, 0.00)

      Here the REP_OFFICE is 21. The row in inserted into the underlying table, but it is not displayed by
      the view.


Prof. Mukesh N. Tekwani [9869 488 356]                                                             Page 3
SQL - Ch 13 – SQL VIEWS

    This can cause problems with data integrity. To avoid such problems (table updated but record not
    displayed by view), SQL provides the CHECK OPTION as follows:

    CREATE VIEW EASTREPS AS
    SELECT *
    FROM SALESREPS
    WHERE REP_OFFICE IN (11, 12, 13)
    WITH CHECK OPTION

    Now, if we try to use an update view, SQL will automatically check each UPDATE and INSERT query
    to make sure that the resultant query meets the condition “REP_OFFICE IN (11, 12, 13)”.

    CASCADED and LOCAL options
    When a new view is created it may be based on another view, and not on a table. E.g., a view VC may be based
    on view VB, which in turn is based on view VA. We say that there is a hierarchy of views with VA being at
    the highest level, than VB and finally VC.

    If the new view VC is created WITH CASCADED CHECK OPTION, and we attempt to update the
    view, it causes the DBMS go to view VB and then VA to check option for each view.

    If the new view is created WITH LOCAL CHECK OPTION, then the DBMS checks only that view; the
    underlying views are not checked. So if we define view VC with LOCAL CHECK OPTION, then only
    conditions specified in that view are checked.

8   Dropping a View – CASCADE and RESTRICT options
    When a view is no longer needed, it can be removed by using the DROP VIEW statement. We can
    also control what happens when a view is dropped and another view depends on its definition.

    E.g., consider that we have view VA and VB. View VB depends on VA.

    We give the query

    DROP VIEW VA

    If we drop VA, then cascading effect takes place and view VB is also dropped. Thus the default
    option for dropping a view is CASCADE. The CASCADE option tells the DBMS to delete not only the
    named view, but also any views that depend on its definition.

    But if we give the query

    DROP VIEW VA RESTRICT

    Now the query fails because RESTRICT option tells the DBMS to remove the view only if no other
    views depend on it. Since VB depends on VA, it will cause an error.




Page 4                                                                         mukeshtekwani@hotmail.com

More Related Content

What's hot (20)

PDF
Oracle PL/SQL online training | PL/SQL online Training
suresh
 
PDF
Managing users & tables using Oracle Enterprise Manage
NR Computer Learning Center
 
PPTX
Synchronization Pradeep K Sinha
Jawwad Rafiq
 
PPTX
Logical Replication in PostgreSQL
EDB
 
PPTX
Sql and Sql commands
Knowledge Center Computer
 
PPTX
User defined Function in SQL
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
PostgreSQL.pptx
MAYURUGALE6
 
PDF
PostgreSql query planning and tuning
Federico Campoli
 
PDF
SQL JOINS
Swapnali Pawar
 
PPTX
Database constraints
Khadija Parween
 
PPTX
The oracle database architecture
Akash Pramanik
 
ODP
PostgreSQL Administration for System Administrators
Command Prompt., Inc
 
PDF
Understanding and controlling transaction logs
Red Gate Software
 
PDF
Alphorm.com Formation Oracle 12c DBA2 : Installation et mise à niveau
Alphorm
 
PDF
CV - Database Administrator ( French )
Franck VICTORIA
 
PPSX
Oracle Performance Tuning Fundamentals
Carlos Sierra
 
PDF
Introduction VAUUM, Freezing, XID wraparound
Masahiko Sawada
 
PPT
User Interface Design Chapter 2 Galiz
Latesh Malik
 
PPT
PLSQL Cursors
spin_naresh
 
PDF
SQL Joins With Examples | Edureka
Edureka!
 
Oracle PL/SQL online training | PL/SQL online Training
suresh
 
Managing users & tables using Oracle Enterprise Manage
NR Computer Learning Center
 
Synchronization Pradeep K Sinha
Jawwad Rafiq
 
Logical Replication in PostgreSQL
EDB
 
Sql and Sql commands
Knowledge Center Computer
 
PostgreSQL.pptx
MAYURUGALE6
 
PostgreSql query planning and tuning
Federico Campoli
 
SQL JOINS
Swapnali Pawar
 
Database constraints
Khadija Parween
 
The oracle database architecture
Akash Pramanik
 
PostgreSQL Administration for System Administrators
Command Prompt., Inc
 
Understanding and controlling transaction logs
Red Gate Software
 
Alphorm.com Formation Oracle 12c DBA2 : Installation et mise à niveau
Alphorm
 
CV - Database Administrator ( French )
Franck VICTORIA
 
Oracle Performance Tuning Fundamentals
Carlos Sierra
 
Introduction VAUUM, Freezing, XID wraparound
Masahiko Sawada
 
User Interface Design Chapter 2 Galiz
Latesh Malik
 
PLSQL Cursors
spin_naresh
 
SQL Joins With Examples | Edureka
Edureka!
 

Viewers also liked (20)

PPTX
MS Sql Server: Creating Views
DataminingTools Inc
 
PPT
Chapter09
sasa_eldoby
 
DOCX
outreach email
Sean Randall
 
PPT
Alfaparf resalta tu belleza capilar
fiorechag
 
PPTX
Filosofia cideb agosto 2012
vanne-rubio
 
PPTX
La iniciativa MOOC de la Universitat Politècnica de València
Ignacio Despujol Zabala
 
PPT
Tema 2.3. Dimensiones y crecimiento de Internet (Internet y World Wide Web)In...
DAVID CARABANTES ALARCÓN (UNIVERSIDAD COMPLUTENSE DE MADRID)
 
DOCX
sistemas de produccion
Laura Benavides
 
PPTX
Protocolo tc pultimate presentacion1
Bienvenido Baez Rodriguez
 
PPTX
Sokol arvay daniel oliver cfc unidad 2 actividad 1
Daniel Sokol
 
PPS
LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )
Daniel Soto Rebollo
 
PPTX
Vitiligo
RMZ14
 
PDF
Aprovechamiento de los subproductos citrícolas
Melany Pelaez
 
PDF
Ati recien nacido
mdio
 
PDF
Catálogo Ingenierías procesos químicos
Grupo Edutecno
 
PDF
Islam para-ninos
Helmon Chan
 
PPTX
PROYECTO LAN
kellygomezxx
 
PPT
Integradora 1
Arturo Paniagua
 
PPT
Las Flores Y El Significado De Sus Nombres Iii Parte
henrymom
 
MS Sql Server: Creating Views
DataminingTools Inc
 
Chapter09
sasa_eldoby
 
outreach email
Sean Randall
 
Alfaparf resalta tu belleza capilar
fiorechag
 
Filosofia cideb agosto 2012
vanne-rubio
 
La iniciativa MOOC de la Universitat Politècnica de València
Ignacio Despujol Zabala
 
Tema 2.3. Dimensiones y crecimiento de Internet (Internet y World Wide Web)In...
DAVID CARABANTES ALARCÓN (UNIVERSIDAD COMPLUTENSE DE MADRID)
 
sistemas de produccion
Laura Benavides
 
Protocolo tc pultimate presentacion1
Bienvenido Baez Rodriguez
 
Sokol arvay daniel oliver cfc unidad 2 actividad 1
Daniel Sokol
 
LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )
Daniel Soto Rebollo
 
Vitiligo
RMZ14
 
Aprovechamiento de los subproductos citrícolas
Melany Pelaez
 
Ati recien nacido
mdio
 
Catálogo Ingenierías procesos químicos
Grupo Edutecno
 
Islam para-ninos
Helmon Chan
 
PROYECTO LAN
kellygomezxx
 
Integradora 1
Arturo Paniagua
 
Las Flores Y El Significado De Sus Nombres Iii Parte
henrymom
 
Ad

Similar to Sql ch 13 - sql-views (20)

PPTX
Designing and Creating Views, Inline Functions, and Synonyms
Tayba Farooqui
 
PPT
Views
Rahul Gupta
 
PPTX
Oracle Database View
Eryk Budi Pratama
 
PPT
Module05
Sridhar P
 
PDF
Sql viwes
Huda Alameen
 
PDF
RDBMS Lecture Notes Unit4 chapter12 VIEW
Murugan Solaiyappan
 
PPTX
View
Pooja Dixit
 
PPTX
L6 views
Rushdi Shams
 
PPT
chap 9 dbms.ppt
arjun431527
 
PPTX
View
LakshmiSamivel
 
PPT
Oracle view
Madhavendra Dutt
 
PPTX
SQL lab number 10 in database system ppt
MUHAMMADANSAR76
 
PDF
Implementing views
sqlschoolgr
 
PPTX
MS SQL SERVER: Creating Views
sqlserver content
 
PPTX
MS SQLSERVER:Creating Views
sqlserver content
 
PPTX
Sql server ___________session_16(views)
Ehtisham Ali
 
Designing and Creating Views, Inline Functions, and Synonyms
Tayba Farooqui
 
Oracle Database View
Eryk Budi Pratama
 
Module05
Sridhar P
 
Sql viwes
Huda Alameen
 
RDBMS Lecture Notes Unit4 chapter12 VIEW
Murugan Solaiyappan
 
L6 views
Rushdi Shams
 
chap 9 dbms.ppt
arjun431527
 
Oracle view
Madhavendra Dutt
 
SQL lab number 10 in database system ppt
MUHAMMADANSAR76
 
Implementing views
sqlschoolgr
 
MS SQL SERVER: Creating Views
sqlserver content
 
MS SQLSERVER:Creating Views
sqlserver content
 
Sql server ___________session_16(views)
Ehtisham Ali
 
Ad

More from Mukesh Tekwani (20)

PDF
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
 
PPSX
Circular motion
Mukesh Tekwani
 
PPSX
Gravitation
Mukesh Tekwani
 
PDF
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
 
PPTX
Hexadecimal to binary conversion
Mukesh Tekwani
 
PPTX
Hexadecimal to decimal conversion
Mukesh Tekwani
 
PPTX
Hexadecimal to octal conversion
Mukesh Tekwani
 
PPTX
Gray code to binary conversion
Mukesh Tekwani
 
PPTX
What is Gray Code?
Mukesh Tekwani
 
PPSX
Decimal to Binary conversion
Mukesh Tekwani
 
PDF
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
 
PDF
Refraction and dispersion of light through a prism
Mukesh Tekwani
 
PDF
Refraction of light at a plane surface
Mukesh Tekwani
 
PDF
Spherical mirrors
Mukesh Tekwani
 
PDF
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
 
PDF
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
 
PDF
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
 
PPSX
Cyber Laws
Mukesh Tekwani
 
PPSX
Social media
Mukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
Mukesh Tekwani
 
Circular motion
Mukesh Tekwani
 
Gravitation
Mukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
Mukesh Tekwani
 
Hexadecimal to binary conversion
Mukesh Tekwani
 
Hexadecimal to decimal conversion
Mukesh Tekwani
 
Hexadecimal to octal conversion
Mukesh Tekwani
 
Gray code to binary conversion
Mukesh Tekwani
 
What is Gray Code?
Mukesh Tekwani
 
Decimal to Binary conversion
Mukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Mukesh Tekwani
 
Refraction of light at a plane surface
Mukesh Tekwani
 
Spherical mirrors
Mukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Mukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Mukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
Mukesh Tekwani
 
Cyber Laws
Mukesh Tekwani
 
Social media
Mukesh Tekwani
 

Recently uploaded (20)

PPTX
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
Mathematics 5 - Time Measurement: Time Zone
menchreo
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPTX
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
PPTX
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
THE TAME BIRD AND THE FREE BIRD.pptxxxxx
MarcChristianNicolas
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Mathematics 5 - Time Measurement: Time Zone
menchreo
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
community health nursing question paper 2.pdf
Prince kumar
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Soil and agriculture microbiology .pptx
Keerthana Ramesh
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 

Sql ch 13 - sql-views

  • 1. SQL – Ch 13 – SQL VIEWS 13. SQL - VIEWS 1 What is a view? 1. A view is a derived table. A view does not store any rows itself. It can combine data from many tables to make a ‘virtual’ table. The actual table on which a view is based is called the ‘base table’. 2. Views are useful for presenting data in different ways to different users. This saves typing in the common queries. 3. A view is not a snapshot of the data returned by a particular query. A view is a copy of the SELECT statement itself. 4. Every time we access a view. The query on which the view is based is run, and the data currently in the base tables is returned. 2 What are the advantages of a view? 1. Security: Each user can be given permission to access the database only through a set of views. This restricts the user's access to stored data. 2. Convenience: A view can take data from many tables and show it as a single table; this converts multi- table queries into single-table queries. 3. Structural simplicity: The user can have a "personalized" view of the database. 4. No changes in output as seen by user: A view can present an unchanged image of the database, even if the source tables are split, restructured, or renamed. 5. Data integrity: If data is accessed and entered through a view, the DBMS can automatically check the data to ensure that it meets specified integrity constraints. 6. Restricting data available to users: If we want to provide access to some small part of data store in a table, a view is useful. 3 What are the disadvantages of a view? 1. Performance: If a view is defined by a complex, multi-table query, then even a simple query against the view becomes a complicated join, and it may take a long time to complete. 2. Update restrictions: When a user tries to update rows of a view, the DBMS must translate the request into an update on rows of the underlying source tables. This is possible for simple views, but more complex views cannot be updated. 4 Creating a View The CREATE VIEW statement is used to create a view. Syntax: CREATE VIEW viewname • Assign a name to each column in the view. If a list of column names is specified, it must have the same number of items as the number of columns in the query. • Only the column names are specified; we should not give the other characteristics of columns. • If the list of column names is omitted from the CREATE VIEW statement, each column in the view takes the name of the corresponding column in the query. • The list of column names must be specified if the query includes calculated columns or if it produces two columns with identical names. Horizontal View: Example: CREATE VIEW PASSED AS SELECT * FROM STUDENTS WHERE RESULT = ‘P’ A horizontal view will restrict the user’s access to only a few rows of the table. A “horizontal view” will permit a user to see only the records of those who have passed. A horizontal view slices the table horizontally to create the view. All columns are included in the view but only some of the rows are displayed. Prof. Mukesh N. Tekwani [9869 488 356] Page 1
  • 2. SQL - Ch 13 – SQL VIEWS Example 2: Define a view for Sue (employee number 102) containing only orders placed by customers assigned to her. CREATE VIEW SUEORDERS AS SELECT * FROM ORDERS WHERE CUST IN (SELECT CUST_NUM FROM CUSTOMERS WHERE CUST_REP = 102) Vertical View: A vertical view restricts a user’s access to only certain columns of a table. Example 1: CREATE VIEW STUD_ADDRESS AS SELECT ROLLNO, NAME, ADD1, ADD2, CITY FROM STUDENTS Row/Column Subset View: This type of view is a combination of horizontal and vertical views. It will display a few selected rows satisfying the condition in the WHERE clause, and a few selected columns. Example: CREATE VIEW STUD_PASSED AS SELECT ROLLNO, NAME, PCTG FROM STUDENTS WHERE RESULT = ‘P’ Grouped View: A grouped view is one in which a query includes the GROUP BY clause. Related rows of data are grouped together and produce one row of result for each group. Define a view that contains summary order data for each salesperson. CREATE VIEW ORD_BY_REP (WHO, HOW_MANY, TOTAL, LOW, HIGH, AVERAGE) AS SELECT REP, COUNT(*), SUM(AMOUNT), MIN(AMOUNT), MAX(AMOUNT), AVG(AMOUNT) FROM ORDERS GROUP BY REP 5 Examples of CREATE VIEW a) Create a view to print names of all movies in capital letters. CREATE VIEW Movies_upper(title) AS SELECT UPPER(movie_title) FROM Movies b) Create a view to find the total revenue from all movies. CREATE VIEW TRev (total_revenue) AS SELECT SUM(gross) FROM Movies c) Create a view to find all people who live in a state where a movie studio is located. CREATE VIEW PS AS SELECT FName, LName, StudioName, Person_State FROM People, Studio WHERE Person_State = Studio_State Page 2 [email protected]
  • 3. SQL – Ch 13 – SQL VIEWS d) This is an example of a view with a sub-query. Create a view that returns the list of all the studios with an average budget of over $50 million. CREATE VIEW Big_Movies AS SELECT movie_title, budget, gross FROM Movies WHERE studio_id IN (SELECT studio_id FROM Movies GROUP BY studio_id HAVING AVG(budget) > 50) 6 Updating a View Records can be updated, inserted, and deleted though views. Views against which INSERT, DELETE, and UPDATE statements can be used are called as updateable views. The following conditions must be fulfilled for view updates: 1. Each row in the view must map to a single row in the base table.that are used in the view. 2. Aggregate functions, the DISTINCT operator, GROUP BY clause and HAVING clause cannot be used in updateable views. 3. The WHERE clause cannot include a sub-query. 4. The VIEW must have a single source table 5. Calculated columns cannot be use in view updates. 6. Updating a view is actually updating the underlying (base) table – i.e. the table mentioned in the SELECT clause. 7. But it may happen that even though the base table is updated, the new record does not show up in the view due to the nature of the view. 7 Explain the CHECK OPTION for VIEW updates. If a view is defined by a query that includes a WHERE clause, only rows that meet the search condition are visible in the view. Other rows may be present in the source table(s) from which the view is derived, but they are not visible through the view. For example, consider the EASTREPS view contains which only few rows of the SALESREPS table: CREATE VIEW EASTREPS AS SELECT * FROM SALESREPS WHERE REP_OFFICE IN (11, 12, 13) We can add a new record with this updateable view: INSERT INTO EASTREPS (EMPL_NUM, NAME, REP_OFFICE, AGE, SALES) VALUES (113, 'Jake', 11, 43, 0.00) The DBMS will add the new row to the underlying SALESREPS table, and the row will be visible through the EASTREPS view. The row we are trying to insert satisfies the condition that the REP_OFFICE should be 11, 12, or 13. But suppose we add a new salesperson with this INSERT statement: INSERT INTO EASTREPS (EMPL_NUM, NAME, REP_OFFICE, AGE, SALES) VALUES (114, 'Fred’, 21, 47, 0.00) Here the REP_OFFICE is 21. The row in inserted into the underlying table, but it is not displayed by the view. Prof. Mukesh N. Tekwani [9869 488 356] Page 3
  • 4. SQL - Ch 13 – SQL VIEWS This can cause problems with data integrity. To avoid such problems (table updated but record not displayed by view), SQL provides the CHECK OPTION as follows: CREATE VIEW EASTREPS AS SELECT * FROM SALESREPS WHERE REP_OFFICE IN (11, 12, 13) WITH CHECK OPTION Now, if we try to use an update view, SQL will automatically check each UPDATE and INSERT query to make sure that the resultant query meets the condition “REP_OFFICE IN (11, 12, 13)”. CASCADED and LOCAL options When a new view is created it may be based on another view, and not on a table. E.g., a view VC may be based on view VB, which in turn is based on view VA. We say that there is a hierarchy of views with VA being at the highest level, than VB and finally VC. If the new view VC is created WITH CASCADED CHECK OPTION, and we attempt to update the view, it causes the DBMS go to view VB and then VA to check option for each view. If the new view is created WITH LOCAL CHECK OPTION, then the DBMS checks only that view; the underlying views are not checked. So if we define view VC with LOCAL CHECK OPTION, then only conditions specified in that view are checked. 8 Dropping a View – CASCADE and RESTRICT options When a view is no longer needed, it can be removed by using the DROP VIEW statement. We can also control what happens when a view is dropped and another view depends on its definition. E.g., consider that we have view VA and VB. View VB depends on VA. We give the query DROP VIEW VA If we drop VA, then cascading effect takes place and view VB is also dropped. Thus the default option for dropping a view is CASCADE. The CASCADE option tells the DBMS to delete not only the named view, but also any views that depend on its definition. But if we give the query DROP VIEW VA RESTRICT Now the query fails because RESTRICT option tells the DBMS to remove the view only if no other views depend on it. Since VB depends on VA, it will cause an error. Page 4 [email protected]