Database (Oracle) basic knowledge summary

view

  • Standard View

    • Normal view, also known as relational views
  • Inline view

    • An embedded view when writing queries using SQL statements temporary building, also known as inline view
  • Materialized views

    • The results of a stored query, formerly known as snapshots

    Syntax to create a view

create [or replace][force | noforce] view 
[(alias[, alias]...)] 
as subquery 
[with check option [constraint]]
[with read only [constraint]]

Create a read-only view

create view CS_Students
as
select ID, first_name, last_name, major, current_credits from students where major='Computer Science'
with read only

Create a view with the with check option

create or replace view his_classes
as
select department, course, description, max_students, current_students, num_credits, room_id from classes where department='his'
with check option

Multi-table views

create view class_building
as
select department, course, classes.room_id, building, room_number from classes, rooms where classes.room_id = rooms.room_id

Updatable view

  • Key reserved table
  • All columns must be updated to retain the key columns in the table
  • Add, delete, change again the same operation time can substantially modify the view of a table
  • Avoid the update operation on a multi-table view
select * from user_updatable_columns where table_name='class_building'

Inline view:

  • The inline view is a temporary view, not stored in the data dictionary
  • Facilitate the implementation of the query
  • When the query contains a temporary inline view, in the view select statement is first executed to obtain a result set, and then view the results of inline query queries an outer layer
  • A query can embed multiple inline view
create table students(
    id number(5) primary key,
    first_name varchar2(20),
    last_name varchar2(20),
    major varchar2(30),
    current_credits number(3)
);
create table registered_students(
    student_id number(5) not null,
    department char(3) not null,
    course number(3) not null,
    grade char(1),
    constraint rs_grade check(grade in ('A', 'B', 'C', 'D', 'E')),
    constraint rs_student_id foreign key (student_id) references students(id),
    constraint rs_department_course foreign key (department, course) references classes(department, course)
);

select s.id, s.first_name, s.last_name, s.major, stu_count.totalcourse from students s,(select student_id, count(*) totalcourse from registered_students group by student_id) stu_count where s.id = stu_count.student_id;

Materialized views

  • Also known as materialized views
  • The difference between materialized views and materialized view general view that holds the results of the query, but only preserved by the normal view sql statement query
  • As a result of materialized views store query, frequently when trying to access, can greatly enhance the performance of the query, reduce the time of the query
  • Commonly used in the data warehouse environment, complex and aggregated polymerization environment

grammar

create materialized view [view_name]
referesh [fast|complete|force]
[
on [commit|demand]
start with (start_time) next (next_time)
]
[build immediate|build deferred]
as {sql statement}

such as

create materialized view mv_view
refresh force on demand
start with sysdate
next to_date(concat(to_char(sysdate+1,'dd-mm-yyy'),'22:00:00'),'dd-mm-yyyy hh24:mi:ss')
as
select * from table_name;

index

An Oracle table, each table will automatically have a ROWID pseudo column, the pseudo-column generated automatically by Oracle. Where a unique identifier for a record ID number of a physical location. Once the data is added to the database table, and generates the ROWID fixed, during operation of the database table will not be changed. However, when a change or a change table storage location table space occurs, due to a physical change in position is generated, the ROWID value will change.

Index Classification

  • B-tree index

    • Oracle in default index is an index of this type. B-tree index is generally high re-retrieval column cardinality (less duplicate content on the column or not) may provide a high performance when retrieving operation
    create index rs_course on registered_students(course)
  • Bitmap Index

    • If the data are low on a column cardinality (Low - Cardinality) when the column may be utilized to improve the performance of bitmap index query.
    • Create a bitmap (bit position) for each value of the index column, using 1 bit (a value of 0 or 1) to indicate whether the row containing the bitmap index column values ​​of each row in the table.
    create bitmap index rs_department on registered_students(department)
  • Function Index

    • Index values ​​are not directly from the column, but from a function or an expression containing columns
CREATE TABLE classes (
  department       CHAR(3),
  course           NUMBER(3),
  description      VARCHAR2(2000),
  max_students     NUMBER(3),
  current_students NUMBER(3),
  num_credits      NUMBER(1),
  room_id          NUMBER(5),
  CONSTRAINT classes_department_course
    PRIMARY KEY (department, course),
  CONSTRAINT classes_room_id
    FOREIGN KEY (room_id) REFERENCES rooms (room_id)
  );
  
  create index cla_stu on classes(max_students - current_students);
  set AUTOTRACE TRACEONLY EXPLAIN;
  select * from classes where max_students-current_students>20;

Query Index

select * from user_indexes;

Data partition

Data partitioning

  • Score refers to a table or index is divided into several pieces
  • Each logical partition must have the same properties, but may have different physical properties
  • Consider good partitioning scheme, select a column in the table or column data when creating a table structure as the partition key
  • Partition column data types may be included in the keyword number, date, varchar2, char
  • oracle partition management, automatic insertion of new data into the corresponding partition

Stored data partition advantage

  • Since the data partitioning, hardware failure affects only local data
  • Improve speed of data query, the query may be only a specific partition
  • It provides a decentralized data management capabilities of large databases
  • For all operating tables are adapted to each partition partition table
  • DBA can be set to the attribute of each partition
  • DBA can operate table space, availability of partition control data
  • Partitions can be separated or combined, in order to balance the I / O

Suitable partitions scene

  • Table size than 2GB
  • Table contains historical data, the new data is added to the new partition

Four partitioning-method

  • Range-based partitioning
    • Keywords can be a multi-column partition
    • The inserted data is automatically assigned to the corresponding partition
    • The interpolated data is not greater than the maximum value less than the
    • You can use maxvalue
    • Not contain LONG, LOB and object types listed in the partition table
    • Aggregate table can not be partitioned
    • You can specify a table space for each partition. When not specify a table space, using the user's default table space
create table <table_name>
(column_name data type, column_name data type, ...)
partition by range (column_list)
(partition <partition name> values less than <value_list>,
partition <partition name> values less than <value_list>
);

RS_audit table is used to record registered_students modification table performed. If in order to improve query speed, DBA the 2018 record in the first half and second half, respectively, kept in the District ts1 and ts2 in.

create table rs_audit(
change_type char(1) not null,
...
)
partition by range(timestamp)
(partition rsaudit_201301
 values less than (to_date('20180701', 'YYYYMMDD'))
 tablespace ts1,
 partition rsaudit_201302
 values less than (to_date('20190101', 'YYYYMMDD'))
 tablespace ts2
);
  • Hash-based partitioning

    • The hash function is calculated for a record to be inserted which partition
    • Use hash partitioning, simply specify the number of partitions to n
    • Or hash partition name, and stores it in the pending table space
    -- 将表 students 中的记录分别存储在4个分区中
    create table students(
      id number(5) primary key,
        first_name varchar2(20),
        last_name varchar2(20),
        major varchar2(30),
        current_credits number(3)
    )
      partition by hash(id)
      partitions 4
      store in (stu1, stu2, stu3, stu4);
    create table hash_table
    (
      col number(8),
      inf varchar2(100)
    )
    partition by hash(col)
    (
      partition part01 tablespace hash_ts01,
        partition part02 tablespace hash_ts02,
        partition part03 tablespace hash_ts03
    )
  • Based on the list of partitions

    • Tells the database a list of values ​​established by specific discrete values ​​which belong to a partition
    • Only a single column partitioning key
    -- 把学生基本信息表 student 按照专业 major 的不同取值进行分区
    create table students (
      id                         NUMBER(5) PRIMARY KEY,
      first_name           VARCHAR2(20),
      last_name            VARCHAR2(20),
      major                   VARCHAR2(30),
      current_credits     NUMBER(3)
    )
    PARTITION BY LIST (major) (
       PARTITION engineering VALUES ('Computer Science', 
                                         'Chemistry', 'Mechanics'),
       PARTITION history VALUES (' History ', ' Economics '),
       PARTITION music VALUES ('Music'),
       PARTITION nutrition VALUES ('Nutrition'));
  • Composite Partitioning

    • Partition partition is a hybrid combination mode
    • It can be divided into two types:
      • Range - Partition Hash composition
      • Range - list composite partitioning
    • First, the partition table composition range partitioning and the hash partitioning or partitioning again listing partitioning each range.
    -- 将rooms表首先按照教室编号room_id进行范围分区,编号30000以下的在一个分区,编号在30000以上、60000以下的在一个分区,编号大于60000的在一个分区。然后再把每个分区按照座位数量分为两个子hash分区。 
    
    CREATE TABLE rooms (
      room_id          NUMBER(5) PRIMARY KEY,
      building          VARCHAR2(15),
      room_number      NUMBER(4),
      number_seats      NUMBER(4),
      description        VARCHAR2(50)
     )
    PARTITION BY RANGE (room_id)
    SUBPARTITION BY HASH (number_seats)
    SUBPARTITIONS 2
    (PARTITION rooms_1 VALUES LESS THAN (30000),
    PARTITION rooms_2 VALUES LESS THAN (60000),
    PARTITION rooms_3 VALUES LESS THAN (maxvalue)); 
    

Query partition table

  • When a record in the partition table, record, and a partition boundary based on comparing predefined distribution key specified so as to be assigned to the partition table
  • When the partition table query, you can query for the entire table, and is also available on a partition
select * from students
select * from students partition(history)
select * from students partition(history) ss where ss.current_credits=12

Copy partition table, that is to copy a partition table to another table

create table music_students as select * from students partition(music)

Maintenance Partition Table

  • Add District

    • After the partition to be loaded last partition high value
    • When using maxvalue, the partition table is not increased
    -- 给表 rs_audit 增加一个分区
    alter table rs_audit
    add partition rsaudit_201401
    values less than (to_date('20140701', 'YYYYMMDD'))
    tablespace ts3;
    
    --将分区 rsaudit_201301 删掉
    alter table rs_audit drop partition rsaudit_201301
  • Modify Partition

    • You can rename the partition
    • You can modify the partition storage parameters
    -- 将表 rooms 的分区 rooms_1 改名为 rooms_30000
    alter table rooms rename partition rooms_1 to rooms_30000
  • Mobile partition data

-- 将分区 rasudit_201302 中的数据移动到表中间 bak_201302 上
alter table rs_audit move partition rsaudit_201302 tablespace bak_201302
  • Partition Split
-- 将表rooms的分区rooms_2拆为两个分区,将room_id在30000至45000之间的记录划分到分区rooms_21中,room_id在45000至60000之间的记录划分到分区rooms_22中
alter table rooms split partition rooms_2 at (45000) into (partition rooms_21, partition rooms_22)

user

oracle user

The type of user

  • root
    • Create a new database
    • Startup and shutdown database
    • Modify the database scheme
    • Complete database backup and recovery
    • Modify the database structure
    • Create users, rights management, etc.
  • Database Administrator
    • Users with DBA role, can perform any operation inside the database
  • Other users
    • Database developers can create any entity

Create a user generally include the following aspects:

  • username
  • Ways of identifying
  • Specify the default table space
    • When a user creates schema objects, if not specified table space, then the object is created in the default table space
  • Quota allocation table
    • The maximum size of the user can decide to use in each tablespace
  • Specifies a temporary table space
    • As required by disk space for sorting or summarized data sql statement provides storage space
  • Environmental resources specified file
    • CPU time specified by the profile file, the number of logical read, the number of each user can connect warrior A dialog idle time
  • Set the default role
create user user_name identified by passward
[default tablespace 表空间名]
[temporary tablespace 表空间名]
[quota [整数][unlimited] on 表空间名]
[profile 环境文件名]

create user ITryagain
identified by 123456
default tablespace data_ts
temporary tablespace data_ts
quota 10M on data_ts
quota 20M on system
profile pITryagain;

View table space

-- 查看系统默认表空间
select property_value from database_properties where property_name='default_permanent_tablespace'

-- 查看用户表空间
select default_tablespace, temporaty_tablespace from dba_users where username='C##ITRYAGAIN'

Modify User

-- 将用户 ITryagain 的密码更改为 T#0908,在 data_ts 表空间中分配50M空间,并取消在 SYSTEM 中的表空间。 
alter user ITryagain
identified by T#0908
default tablespace data_ts
temporary tablespace temp_ts
quota 50M on data_ts
quota 0M on system
profile pITryagain;

delete users

drop user user_name [cascade]
-- 使用 cascade 选项会从数据字典中删除该用户、该用户的相关模式及模式中包含的所有模式对象
-- 不能删除当前已经连接到数据库的用户

Resource Management

  • profile is a resource limits specified database entity, it can limit the resources of a single call or an entire conversation required
  • When an environmental resource is assigned to one user, it implements these restrictions on the user
create profile profile_name limit limit(s) range

create profile pITryagain limit FAILED_LOGIN_ATTEMPTS 3

Their names and descriptions of common restrictions

-- 查询 profile 文件
select profile, resource_name, limit from dba_profiles prder by profile

select * from dba_profiles where profile='DEFAULT'

-- 修改 profile 文件
-- 资源文件一旦建立,可以分配个数据库用户
-- 一个环境资源文件可以分配给多个用户,但一个用户在任何时候都只有一个环境资源文件
-- 环境资源文件一旦建立,可以使用 alter profile 命令来修改参数
alter profile pITryagain limit
PASSWORD_REUSE_TIME 7
IDLE_TIME 20

-- 删除 profile 文件
-- 具有系统权限 drop profile 的用户可以通过语句 drop profile 删除环境资源文件
-- cascade 选项表示撤销文件的分配,使用该选项可以删除当前分配给用户的环境资源文件
drop profile profile_name [cascade]

Competence

There are two types of privilege levels oracle

  • System-level privileges
    • That permission to perform a specific action at the system level, for example, connect to the database, create a table space and create a user belongs to system-level privileges in the database. The definition of more than 100 system-level privileges in the oracle.
  • Object-level permissions
    • A user authority value other users can access the objects, i.e., objects in a variety of modes, such as a particular action performed on the permissions tables, views, sequences, procedure, function, or package. Objects of different types have different kinds of privileges.

Part of the system-level privileges

-- 授予系统权限
grant [系统级权限名][角色] to [用户名][角色][public][with admin option]

grant create session to ITryagain with admin option;

-- 撤销系统权限
revoke [系统级权限名][角色] from [用户名][角色][public][with admin option]

revoke create session from ITryagain;

-- 查看系统权限
-- 数据库管理员可以使用 dba_sys_privs 数据字典视图产看所有系统权限的授权信息
-- 用户也可以使用 user_sys_privs 数据字典视图查看自己具有的系统权限
-- 以用户 ITryagain 身份登录
select * from user_sys_privs;

Object-level permissions

-- 授予对象权限
grant select on students to ITryagain
grant ALL on students to ITryagain
grant update(number_seats) on rooms to ITryagain

-- 查看对象权限
-- 用户可以通过查询 user_tab_privs dba_tab_privs 等数据字典视图查看童虎的对象权限信息
select table_name, priviege from dba_tab_privs where grantee='ITRYAGAIN';

Roles

  • Role is a named set of permissions, roles can use this set of permissions granted or revoked at the same time
  • A role can combine multiple permissions and roles
  • Roles can be divided into predefined roles and custom role types
  • Common system predefined roles
    • connect
    • resource
    • dba
-- 查询角色
-- 预定义角色的细节可以从 dba_sys_privs 数据字典视图中查询到
select * from dba_sys_privs where grantee='connect'
select * from dba_sys_privs where grantee='resource'

-- 创建自定以角色
create role 角色名 [not identified] [identified [by 口令][externally]]

create role ITryagain
-- identified by 字句说明了在位一个已经被授予该角色的用户启用角色之前进行验证时使用的口令

-- 删除角色
-- 删除角色时,并不会删除分配了这个角色的用户
drop role role_name

-- 授予角色权限
-- 新创建的角色没有任何相关的权限,为使一个新角色与权限相关联,必须给该角色授予权限或其他角色
-- 在同一个 grant 语句中,不能将系统权限和对象权限一起授予
grant create table, create view to ITryagain

-- 给用户指派角色
-- 一个角色可以指派多个用户,一个用户也可以具有多个橘色
-- 当把角色指派给用户时,赋予该角色的权限也自动分配给用户
grant create procedure, create trigger, ITryagain to user1;

-- 撤销用户角色
revoke ITryagain from user1;

View role information

Backup and Recovery

Database failure classification

  • Internal Affairs fault
    • It can be expected
    • Unexpected
  • system error
    • It means any time cause the system to shut down, making the system to reboot
    • All transactions that affect the running, but does not destroy the database
  • Media failure
    • It refers to the external memory failure
    • The destruction of the database or part database, and all matters affecting this part is reading data

Backup

Including backup 物理备份and逻辑备份

Physical Backup: the backup copy of the database file, a database for backup physical files, which files contain data files, control files and archived redo log files. Physical backup database is part of the physical file stored in other positions, such as a disk or tape backup offline. Divided into cold and hot backup.

Logical backup: backup logical value of the data in the database, such as a table or a stored procedure, a tool may be used to export oracle to binary logical data, into the database when the database recovery.

Backup Strategy

  • Large capacity disk arrays, disk image technology so that each database file automatically distributed to each physical disk
  • Using a dual server, keep a backup database on another server
  • Maintaining multiple control files on several different physical disk backup
  • Try to make the database run in archive mode
  • A leveling nightly backup operation, back up all data files, all archived log files, a control file
  • Weekly sequentially outputted (the Export) Operation

Backup and recovery methods

  • Physical backup
    • Use RMAN Recovery Manager for backup and restore: RMAN is the oracle built-in backup and recovery program, no additional installation, usually using the command line
    • Manual backup and recovery: in this way is to use the operating system commands on the database file backup and restore
  • Logical backup
    • You can back up important data, and to achieve between different operating systems or different versions of oracle data transmission

Cold Backup

  • 冷备份也称脱机备份,是指数据库关闭时的物理备份,步骤为
    • 编写一个要备份的数据库文件列表
    • 用 shutdown 命令正常关闭 oracle 例程
    • 用操作系统的备份工具,备份所有的数据文件、日志文件、控制文件、文本参数文件 pfile、服务器参数文件 spfile
    • 重启 oracle 历程

热备份

  • 也称联机备份,是在数据库运行时的物理备份
  • 热备份要求数据库在归档模式下操作
  • 在备份一个数据文件之前,要将它所在的表空间设置为备份模式,备份完成之后,再将表空间恢复为正常状态。
  • 步骤为
    • 逐个备份表空间中的数据文件
      • 设置表空间为备份状态
      • 备份表空间的数据文件
      • 恢复表空间为正常状态
    • 备份归档重做日志文件
      • 强制日志切换
      • 备份归档的重做日志文件
    • 备份控制文件

故障恢复

  • 事务内部故障,其恢复是由系统自动完成的
  • 系统故障的恢复是由系统在重复启动时自动完成的
  • 介质故障的恢复方法是重装数据库,然后重做已完成的事务,介质故障的恢复通常需要管理员人工干预
  • oracle 数据库的恢复过程分两步进行,首先将存放在重做日志文件中的所有数据库更新操作 REDO 到数据文件,之后对所有未提交的事务进行回滚
  • 数据库的恢复只能在发生故障之前的数据文件上进行重做(REDO)

Guess you like

Origin www.cnblogs.com/csu-lmw/p/12113885.html