Presentation is loading. Please wait.

Presentation is loading. Please wait.

Oracle – SQL 10g.

Similar presentations


Presentation on theme: "Oracle – SQL 10g."— Presentation transcript:

1 Oracle – SQL 10g

2 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

3 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

4 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

5 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

6 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

7 Views (Contd…) A view with the check option:
SQL> CREATE VIEW emp_vw 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

8 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

9 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

10 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

11 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

12 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

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

14 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

15 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

16 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

17 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

18 Extended String Datatypes
Until Oracle 11g SQL, the maximum precision allowed for a string type column was In Oracle 12c, the precision has been increased upto 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

19 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

20 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

21 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

22 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

23 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

24 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

25 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

26 Thank You CONFIDENTIAL© Copyright 2016 Tech Mahindra Limited


Download ppt "Oracle – SQL 10g."

Similar presentations


Ads by Google