Oracle – SQL 10g.

Slides:



Advertisements
Similar presentations
Oracle 10g & 11g for Dev Virtual Columns DML error logging
Advertisements

Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
SQL (DDL & DML Commands)
1 Information Retrieval and Use (IRU) CE An Introduction To SQL Part 1.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
Database Programming Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and Synonymns.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Chapter 13 Views Oracle 10g: SQL. Oracle 10g: SQL2 Objectives Create a view, using CREATE VIEW command or the CREATE OR REPLACE VIEW command Employ the.
Copyright  Oracle Corporation, All rights reserved. 12 Creating Views.
SQL/Lesson 7/Slide 1 of 32 Implementing Indexes Objectives In this lesson, you will learn to: * Create a clustered index * Create a nonclustered index.
Indexes- What?  Optional structures associated with tables  Provides a quick access path to table data  You can create indexes on one or more columns.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
 CONACT UC:  Magnific training   
Views / Session 3/ 1 of 40 Session 3 Module 5: Implementing Views Module 6: Managing Views.
LEC-8 SQL. Indexes The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading.
1 ORACLE I 3 – SQL 1 Salim Phone: YM: talim_bansal.
SQL IMPLEMENTATION & ADMINISTRATION Indexing & Views.
Fundamentals of DBMS Notes-1.
TABLES AND INDEXES Ashima Wadhwa.
Managing Tables, Data Integrity, Constraints by Adrienne Watt
Top 50 SQL Interview Questions & Answers
Including Constraints
Relational Database Design
Aggregating Data Using Group Functions
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
SQL Implementation & Administration
ATS Application Programming: Java Programming
PL/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-1
Subqueries.
Interacting with the Oracle Server
Displaying Data from Multiple Tables
Using the Set Operators
Displaying Data from Multiple Tables
Database Performance Tuning and Query Optimization
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
Using SQL*Plus.
Writing Correlated Subqueries
(SQL) Aggregating Data Using Group Functions
ORACLE SQL Developer & SQLPLUS Statements
Using the Set Operators
DATABASE MANAGEMENT SYSTEM
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
Chapter 4 Indexes.
CH 4 Indexes.
Chapter 2 Views.
Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
Chapter 7 Introduction to Structured Query Language (SQL)
CH 4 Indexes.
Chapter 2 Views.
Contents Preface I Introduction Lesson Objectives I-2
Chapter 8 Advanced SQL.
Chapter 11 Database Performance Tuning and Query Optimization
Database Systems: Design, Implementation, and Management Tenth Edition
IST 318 Database Administration
Displaying Data from Multiple Tables
Using the Set Operators
Displaying Data from Multiple Tables
Presentation transcript:

Oracle – SQL 10g

Views A view is an object that contains no data of its own Its a kind of table whose contents are taken from other tables through the execution of a query As the values in the base tables change, the changes are automatically reflected in the views Syntax: CREATE VIEW <viewname> AS <select query>; SQL> CREATE VIEW emp_vw AS SELECT empno, ename, job FROM emp; CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Views (Contd…) According to the ANSI standard, views are read-only if the CREATE VIEW statement contains: SET & DISTINCT operators A group function or computed columns or expressions A GROUP BY or HAVING clause References to more than one table, either through a join or a sub-query References to a non-updatable view Does not include NOT NULL column that does not have a DEFAULT clause CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Views (Contd…) Create a view containing all the employees in dept 20: SQL> CREATE VIEW emp_vw1 AS SELECT empno, ename, job FROM emp WHERE deptno = 20; To find out the base table on which view is dependent: SQL> SELECT * FROM user_views; CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Manipulating Views Inserting records in a view: INSERT INTO emp_vw1 VALUES ( 2222 , ‘POOJA’, ‘ANALYST’); Updating views: UPDATE emp_vw1 SET job = ‘MANAGER’ WHERE ename = ‘SMITH’; CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

VIEW WITH CHECK Option Create a view with columns deptno, job, average salary, sum of salaries for each job in each dept: CREATE VIEW emp_vw2 (deptno, job,avgsal, totsal) AS SELECT deptno, job,avg(sal), sum(sal) FROM emp GROUP BY deptno,job; With check option: Any insert or update of a row into the view is rejected if the row does not meet the view definition CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Views (Contd…) A view with the check option: SQL> CREATE VIEW emp_vw3 AS SELECT * FROM emp WHERE deptno = 20 WITH CHECK OPTION; The user can now enter values only for dept 20 To drop a view: SQL> DROP VIEW emp_vw3; CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Updatable Views Rules for Performing DML Operations on a View: Rows can’t be deleted from a view if they contain: Group functions A GROUP BY clause The DISTINCT keyword The pseudo column ROWNUM keyword Rows can’t be modified from a view, if in addition to above conditions, they contain: Columns defined by expressions Rows can’t be added to a view if either all above conditions or the following condition is met: NOT NULL columns in the base tables are not selected by the view CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Indexes Created in existing tables to locate rows quickly & efficiently Can be created on one or more columns of a table, and each index is given a name Users cannot see indexes, they are just used to speed up queries CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Creating an Index CREATE INDEX index_name ON table_name (<Column Name>); CREATE INDEX emp_indx ON emp(ENAME); CREATE INDEX emp_indx ON emp(ENAME,JOB); An index is a schema object that contains an entry for each value that appears in the indexed column(s) of the table or cluster and provides direct, fast access to rows. USER_INDEXES meta-data can be used to find out the details about indexes. CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Guidelines for Indexing Create an index if a query statement retrieves less than 15% of the rows in a large table Indexes are explicitly created on Primary Keys Index columns are used for joins to improve performance on joins of multiple tables Some RDBMS offer the choice of a clustered index in which the system sorts and re-sorts and rows of a table so that their physical order on the database device is always the same as their logical (indexed) order. CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Indexes (Contd…) Conditions when an Index will not be Invoked: No WHERE clause Index key not used in a WHERE clause Use of operators like ‘NOT’ and ‘IS NULL’ Use of only Secondary Keys in a Composite Index Use of functions or expressions with the Index Key Use of Index Key & another column with the logical ‘OR’ operator CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Oracle 11g and 12c SQL New Features CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Introducing Virtual Columns Beginning with Oracle 11g tables may now include virtual columns (dynamic values; not stored) Virtual columns obtain their value by evaluating an expression that might use: Columns from the same table Constants Function calls (user-defined functions or SQL functions) CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Example of Virtual Column CREATE TABLE NEWEMP (EMPNO NUMBER(4) NOT NULL, ENAME VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7, 2), COMM NUMBER(7, 2), INCOME NUMBER(9,2) GENERATED ALWAYS AS (NVL("SAL",0)+NVL("COMM",0)) VIRTUAL, DEPTNO NUMBER(2)); CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Identity Columns A column in a table can be marked as identity column which generates its value by itself. Oracle implicitly creates a sequence of default configuration for the identity column. For each insert operation, the current value of the sequence gets automatically assigned to the identity column. The feature syntax is as below – SQL> create table t_id_col   2  ( x number   3      generated by default   4          as identity   5          ( start with 10   6            increment by 15 )   7          primary key,   8    y varchar2(30)   9  )  10  /    CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Identity Columns SQL> insert into t (x,y) values ( 1, 'hello1' ); SQL> insert into t (x,y) values ( default, 'hello2' );    SQL> insert into t (y) values ( 'hello3' );   SQL> select * from t;          X  Y ——————————  ———————————          1  hello1         10  hello2         25  hello3 CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Extended String Datatypes Until Oracle 11g SQL, the maximum precision allowed for a string type column was 4000. In Oracle 12c, the precision has been increased upto 32767 bytes or 32K. The new string data types will be known as Extended String Types in Oracle 12c. The feature is controlled by an initialization parameter MAX_STRING_SIZE. The database must be in upgrade mode to enable this feature. Note that once the feature is enabled, thereafter the parameter cannot be disabled. ALTER SYSTEM SET max_string_size = ENABLED; CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Top N queries using FETCH FIRST and OFFSET Oracle 12c eases the cases of top-N analysis by introducing FETCH FIRST clause in SQL language. The clause internally sorts the query result set and retrieves the specified number of rows from the set. There are two flavors of pulling out the data from the result set i.e. either retrieve fixed number of rows (FETCH FIRST 10 ROWS ONLY) or retrieve a percentage of rows from the result set (FETCH 5 PERCENT ONLY). If one needs to retrieve the data set after excluding certain number of rows from the top, OFFSET clause can be used. If more than one row in the set satisfy the fetch condition, retrieve all the rows obeying the boundaries using WITH TIES clause. The below SQL query fetches top-5 employees sorted by their salary, in the company. SELECT employee_id, last_name FROM employees ORDER BY salary FETCH FIRST 5 ROWS ONLY ; CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Invisible Columns Oracle 12c introduce the feature of marking a column as invisible and hiding it from the table operations. An invisible column neither appears in the table definition nor in the SELECT * query on the table. In addition, the invisible column doesn’t participates in the transactions on the table. To select  or insert a value in the invisible column, it must be explicitly specified. To make it appear in the table structure description, the SQLPLUS variable SET COL INVISIBLE must be turned on. For example, we create a table T which has one visible and one invisible column. sql> create table T (x NUMBER, y NUMBER invisible); sql> insert into T values (1); sql> insert into T (x,y) values (2,5); Now, querying the table with an asterisk (*) will list only the visible columns. To list invisible column data, the column has to be explicitly selected. CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Invisible Columns sql> select * from T; X ---------- 1 2   X ---------- 1 2 sql> select x,y from T; X            Y ------- ---------- 2             5 CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Query Tuning Overview Query Tuning is a comprehensive subject and here we are just getting an overview to know what it means and following slides tell us some best practices that we can follow for getting the best from our queries performance Query tuning starts with knowing which queries are taking more time to retrieve data and then restructuring them, so that they will execute faster We can use SET AUTOTRACE command in SQL*Plus to learn about execution plan of a query. Execution plan is prepared by Oracle Query Optimizer that resides in the Oracle server, and suggests the steps required to execute query and retrieve data in an optimal way Query tuning requires multirole efforts, starting with business analyst, database designers, developers and DBAs, each of whom have to tune different aspects that will contribute in improving the overall performance In this course, we are looking at this from developer’s perspective CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Using AUTOTRACE command As a developer, you can use AUTOTRACE command as shown below to quickly learn about the query execution plan that can help you decide if the query requires some changes (tuning) for better and faster performance The suggested AUTOTRACE command usage is: SET AUTOTRACE ON EXPLAIN This command displays output as sampled below (for the query shown) Note to instructor: Briefly explain the concept of EXPLAIN PLAN using the sample in slide as to what operations are involved to give an idea to the participants CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Some best practices for faster Query Performance Select ONLY those columns in a query which are required. Extra columns which are not actually used, incur more I/O on the database and increase network traffic. Do not use the keyword DISTINCT as it incurs an extra sort operation and therefore slows your queries down. There should not be any Cartesian product in the query unless there is a definite requirement to do so. Wherever multiple tables are used, always refer to a column by either using an alias or using the fully qualified name. Do not leave the guess work for Oracle. When writing subqueries make use of the EXISTS operator where possible as Oracle knows that once a match has been found it can stop and avoid a full table scan. Use equijoins whenever possible, they improve SQL efficiency. Avoid doing an ORDER BY on a large data set especially if the response time is important. CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Contd… If possible use bind variables instead of constant/literal values in the predicate filter conditions to reduce repeated parsing of the same statement. Try to use an index if less than 5% of the data needs to be accessed from a data set. Querying from a view requires all tables from the view to be accessed for the data to be returned. If that is not required, then do not use the view. Instead, use the base table(s), or if necessary, define a new view. If Query requires quick response rather than good throughput is the objective, try to avoid sorts (group by, order by, etc.). Queries tend to perform worse as they age due to volume increase, structural changes in the database and application, upgrades etc. Seek help from DBAs and other experts to know more about this and tune the queries accordingly. It is always good to understand the data both functionally and it’s diversity and volume in order to tune the query. CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited

Thank You CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited