Oracle study notes

Introduction
   Oracle Database, also known as Oracle RDBMS, or Oracle for short. It is a relational database management system from Oracle Corporation. It is a product that has been leading the way in the database field. It can be said that the Oracle database system is a popular relational database management system in the world. The system has good portability, convenient use and strong functions, and is suitable for all kinds of large, medium, small and microcomputer environments. It is a high-efficiency, reliable, high-throughput database solution.

Sql classification
   DQL (data query language)
      select
   DDL (data definition language)
      create, alter, drop, truncate
   DML (data manipulation language)
      insert, update, delete
   DCL (data control language)
      grant (authorization), revoke (recycling authority)
   TCL (Transaction control language)
      commit (commit), rollback (rollback), savepoint (savepoint)

common data types
   varchar2 Maximum value: 4000 bytes
   char Maximum value: 2000 bytes
   number (maximum length)
   number (maximum length, decimal places number)
   date year, month, day, hour, minute and second
   timestamp (timestamp) accurate to nanoseconds
   clob (character large object) 4GB * block size
   blob (binary large object) 4GB * block size

Constraint : used to ensure the validity and legality of data [constraint constraint name] (optional)
   primary key Primary key constraint, indicating unique non-null , and a table can only have one primary key
   not null non-null constraint
   unique unique constraint
   check (condition) check constraint
   references table name (column name) foreign key constraint (the column must be unique)
   primary key[unique] (column 1, column 2) Compound constraint, that is, the two columns are unique together, but not unique respectively

Default value
   default 'male' After the data type, before the constraint

Copy table: no other constraints except not null will be copied
   create table emp_my as select * from emp ;

Example 1: Create table statement
   create table users(
     username varchar2(20) primary key,
     password varchar2(20) not null,
     name varchar2(20) not null,
     zip number(6) check (length(zip) = 6),
     email varchar2(20) unique,
     married number(1) default 1 check (married = 1 or married = 0),
     birthday date
   );

user_tables (system table) saves the information of the table created by the current user
user_constraints, user_cons_columns (constraint table) saves the constraint information created by the current user

column(clo) controls the width of the
   column col column name format 9999
   col column name format a12

/ can be repeated Execute the current command
list(l) to view the current command
change(c)/oldstr/newstr Modify the column name (for the queried records)
start(@) xx.sql You can batch execute the sql statement
desc table name You can view the detailed information of the table
save path/file name can save the last sql command
help index can view all sqlplus commands
set pagesize 2000 set the number of records displayed by paging
set timing on display the time taken by a sql statement

For string comparison
   1. Use single quotes to represent strings
   2. Strict case sensitivity

like (fuzzy query ) select * from emp where ename like 'S%';
   S%: starts with S %A%: contains A %A: ends with A _A%: a _ represents a character

dual: Oracle special table, only one row and one column
   through the special table Do mathematical operations (cannot take remainder) select 100+200 from dual;

dbms_random.random() Generate random number
sysdate (is a variable) Get current time
to_char (date, format string) Convert date to string
   select to_char( sysdate,'yyyy-mm-dd hh24:mi:ss day q(quarter) am') from dual;
to_date(string, 'format string') convert string to date
   to_date('1981-12-31 ','yyyy-mm-dd')
add_months(date, integer) month addition and subtraction
Group by rules:    1. Only the columns that appear in group by can appear in the select clause.    2. Columns that do not appear in group by must be used with group functions in order to appear in select




















   select max(sal),deptno from emp group by deptno;

order by: used to sort
   asc ascending order desc descending order by a certain column

Example 3: Query the number of employees who joined each month in 1981
   select count(*), to_char(hiredate ,'mm') from emp where to_char(hiredate,'yyyy')='1981' group by to_char(hiredate,'mm');

execution order
   from > where > group > having > select > order by

while and having compare
   while The efficiency is higher than having, but when the data after grouping requires conditional comparison, only having
   select avg(sal), deptno from emp group by deptno having(avg(sal)>2000);

pseudo column
   rowid: uniquely identifies a record rownum : The number rownum conditional comparison of query records
   can only be used for < , <=

comparison Subquery
   1. The query result is a single value
   2. The query result is one row and multiple columns
   3. The query result is multiple rows and multiple columns, you can see it Create a temporary table

Example 4: Find employee information with salary rankings 6-10
   select * from(select e.*,rownum r from (select empno,ename,sal from emp order by sal desc) e where rownum <=10) where r > 5;

join query
   select empno,ename,sal,dname,e .deptno from emp e,dept d where e.deptno = d.deptno;
   Equivalent to select empno,ename,sal,dname,e.deptno from emp e inner join dept d on (e.deptno = d.deptno);
   Inner join: Only the matching records in the two tables will appear in the query
   result . Outer join: There are two types related to the connection order of the tables: left outer join (left outer join, all records in the left table regardless of whether they are related to the right table or not) Matches will appear in the final result) right outer join (right outer join)
      select empno,ename,sal,dname,e.deptno from emp e left outer join dept d on (e.deptno = d.deptno);
      equivalent to select empno,ename,sal,dname,e.deptno from emp e, dept d while e.deptno = d.deptno(+);(oracle special writing, + refers to the table on the right of the connection, only for understanding)

Cartesian connection
   select empno, ename, sal, dname from emp e, dept d;
   equivalent to select empno, ename, sal, dname from emp e cross join dept d;

multi-table join
   select o.orderid,o.orderdate,o.totalprice, i.qty,p.productname,p.price from orders o
      inner join orderitem i on (o.orderid = i.orderid)
      inner join product p on (i.productid = p.productid)
      where o.username = 'xxx' ;

Example 5: Find the employee information of the highest salary in each department
    select e.* from (select max(sal) msal,deptno from emp group by deptno) d
      inner join emp e on (d.deptno = e.deptno and d. sal = e.sal);
    or select * from emp e where sal = (select max(sal) msal from emp where deptno = e.deptno);

Example 6: Query the details of employees with the same salary
   select * from emp where sal in(select sal from emp group by sal having(count(*)>1));

Example 7: Rank by salary
   select empno,ename,sal,(select count(*)+1 from emp where sal > e.sal) from emp e;

Example 8: Find the top two information with the highest salary in each department
   select * from (select empno,ename,sal,deptno,(select count(*)+1 from emp where sal > e.sal and deptno > e.deptno) rank from emp e order by deptno,rank)where rank <=2;
   is equivalent to (oracle-specific solution) select empno,ename,sal,deptno,rank() over(partition by deptno order by sal desc) r from emp;
   rank(): loose ranking
   dense_rank(): tight ranking

First : The values ​​of the columns in the table should be atomic and cannot be subdivided

Second Normal Form: In the design of the table There should be no attributes that partially depend on the main attribute
   stuid, courseid The main attribute
   stuname depends on stuid Partially depends on
   coursename depends on courseid Partially depends on
   Score depends on stuid, courseid all depends on
       stuid stuname courseid coursename score
       1001 zhangsan 2001 java 90
       1001 zhangsan 2002 oracle 80
       1002 lisi 2001 java 70
       1002 lisi 2002 oracle 60

Third normal form: There cannot be indirect dependencies in the design of the table

Transaction : Representation An atomic inseparable operation
   treats one or more DMLSQL (insert, update, delete) as a whole. If the operation is successful, it will be committed (commit), and if one fails, it will be revoked (rollback)
   DDL and DCL statements ( create, alter, drop, grant, revoke), if there is no transaction before, start, if there is, join. And the successful execution will automatically commit the transaction.

Four major characteristics of transactions
   Atomicity A
   Consistency C: The state of the database before and after the transaction starts is consistent
   Isolation I: Avoid the appearance of dirty data set transaction isolation level serializable Set transaction isolation level
   Persistence D: After the transaction ends, the state of the data should be kept forever

Add a column: If there is already a record in the table, if the column requires a not null constraint, you can add the default value
   alter table table name add (column name 1 data type constraint, column name 2...)
   alter table users add (address varchar (20),telephone number(11));

delete column
   alter table table name drop column column name
   alter table users drop column address;

column rename
   alter table users rename column telephone to phone;

modify column type 
   alter table users modify mail varchar2( 30);//It was originally 20
  
modify constraint
   alter table users modify mail not null;
  
add constraint
   alter table users add [constraint constraint name] constraint type
       add primary key constraint alter table orders_my add constraint orders_my_username_fk foreign key(username) references users_my(username) ;

disable/enable constraint
   alter table users disable[enable] constraint constraint name

Delete constraint
   alter table users drop constraint Constraint name When

deleting data, foreign key constraints may be violated.
   1. Delete the slave table first and then delete the main table.
   2. Delete constraint
   3. Cascade
   delete. If the on delete cascade option is selected, the records from the slave table will be automatically deleted when the main table record is deleted.
   alter table orders_my add constraint orders_my_username_fk foreign key(username) references users_my(username) on delete cascade;

truncate table table name
   deletes all records in the table ( If you don't open a transaction, you can't recover it)
   delete from table name (delete a transaction is enabled, recoverable)

while deleting the table, first delete the foreign key constraint related to this table in
   cascade drop table users_my cascade constraint;

authorization syntax
   grant select on orders_my to xxx; Revoke
permission
   revoke select on orders_my from xxx;

create user
   cannot log in directly after creating user create user username identified by password
   Authorize login permissions, you can log in but cannot create tables grant create session to user name
   grants create table permissions, but no table space permissions grant create table to user name

Role : includes multiple commonly used permissions connect, resource
   grant connect to user name
   grant resource to username

change password
   alter user username identified by new password;

each user (a schema)
   table, constraint, function, sequence, view, index
  
sequence : ensure that the primary key value is unique (similar to the mysql primary key auto Add)
   create sequence sequence name; by default
   , the next value of the sequence is obtained from 1 select sequence name.nextval from dual;
   currval takes the current value
   create sequence sequence name start with 100001 increment by 5; the default value is 100001, and the increment value is 5
  
The data dictionary for sequences
   select sequence_name from user_sequences;
 
create a view: what is created is a virtual table, when querying the view, it is actually equivalent to the query table
   create view emp_view as select * from emp;
   Role: Simplify the writing of complex SQL statements

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326124336&siteId=291194637