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)

Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
 
Sql – Structured Query Language
Sql – Structured Query LanguageSql – Structured Query Language
Sql – Structured Query Language
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
Sql server ___________data control language
Sql server  ___________data control languageSql server  ___________data control language
Sql server ___________data control language
 
database language ppt.pptx
database language ppt.pptxdatabase language ppt.pptx
database language ppt.pptx
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Joins And Its Types
Joins And Its TypesJoins And Its Types
Joins And Its Types
 
SQL Queries - DDL Commands
SQL Queries - DDL CommandsSQL Queries - DDL Commands
SQL Queries - DDL Commands
 
SQL DDL
SQL DDLSQL DDL
SQL DDL
 
All data models in dbms
All data models in dbmsAll data models in dbms
All data models in dbms
 
Nested queries in database
Nested queries in databaseNested queries in database
Nested queries in database
 
joins in database
 joins in database joins in database
joins in database
 
Relational algebra in dbms
Relational algebra in dbmsRelational algebra in dbms
Relational algebra in dbms
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
SQL
SQLSQL
SQL
 

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
 

Viewers also liked (20)

MS Sql Server: Creating Views
MS Sql Server: Creating ViewsMS Sql Server: Creating Views
MS Sql Server: Creating Views
 
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
 

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

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
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
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
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Recently uploaded (20)

TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
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
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
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
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

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