SlideShare a Scribd company logo
1 of 4
Download to read offline
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)

MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
MS Sql Server: Creating Views
MS Sql Server: Creating ViewsMS Sql Server: Creating Views
MS Sql Server: Creating Views
 
Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Using the set operators
Using the set operatorsUsing the set operators
Using the set operators
 
Sql subquery
Sql  subquerySql  subquery
Sql subquery
 
Oracle Index
Oracle IndexOracle Index
Oracle Index
 
Mysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sqlMysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sql
 
Relational data model
Relational data modelRelational data model
Relational data model
 
Sql joins
Sql joinsSql joins
Sql joins
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
SQL Differences SQL Interview Questions
SQL Differences  SQL Interview QuestionsSQL Differences  SQL Interview Questions
SQL Differences SQL Interview Questions
 
Including Constraints -Oracle Data base
Including Constraints -Oracle Data base Including Constraints -Oracle Data base
Including Constraints -Oracle Data base
 
Stored-Procedures-Presentation
Stored-Procedures-PresentationStored-Procedures-Presentation
Stored-Procedures-Presentation
 
Index in sql server
Index in sql serverIndex in sql server
Index in sql server
 
Sql server ___________session_17(indexes)
Sql server  ___________session_17(indexes)Sql server  ___________session_17(indexes)
Sql server ___________session_17(indexes)
 
SQL JOINS
SQL JOINSSQL JOINS
SQL JOINS
 
SQL select statement and functions
SQL select statement and functionsSQL select statement and functions
SQL select statement and functions
 
Sql wksht-1
Sql wksht-1Sql wksht-1
Sql wksht-1
 
SQL Views
SQL ViewsSQL Views
SQL Views
 

Viewers also liked

Alfaparf resalta tu belleza capilar
Alfaparf   resalta tu belleza capilarAlfaparf   resalta tu belleza capilar
Alfaparf resalta tu belleza capilarfiorechag
 
Filosofia cideb agosto 2012
Filosofia cideb agosto 2012Filosofia cideb agosto 2012
Filosofia cideb agosto 2012vanne-rubio
 
La iniciativa MOOC de la Universitat Politècnica de València
La iniciativa MOOC de la Universitat Politècnica de ValènciaLa iniciativa MOOC de la Universitat Politècnica de València
La iniciativa MOOC de la Universitat Politècnica de ValènciaIgnacio Despujol Zabala
 
Sokol arvay daniel oliver cfc unidad 2 actividad 1
Sokol arvay daniel oliver cfc unidad 2 actividad 1Sokol arvay daniel oliver cfc unidad 2 actividad 1
Sokol arvay daniel oliver cfc unidad 2 actividad 1Daniel Sokol
 
LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )
LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )
LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )Daniel Soto Rebollo
 
Vitiligo
VitiligoVitiligo
VitiligoRMZ14
 
Aprovechamiento de los subproductos citrícolas
Aprovechamiento de los subproductos citrícolasAprovechamiento de los subproductos citrícolas
Aprovechamiento de los subproductos citrícolasMelany Pelaez
 
Ati recien nacido
Ati recien nacidoAti recien nacido
Ati recien nacidomdio
 
Catálogo Ingenierías procesos químicos
Catálogo Ingenierías procesos químicosCatálogo Ingenierías procesos químicos
Catálogo Ingenierías procesos químicosGrupo Edutecno
 
Islam para-ninos
Islam para-ninosIslam para-ninos
Islam para-ninosHelmon Chan
 
Las Flores Y El Significado De Sus Nombres Iii Parte
Las Flores Y El Significado De Sus Nombres  Iii ParteLas Flores Y El Significado De Sus Nombres  Iii Parte
Las Flores Y El Significado De Sus Nombres Iii Partehenrymom
 
Isilog solution itsm
Isilog solution itsmIsilog solution itsm
Isilog solution itsmISILOG
 
Cristo Viene
Cristo VieneCristo Viene
Cristo VieneLuis Kun
 

Viewers also liked (20)

Chapter09
Chapter09Chapter09
Chapter09
 
outreach email
outreach emailoutreach email
outreach email
 
Alfaparf resalta tu belleza capilar
Alfaparf   resalta tu belleza capilarAlfaparf   resalta tu belleza capilar
Alfaparf resalta tu belleza capilar
 
Filosofia cideb agosto 2012
Filosofia cideb agosto 2012Filosofia cideb agosto 2012
Filosofia cideb agosto 2012
 
La iniciativa MOOC de la Universitat Politècnica de València
La iniciativa MOOC de la Universitat Politècnica de ValènciaLa iniciativa MOOC de la Universitat Politècnica de València
La iniciativa MOOC de la Universitat Politècnica de València
 
Tema 2.3. Dimensiones y crecimiento de Internet (Internet y World Wide Web)In...
Tema 2.3. Dimensiones y crecimiento de Internet (Internet y World Wide Web)In...Tema 2.3. Dimensiones y crecimiento de Internet (Internet y World Wide Web)In...
Tema 2.3. Dimensiones y crecimiento de Internet (Internet y World Wide Web)In...
 
sistemas de produccion
sistemas de produccionsistemas de produccion
sistemas de produccion
 
Protocolo tc pultimate presentacion1
Protocolo tc pultimate presentacion1Protocolo tc pultimate presentacion1
Protocolo tc pultimate presentacion1
 
Sokol arvay daniel oliver cfc unidad 2 actividad 1
Sokol arvay daniel oliver cfc unidad 2 actividad 1Sokol arvay daniel oliver cfc unidad 2 actividad 1
Sokol arvay daniel oliver cfc unidad 2 actividad 1
 
LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )
LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )
LA AVENTURA DEL MISTERIO ( EL VIEJO BELCHITE )
 
Vitiligo
VitiligoVitiligo
Vitiligo
 
Aprovechamiento de los subproductos citrícolas
Aprovechamiento de los subproductos citrícolasAprovechamiento de los subproductos citrícolas
Aprovechamiento de los subproductos citrícolas
 
Ati recien nacido
Ati recien nacidoAti recien nacido
Ati recien nacido
 
Catálogo Ingenierías procesos químicos
Catálogo Ingenierías procesos químicosCatálogo Ingenierías procesos químicos
Catálogo Ingenierías procesos químicos
 
Islam para-ninos
Islam para-ninosIslam para-ninos
Islam para-ninos
 
PROYECTO LAN
PROYECTO LANPROYECTO LAN
PROYECTO LAN
 
Integradora 1
Integradora 1 Integradora 1
Integradora 1
 
Las Flores Y El Significado De Sus Nombres Iii Parte
Las Flores Y El Significado De Sus Nombres  Iii ParteLas Flores Y El Significado De Sus Nombres  Iii Parte
Las Flores Y El Significado De Sus Nombres Iii Parte
 
Isilog solution itsm
Isilog solution itsmIsilog solution itsm
Isilog solution itsm
 
Cristo Viene
Cristo VieneCristo Viene
Cristo Viene
 

Similar to SQL Views in a Nutshell

Similar to SQL Views in a Nutshell (20)

Designing and Creating Views, Inline Functions, and Synonyms
 Designing and Creating Views, Inline Functions, and Synonyms Designing and Creating Views, Inline Functions, and Synonyms
Designing and Creating Views, Inline Functions, and Synonyms
 
View
ViewView
View
 
Sql viwes
Sql viwesSql viwes
Sql viwes
 
Sql server ___________session_16(views)
Sql server  ___________session_16(views)Sql server  ___________session_16(views)
Sql server ___________session_16(views)
 
Module05
Module05Module05
Module05
 
Oracle view
Oracle viewOracle view
Oracle view
 
Les11
Les11Les11
Les11
 
Les10
Les10Les10
Les10
 
chap 9 dbms.ppt
chap 9 dbms.pptchap 9 dbms.ppt
chap 9 dbms.ppt
 
foodmunch 2.pptx hdshid hdbfhdbfhkd vcn vbds
foodmunch 2.pptx hdshid hdbfhdbfhkd vcn  vbdsfoodmunch 2.pptx hdshid hdbfhdbfhkd vcn  vbds
foodmunch 2.pptx hdshid hdbfhdbfhkd vcn vbds
 
View
ViewView
View
 
Chapter 07 ddl_sql
Chapter 07 ddl_sqlChapter 07 ddl_sql
Chapter 07 ddl_sql
 
MS SQL SERVER: Creating Views
MS SQL SERVER: Creating ViewsMS SQL SERVER: Creating Views
MS SQL SERVER: Creating Views
 
MS SQLSERVER:Creating Views
MS SQLSERVER:Creating ViewsMS SQLSERVER:Creating Views
MS SQLSERVER:Creating Views
 
VIEWS.pptx
VIEWS.pptxVIEWS.pptx
VIEWS.pptx
 
Creating Views - oracle database
Creating Views - oracle databaseCreating Views - oracle database
Creating Views - oracle database
 
Creating other schema objects
Creating other schema objectsCreating other schema objects
Creating other schema objects
 
View
ViewView
View
 
Oracle Database View
Oracle Database ViewOracle Database View
Oracle Database View
 
Views
ViewsViews
Views
 

More from Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

More from Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

SQL Views in a Nutshell

  • 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 mukeshtekwani@hotmail.com
  • 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 mukeshtekwani@hotmail.com