Hot news

Why Oracle DB?

Oracle is the most suitable DB for storing data in high- security mode, arranging BigData , implementing any idea in many applications . ...

Showing posts with label DML. Show all posts
Showing posts with label DML. Show all posts

2020-02-28

SQL structure

В этой статье собраны и структурированы минимальные основы SQL Oracle из обширной документации базы данных Oracle 12c. Для тех, кто начинает изучение базы, эта информация поможет обрисовать общую картину. Для разработчиков и тестировщиков базы данных эти таблицы служат удобными помощниками в повседневной работе.
Расшифровки языковых аббревиатур в DB Oracle
SQL Structured Query Language
DDL Data Definition Language (DDL) statements manage schema objects in the database. These statements create new, drop old, and establish schema objects. They also control access to schema objects.
DML Data Manipulation Language (DML) statements can change data in database tables. For example, DML statements insert new rows into a table, update column values in existing rows, delete rows from a table, lock a table in the database, and explain the execution plan for a SQL statement.
TCL Transaction control language
PL Procedural Language
Структуризация
SQL
Static PL/SQL DDL Dynamic PL/SQL SQL*Plus
query DML TCL manage control native DBMS_SQL package
SELECT DELETE COMMIT ALTER ADMINISTER CLOSE DBMS_SQL.RETURN_RESULT Procedure @
EXPLAIN ROLLBACK CREATE ANALYZE EXECUTE IMMEDIATE DBMS_SQL.GET_NEXT_RESULT Procedure @@
INSERT SAVEPOINT DROP ASSOCIATE FETCH DBMS_SQL.TO_REFCURSOR Function /
LOCK TABLE SET TRANSACTION FLASHBACK AUDIT OPEN FOR DBMS_SQL.TO_CURSOR_NUMBER Function ACCEPT, APPEND, ARCHIVE, ATTRIBUTE
MERGE GRANT CALL BREAK, BTITLE
UPDATE PURGE COMMENT CHANGE, CLEAR, COLUMN, COMPUTE, CONNECT, COPY
RENAME DISASSOCIATE DEFINE, DEL, DESCRIBE, DISCONNECT
REVOKE NOAUDIT EDIT, EXECUTE, EXIT
TRUNCATE SET (constraint, role) GET
HELP, HOST
INPUT
LIST
PASSWORD, PAUSE, PRINT, PROMPT
QUIT
RECOVER, REMARK, REPFOOTER, REPHEADER, RUN
SAVE, SET, SHOW, SHUTDOWN, SPOOL, START, STARTUP, STORE
TIMING, TTITLE
UNDEFINE
VARIABLE
WHENEVER
XQUERY

Нижеследующие списки касаются PL (Procedural Language)
Stored PL/SQL Units
Anonymous Block - часть хранимых подпрограмм, самостоятельный блок в скрипте или теле джоба, триггера
FUNCTION
LIBRARY
PACKAGE
PACKAGE BODY
PROCEDURE
TRIGGER
TYPE
TYPE BODY

PL/SQL Data Types
SQL BOOLEAN INTEGER REF CURSOR User-Defined Subtypes Predefined
BINARY_FLOAT SIMPLE_INTEGER Unconstrained BFILE
BINARY_DOUBLE PLS_INTEGER Constrained BLOB
CHAR BINARY_INTEGER with Base Types BOOLEAN
VARCHAR2 CHAR
LONG CLOB
LONG RAW DATE
ROWID NUMBER
UROWID

PL/SQL Collections and Records Collection Methods
Associative Arrays Collection Types Multidimensional Collections Nested Tables Varrays (Variable-Size Arrays) Record COUNT
%ROWTYPE Attribute DELETE
Constants EXISTS
Types EXTEND
Variables FIRST
LAST
LIMIT
NEXT
PRIOR
TRIM

PL/SQL Language Elements
Statement Pragma Constuction Declaration Attributes Others
Assignment AUTONOMOUS_TRANSACTION Block Collection Variable Implicit Cursor Collection Method Invocation
Basic LOOP EXCEPTION_INIT Comment Constant Named Cursor RETURNING INTO Clause
CASE INLINE Exception Handler Cursor Variable %ROWTYPE SQLCODE Function
CLOSE RESTRICT_REFERENCES Expression Exception %TYPE SQLERRM Function
CONTINUE SERIALLY_REUSABLE Explicit Cursor
Cursor FOR LOOP UDF Formal Parameter
DELETE Function
EXECUTE IMMEDIATE Procedure
EXIT Record Variable
FETCH Scalar Variable
FOR LOOP
FORALL
GOTO
IF
INSERT
NULL
OPEN
OPEN FOR
PIPE ROW
RAISE
RETURN
SELECT INTO
UPDATE
WHILE LOOP

PL/SQL Control Statements
Conditional Selection LOOP Sequential Control
IF THEN LOOP GOTO
IF THEN ELSE EXIT NULL
IF THEN ELSIF EXIT WHEN
Simple CASE CONTINUE
Searched CASE CONTINUE WHEN
FOR LOOP
WHILE LOOP

SQL Statements for Stored PL/SQL Units
Изменение свойств* Создание Удаление
ALTER FUNCTION CREATE FUNCTION DROP FUNCTION
ALTER LIBRARY CREATE LIBRARY DROP LIBRARY
ALTER PACKAGE CREATE PACKAGE DROP PACKAGE
CREATE PACKAGE BODY DROP PACKAGE BODY**
ALTER PROCEDURE CREATE PROCEDURE DROP PROCEDURE
ALTER TRIGGER CREATE TRIGGER DROP TRIGGER
ALTER TYPE CREATE TYPE DROP TYPE
CREATE TYPE BODY DROP TYPE BODY
* - вместо внесения изменений через ALTER-команду можно пересоздать объект командой CREATE OR REPLACE. При этом объект сохранит статус, например, включенность триггера. ** - в документации Oracle пропущена команда, но удалить тело пакета с сохранением его спецификации позволительно

PL/SQL Reserved Words
ALL, ALTER, AND, ANY, AS, ASC, AT
BEGIN, BETWEEN, BY
CASE, CHECK, CLUSTERS, CLUSTER, COLAUTH, COLUMNS, COMPRESS, CONNECT, CRASH, CREATE, CURSOR
DECLARE, DEFAULT, DESC, DISTINCT, DROP
ELSE, END, EXCEPTION, EXCLUSIVE
FETCH, FOR, FROM, FUNCTION
GOTO, GRANT, GROUP
HAVING
IDENTIFIED, IF, IN, INDEX, INDEXES, INSERT, INTERSECT, INTO, IS
LIKE, LOCK
MINUS, MODE
NOCOMPRESS, NOT, NOWAIT, NULL
OF, ON, OPTION, OR, ORDER, OVERLAPS
PROCEDURE, PUBLIC
RESOURCE, REVOKE
SELECT, SHARE, SIZE, SQL, START, SUBTYPE
TABAUTH, TABLE, THEN, TO, TYPE
UNION, UNIQUE, UPDATE
VALUES, VIEW, VIEWS
WHEN, WHERE, WITH

PL/SQL Keywords
A, ADD, ACCESSIBLE, AGENT, AGGREGATE, ARRAY, ATTRIBUTE, AUTHID, AVG
BFILE_BASE, BINARY, BLOB_BASE, BLOCK, BODY, BOTH, BOUND, BULK, BYTE
C, CALL, CALLING, CASCADE, CHAR, CHAR_BASE, CHARACTER, CHARSET, CHARSETFORM, CHARSETID, CLOB_BASE, CLONE, CLOSE, COLLECT, COMMENT, COMMIT, COMMITTED, COMPILED, CONSTANT, CONSTRUCTOR, CONTEXT, CONTINUE, CONVERT, COUNT, CREDENTIAL, CURRENT, CUSTOMDATUM
DANGLING, DATA, DATE, DATE_BASE, DAY, DEFINE, DELETE, DETERMINISTIC, DIRECTORY, DOUBLE, DURATION
ELEMENT, ELSIF, EMPTY, ESCAPE, EXCEPT, EXCEPTIONS, EXECUTE, EXISTS, EXIT, EXTERNAL
FINAL, FIRST, FIXED, FLOAT, FORALL, FORCE
GENERAL
HASH, HEAP, HIDDEN, HOUR
IMMEDIATE, INCLUDING, INDICATOR, INDICES, INFINITE, INSTANTIABLE, INT, INTERFACE, INTERVAL, INVALIDATE, ISOLATION
JAVA
LANGUAGE, LARGE, LEADING, LENGTH, LEVEL, LIBRARY, LIKE2, LIKE4, LIKEC, LIMIT, LIMITED, LOCAL, LONG, LOOP
MAP, MAX, MAXLEN, MEMBER, MERGE, MIN, MINUTE, MOD, MODIFY, MONTH, MULTISET
NAME, NAN, NATIONAL, NATIVE, NCHAR, NEW, NOCOPY, NUMBER_BASE
OBJECT, OCICOLL, OCIDATE, OCIDATETIME, OCIDURATION, OCIINTERVAL, OCILOBLOCATOR, OCINUMBER, OCIRAW, OCIREF, OCIREFCURSOR, OCIROWID, OCISTRING, OCITYPE, OLD, ONLY, OPAQUE, OPEN, OPERATOR, ORACLE, ORADATA, ORGANIZATION, ORLANY, ORLVARY, OTHERS, OUT, OVERRIDING
PACKAGE, PARALLEL_ENABLE, PARAMETER, PARAMETERS, PARENT, PARTITION, PASCAL, PIPE, PIPELINED, PLUGGABLE, PRAGMA, PRECISION, PRIOR, PRIVATE
RAISE, RANGE, RAW, READ, RECORD, REF, REFERENCE, RELIES_ON, REM, REMAINDER, RENAME, RESULT, RESULT_CACHE, RETURN, RETURNING, REVERSE, ROLLBACK, ROW
SAMPLE, SAVE, SAVEPOINT, SB1, SB2, SB4, SECOND, SEGMENT, SELF, SEPARATE, SEQUENCE, SERIALIZABLE, SET, SHORT, SIZE_T, SOME, SPARSE, SQLCODE, SQLDATA, SQLNAME, SQLSTATE, STANDARD, STATIC, STDDEV, STORED, STRING, STRUCT, STYLE, SUBMULTISET, SUBPARTITION, SUBSTITUTABLE, SUM, SYNONYM
TDO, THE, TIME, TIMESTAMP, TIMEZONE_ABBR, TIMEZONE_HOUR, TIMEZONE_MINUTE, TIMEZONE_REGION, TRAILING, TRANSACTION, TRANSACTIONAL, TRUSTED
UB1, UB2, UB4, UNDER, UNPLUG, UNSIGNED, UNTRUSTED, USE, USING
VALIST, VALUE, VARIABLE, VARIANCE, VARRAY, VARYING, VOID
WHILE, WORK, WRAPPED, WRITE
YEAR
ZONE

2018-06-23

Indexes as quick sorting (II)

Part II – What index?

The previous part of index describing showed some examples of DML fast execution.
Now not only char columns are used in BigData. And it seems that Oracle can't work with all of them:
"
You cannot create an index on columns or attributes whose type is user-defined, LONG, LONG RAW, LOB, or REF, except that Oracle Database supports an index on REF type columns or attributes that have been defined with a SCOPE clause.
"
Don't worry. Oracle DB has a workaround. There are many types of indexes.
Note: The following screen shots are from Oracle SQL Developer and SQLDetective applications.
Oracle SQL Developer SQLDetective
Don't forget to set Storage parameters on index creating.
Not all of them are allowed for altering:
Create indexes only for frequent using statements
because the index is stored in tablespace as a table copy.

Here are some useful words from Oracle Documentation about index organizations:
* B-tree (short for balanced trees) indexes
     * Index-organized tables
          Index-organized tables are useful when related pieces of data must be stored together or data must be physically stored in a specific order. A typical use of this type of table is for information retrieval, spatial data, and OLAP applications.
          A secondary index is an index on an index-organized table.
Oracle SQL Developer SQLDetective
Table Wizards for Index-Organized table creating

     * Reverse key indexes
          The bytes of the index key are reversed.
     * Descending indexes
          Descending order of data is used.
     * B-tree cluster indexes
          Instead of pointing to a row, the key points to the block that contains rows related to the cluster key.
Oracle SQL Developer SQLDetective
There is no Cluster Wizard in Oracle SQL Developer
An index on cluster may be created by object wizard in SQLDetective only

* Bitmap and bitmap join indexes
     In a bitmap index, an index entry uses a bitmap to point to multiple rows. In contrast, a B-tree index entry points to a single row
Oracle SQL Developer SQLDetective
Only SQLDetective 4.4 allows to set joins

* Function-based indexes
     Function-based indexes are efficient for evaluating statements that contain functions in their WHERE clauses.
Oracle SQL Developer SQLDetective
Type manually your formula into "Expression" editor.
SQLDetective has a tool for generating an expression,
but it's used in Query Builder only.

* Application domain indexes
     You can encapsulate application-specific index management routines as an indextype schema object, and then define a domain index on table columns or attributes of an object type. Extensible indexing can efficiently process application-specific operators.
Oracle SQL Developer SQLDetective
An indextype in Oracle SQL Developer
you should create manually,
it's not supported by object wizard.
SQLDetective supports the Indextype Wizard.
     Extensive indexing can:
          Accommodate indexes on customized, complex data types such as documents, spatial data, images, and video clips (see "Unstructured Data")
          Make use of specialized indexing techniques

* System indexes are created automatically for table constraints except foreign key.

On index creating and modifying, please, don't fully rely on wizard UI as they support not all logical issues and some rare or not-described in Oracle Documentation clauses are not supported by the developer application.
For using index abilities you should create objects of some other types ("Create Table (index organized)", "Create Cluster", "Create Indextype", "Create Operator", "Create Type"):
Oracle SQL Developer SQLDetective
Oracle SQL Developer doesn't support Clusters and Indextypes wizards 

Read about some other index options in the next topic.

2018-06-21

Indexes as quick sorting (I)

Part I – Why indexes?

Oracle Database now grows and grows. It becomes BigData. As modern age wants to do everything fast then there is the best way to select necessary data in time.
Let's see an example.

1. Create a simple table with data:
CREATE TABLE FOR_SORT ( COL1 VARCHAR2(10 BYTE) NULL, COL2 NUMBER(5,0) NULL )
/
-- Insert script for table FOR_SORT
INSERT INTO FOR_SORT(COL1, COL2) VALUES('ddd', 1)
/
INSERT INTO FOR_SORT(COL1, COL2) VALUES('ggg', 2)
/
INSERT INTO FOR_SORT(COL1, COL2) VALUES('ccc', 3)
/
INSERT INTO FOR_SORT(COL1, COL2) VALUES('fff', 4)
/
INSERT INTO FOR_SORT(COL1, COL2) VALUES('hhh', 5)
/
INSERT INTO FOR_SORT(COL1, COL2) VALUES('bbb', 6)
/
INSERT INTO FOR_SORT(COL1, COL2) VALUES('iii', 7)
/
INSERT INTO FOR_SORT(COL1, COL2) VALUES('aaa', 8)
/
INSERT INTO FOR_SORT(COL1, COL2) VALUES('eee', 9)
/
2. Explain plan for simple select statement (SELECT A.* FROM FOR_SORT A;) is the following:

The red colored line in Explain Plan results means that the statement is not optimized.

3. Create an index on one column:
CREATE INDEX IND_COL1 ON FOR_SORT ( COL1 )
4. Explain plan for a select statement with indexed column in WHERE clause (SELECT A.* FROM FOR_SORT A WHERE A.COL1 > 'c';) is more cheaper. Pay attention to "Cost" and "CPU Cost" values:

Note: data is ordered automatically by indexed column.

5. Let's compare explain plan for the same statement but with non-indexed column in WHERE clause(SELECT A.* FROM FOR_SORT A WHERE A.COL2 > 2;):

Result of not-ordered select statement is the same but Explain Plan differs - see "Cost" and "CPU Cost" values: 1/2 (indexed column in WHERE clause) -> 3 (not-indexed) and 14613/7321 (indexed) -> 37587 (not-indexed).

6. Compare explain plan for statements with ordered data, with and without mentioning an indexed column:
SELECT A.* FROM FOR_SORT A ORDER BY A.COL1 DESC;


SELECT A.* FROM FOR_SORT A WHERE A.COL1 IS NOT NULL ORDER BY A.COL1 DESC;

"Cost" and "CPU Cost" values show the best selection: ordering takes much resources but the clause with indexed column decreases it (4 -> 2, 3 -> 1, 36022939 -> 17753, 37137 -> 8921). Results of both select statements are equal, a short clause (any mention of indexed column COL1 in WHERE clause but not in ORDER BY clause) was added for execution speed up.

You see, index helps to execute the DML statements faster. About more index using, please, read the next topic.

2018-06-14

Data storing


There are several object types in Oracle DB for storing data. Some of them work with physical data, others operate with virtual data. Let's investigate TABLES, VIEWS, MATERIALIZED VIEWS, DIMENSIONS.
SQLDEVELOPER from Oracle and SQLDetective (SD) from Conquest Software Solutions allow to work partly with listed objects and their data.
SQLDEVELOPER works with Tables, Views, Materialized Views by object wizards:
and with some other data by Reports:
SD works with Tables, Views, Materialized Views, Dimensions by object wizards: 

TABLES
Tables are the main objects for work with data: adding, editing, deleting, storing. Table's data is stored physically in tablespaces (see SD wizard that allows to set storage parameters on table creating or modifying):
 Table Wizard in SQLDEVELOPER allows the limited list of column types (built-in: varchar2, number, date, clob, blob; ANSI: bfile, binary_double, etc.):
 Table Wizard in SD allows to generate columns as built-in types (number, varchar, date, raw, long, etc.), ANSI (char, float, etc.), user defined (object types of Oracle DB schemas):
 
 
 According to Oracle Documentation a table may be created on OBJECT TYPE, QUEUE, XML TYPE, that's possible by Table Wizard in SD:
 
 
 
 Constraints may be generated in SD on table creating:
 Table data is available for selecting and editing (Insert, Delete, Update, Merge) by Data Browser (Smart Dataset with Dataset Manager in SD), Query and Dataset Builders, Data tab in SQL Editor or Table Wizard.
 Data analyzing can be done by Data Dependency Analyzer, Explain Plan window, Table/View/Partition/Index/Cluster Analyzer (collect statistics, validate structures, list chained rows). On comparing objects in SD it's possible to compare tables by object properties and number of rows. Some developer applications allow to export and import data, duplicate rows, truncate or commit data, rename or drop object without typing and executing Oracle DB commands in SQL Editor. Data viewing in such applications is easy because of visualized sorts and filters.
 
 
 

VIEWS
Data in View is "virtual", it's aggregated from tables and views:
 
 As a View is created as selection from several tables so data editing becomes hard. Data in view is changed automatically on changing it in the source tables. If you need to edit the selected data then it's better to create a Materialized View. More complex view can be created on Object or XML Type, with check constraint. In different editions since Oracle 11g the same named view can be created by different select statements. View allow to rename columns, join, sort and filter data on selecting from source tables.

MATERIALIZED VIEWS
They were named Snapshots in Oracle 7. On MatView creating its data looks like imported from the select statement into MatView with physically created Table. In other words, the MatView becomes a standalone table after creating. Data of MatView may be modified and new version will be stored in the referenced table with the same name as MatView or refreshed from source tables of the select statement.
SQLDEVELOPER / Materialized View Wizard:
 
 
 
 
 SQLDetective / Materialized View Wizard:
 

DIMENSIONS
Dimension wizard in SD helps to visualize an OLAP cube structure:
 
 
 

Please, see the "Select statement" topic of Oracle Documentation about using MODEL, MEASURES, CUBE, DIMENSIONS.