Oracle database is a popular relational database management system in the world at present. The system has good portability, convenient use and powerful functions. It is suitable for all kinds of large, medium, small and microcomputer environments. The main contents of the Oracle database include: basic concepts such as table space, user permissions, and four constraints, DDL manipulation of databases and tables, DML manipulation of table data, multi-table query, paging query, sub-query and other query statement learning.
1. Basic knowledge of Oracle
1. Start and shut down the database
Open the "Services" window and start the corresponding Oracle service
OracleService<SID>: database service
OracleOraDb11g_home1TNSListener : database listening service
OracleDBConsole<SID>: Enterprise Manager Service
2, oracle network service configuration
Server-side configuration listening listener.ora directly modify the file or net manager tool configuration
Client configuration network service name tnsnames.ora
3. Connect to the database
Command line: SQL*Plus connection
Visual tool: PL/SQL Developer connection
4. Tablespace
A logical concept in ORACLE in the table space, it is used to store database files, and the database file is a data file stored on the disk, which is a physical concept. The table space is a memory area in the background, through which to connect to the database file, The table space is just a virtual space, it has no actual size, the table space is the smallest unit to restore the database, the table space cannot exist alone, it should contain at least one database file, and the database files with the same data structure can be placed in one In the table space, and the table space is used to manage these files logically, it can be imagined that ORACLE is a cabinet, and the table space is the empty drawer on the cabinet, and the database file is the folder, which is placed in the drawer
Table: smallest logical unit
Tablespace: the largest logical unit
table space role
Easy storage management, improved I/O performance, backup and recovery
Tablespace classification: permanent, temporary, undo tablespace
Create tablespace:
create tablespace t40 datafile ‘e:\app\Visant\oradata\orcl\t4001.DBF’size 50m autoextend on NEXT 32M MAXSIZE UNLIMITED;
Drop tablespace t40 including contents and datafiles;
5. User
创建:create user t40 identified by t40 default tablespace t40;
A role (admin and user) is a combination of a set of permissions with a name
Common system predefined roles:
CONNECT: Temporary user
RESOURCE: more reliable and formal users
DBA: database administrator role, has the highest authority to manage the database
Authorization command grant connect, resource to t40;
grant all privileges to t40;
Revoke privileges: revoke privileges or role from user;
6. Common data types
Character type: char\varchar2\long (note that long is not a numeric type)
Numeric: number(p,s)
Date: date\timestamp
Lob type: blob (binary object) clob (character format large object)
Bfile (binary data stored in the operating system)
7. Operation of database tables (DDL language)
Create the table:
create table teacher (tno number(4) not null);
Modify the table:
SQL> alter table teacher add( #Add column
sal number (7,2), hirdate date, wechat varchar2 (30));
SQL> alter table teacher modify(tname varchar2(30)); #Modify column
SQL> alter table teacher rename column gendar to gender#Modify column name
SQL> alter table teacher drop column wechat; #delete column
View table: SQL> desc teacher;
Add table data:
insert into teacher(tno,tname,tid,gender)values(1,’zs’,’111’,’男’)
commit; #Must be submitted to be valid
8. Four integrity constraints
Entity Integrity: Unique Constraint (column is unique, nullable, but can only have one null value)
Primary key constraint (primary key column data is unique and cannot be empty)
Domain integrity: restrict data types, check constraints, foreign key constraints, not-null constraints
Referential Integrity: Foreign Key Constraints
Custom Integrity: Rules, Stored Procedures, Triggers
9. Constraint command
Add four constraints
SQL> alter table teacher add constraint pk_teacher primary key(tno);
SQL> alter table teacher add constraint uk_teacher_tname unique(tname);
SQL> alter table teacher add constraint ck_teacher_gender check(gender in(‘男’,’女’));
SQL> alter table teacher add constraint fk_teaccher_deptno_dept foreign key(deptno) references dept(deptno);
delete constraint
alter table teacher drop constraint ck_gendar;
10. Backup and restore
EXP command to export data:
exp t40 / t40 file = "E: \ app \ Visant \ oradata \ orcl \ t40exp.dmp"
IMP command to import data:
imp t40 / t40 file = "E: \ app \ Visant \ oradata \ orcl \ t40imp.exp."
Import and export database objects
Four modes: full database, tablespace, table, user
Second, SQL programming
1. It is divided into four categories:
DDL definition\DML(DQL) manipulation, query\DCL data control\TCL transaction control
DDL keywords: CREATE, DROP, ALTER, TRUNCATE
DML keywords: INSERT, UPDATE, DELETE, SELECT
TCL keywords: COMMIT, ROLLBACK, SAVEPOINT;
Database operations: create create, view show, use use, delete drop
Table operations: create create, view show\desc, modify alter set (field modification add\modify\change\drop)
remove drop
Table data operations: add insert, modify update, delete delete\truncate
query select
2. DML operation:
Create a sequence and add data. change the data. delete data. Query data. Commit! or Rollback!
create sequence sq_teacher start with 1004 increment by 1 nomaxvalue; #Create a sequence and add data
select sq_teacher.nextval from dual; #initialization sequence (get the next sequence first)
select sq_teacher.currval from dual; #Get the current sequence
insert into teacher(tno,tname,gendar,sal)
values(sq_teacher.currval, 'Teacher Wang', 'Male', 5000); commit; #Add data
#change the data
update teacher set sal=sal+2000 where tname in('Teacher Chen', 'Teacher Han'); commit; #Modify data
drop sequence sq_name; #delete sequence
rollback; # rollback
#delete data
delete from dept;
truncate table dept; Once the primary key is referenced, it cannot be deleted. Once deleted, it cannot be recovered
drop table teacher;
#Query data
select * from teacher where job='R&D' order by sal desc#sort in descending order
#string concatenation
select ‘insert into dept values(‘||deptno||’,”’|| dname
||”’,”’||loc||”’);’ from dept
#String quotes, use double quotes in the statement (equivalent to 1 single quote in the result)
3. Subquery
select t.tname,
t.deptno,
(select dname from dept where dept.deptno = t.deptno) as deptname #The subquery is in the column
from teacher t
where t.deptno in (select deptno #subquery in the condition
from dept
where dept.deptno = t.deptno
and dept.dname in ('Admissions', 'Manpower'))
4. Multi-table join query
Inner join (equijoin, unequal join, natural join), outer join (left join, right join)
self-connection, cross-connection
– Names of all male teachers in the admissions department (inner link)
Select t.Tname, t.Deptno ,d.Dname From Teacher t
Inner Join Dept d On t.Deptno = d.Deptno
Where d.Dname = 'Admissions' And t.Gender = 'Male'
– All teacher names, departments (outside link)
Select t.Tname, t.Deptno ,d.Dname From Teacher t
left Join Dept d On t.Deptno = d.Deptno
– The names of all teachers and their tutors (self-connection)
Select T1.Tname, T2.Tname As 导师 From Teacher T1
Left Join Teacher T2 On T1.Mgrno = T2.Tno
5. SQL Functions Functions that perform specific operations
Classification: one-line functions, aggregate functions, analytical functions
Single-row function: returns only one value per row of the query.
Categories: Numbers, Characters, Dates, Conversions, Other Functions
– rounding function
Select Round (sal,1) From teacher
–Character function (substr function starts from 1, intercepts 2 bits of trim and removes spaces)
Select Substr (Time, 1, 2), Substr (Time, 0, 2) , substr (Time, 1),
Length(Trim(Tid)) From Teacher
– Date function (dual dummy table) (to get the desired time by calculation)
Select Sysdate+1/4 From dual
– Conversion function
Select To_Char(111111,’999,999’),
To_Number(‘112’),
To_Date(‘1986-12-12’, ‘yyyy-mm-dd’),
to_char (Sysdate,’yyyy-mm-dd hh24:mi:ss’)
From Dual
--nvl conversion function (nvl2 is similar to conditional expressions) (decode is similar to switch in java)
Select t.Sal, t.Comm,
(t.Sal + Nvl(t.Comm, 0)) salary,
(t.Sal + Nvl2(t.Comm, comm+1000, 0 )) Salary 2,
decode(t.Comm, null, 0, 2300, 2500, t.comm) salary 3
From Teacher t
Aggregate functions: return a result based on a set of rows (a column of rows)
Commonly used: avg, min, max, sum, count
Clause keywords: GROUP BY clause HAVING clause
– View data with more than 10 employees in the department (having must be followed by an aggregate function)
select deptno ,Sum (sal),Avg(sal),Count(0),Max(sal),Min(sal)
From teacher
Group By deptno
having count(*) >10 –sal>1000 (wrong)
Analytical functions: Calculate aggregated values from a set of rows. Used to calculate the cumulative ranking of completed aggregations, etc.
– Analytical functions (the difference in the ranking of the three functions)
select tname,deptno,
rank() over(partition by deptno order by sal) rank,–rank名
dense_rank() over(partition by deptno order by sal) dense_rank,
row_number() over(partition by deptno order by sal) row_number
from teacher
6. Union query : The set operator combines the results of two queries into one result
INTERSECT: Returns records common to both queries
UNION\UNION ALL: Returns all records of each query. Union can be deduplicated
MINUS: Returns the records retrieved by the first query minus the records retrieved by the second query
7. Paging query :
Pseudo-column: A pseudo-column is like a table column, but it is not stored in the table. Pseudo-columns can be queried from the table, but their values cannot be inserted, updated, or deleted
ROWID is the storage address of the row in the table, this address can uniquely identify a row in the database, you can use the ROWID pseudo-column to quickly locate a row in the table
ROWNUM is the sequence number of the row in the result set returned by the query and can be used to limit the number of rows returned by the query
– Query top 5 (rownum query based on result set, starting from 1)
select rownum,tname from teacher where rownum<=5
– Query the fifth to tenth place (using subqueries)
select * from
(select rownum as rn ,tname from teacher where rownum<=10) t
where t.rn >=5
– Get information on teachers with the fifth highest salary in the teacher table
select *from
(select teacher.*, dense_rank() over(order by sal desc) rank from teacher)
where rank = 5; (note that it is an analytical function)
– Pagination ideas
– The first layer: add restrictions to get the result set
– Second layer: filter the largest range for the result set
– The third layer: filter the smallest range for the result set (starting from the first few items)
select t1 from
(select t.*,rownum rn from
(select tname,gender,sal from teacher order by sal desc) t
where rownum<=pageIndex*pageSize and gender=’男’) t1 where t1.rn>(pageIndex-1)*pageSize