前言
SQL語句概述
示例所用E-R圖
Oracle經常使用數據類型規定
第一章 DDL:Data Definition Language
基本表的建立、修改、刪除
View視圖
Sequence序列號
Index索引
Synonym同義詞
前言
由於最近要考ocp(全英文考試,因此下文也會中英夾雜,側重oracle標準。),又要把大學學過的數據庫撿起來。特開此文整理基礎sql語句語法和注意事項。
全部示例代碼均來自oracle官方教材。參考資料:數據庫系統教程和oracle提供的官方教材。sql
一人書寫這麼多內容,不免有錯,歡迎你們留言。數據庫
SQL語句概述
1970年,美國IBM研究中心的E.F.Codd提出關係模型,拉開了將來五十年經久不衰的關係數據庫的帷幕。
SQL原來是指「結構化查詢語句Structured Query Language」,通過不斷髮展,已經不表示任何具體的縮寫含義,成爲一個通用標準。
SQL主要包括:express
示例所用E-R圖
不看懂也不要緊,也不影響語法學習。
E-R圖:Human Resources (HR) Schema人力資源計劃api
Oracle經常使用數據類型規定
CHAR: 固定長度字符串 最大長度2000 bytes
VARCHAR2: 可變長度的字符串 最大長度4000 bytes 可作索引的最大長度749
NCHAR: 根據字符集而定的固定長度字符串 最大長度2000 bytes
NVARCHAR2: 根據字符集而定的可變長度字符串 最大長度4000 bytes
DATE: 日期(日-月-年) DD-MM-YY(HH-MI-SS) 通過嚴格測試,無千蟲問題
LONG :超長字符串 最大長度2G(231-1) 足夠存儲大部頭著做
NUMBER(P,S) 數字類型 P爲總位數,S爲小數位數oracle
RAW: 固定長度的二進制數據 最大長度2000 bytes 可存放多媒體圖象聲音等
LONG RAW: 可變長度的二進制數據 最大長度2G 同上
CLOB: 字符數據 最大長度4G
BLOB: 二進制數據 最大長度4G
BFILE: 存放在數據庫外的二進制數據 最大長度4G
ROWID: 數據表中記錄的惟一行號 10 bytes ****..格式,*爲0或1app
第一章 DDL:Data Definition Languageide
Naming Rules命名規則
Table names and column names must:
• Begin with a letter字母開始
• Be 1–30 characters long
• Contain only A–Z, a–z, 0–9, _, $, and #【命名容許使用字符】
• Not duplicate the name of another object owned by the same user【同一用戶下不一樣對象不能命相同的名】
• Not be an Oracle server–reserved word不使用oracle保留字【例如table等常見英文單詞】學習
基本表的建立、修改、刪除
CREATE TABLE Statement
• You must have:
– The CREATE TABLE privilege
– A storage area測試
CREATE TABLE [schema.指定用戶]table
(column datatype [DEFAULT expr][, ...]) [CONSTRAINT constraint_name] constraint_type,;
//段名+數據類型+約束名+約束類型
1
2
3
• You specify:
– The table name
– The column name, column data type, and column size
• Create the table:例子ui
CREATE TABLE dept//表名
(deptno NUMBER(2)//字段名和數據類型,
dname VARCHAR2(14),
loc VARCHAR2(13) NOT NULL,//非空
create_date DATE DEFAULT SYSDATE);
1
2
3
4
5
• Confirm table creation:
DESCRIBE 表名;//查看錶的結構(字段和類型)
1
Constraints約束
• Constraints enforce rules at the table level.
• Constraints ensure the consistency and integrity of the database.
• The following constraint types are valid:
– NOT NULL非空
– UNIQUE惟一
– PRIMARY KEY主鍵
– FOREIGN KEY外鍵
– CHECK校驗
• View a constraint in the data dictionary.數據字典中查看
• You can name a constraint or the Oracle server generates a name by using the SYS_Cn format.約束命名
• Create a constraint at either of the following times:建立約束的時間
– At the same time as the creation of the table在建立表的同時
– After the creation of the table建立表以後
//Example of a column-level constraint
CREATE TABLE employees(
employee_id NUMBER(6) CONSTRAINT emp_emp_id_pk約束名稱 PRIMARY KEY,
first_name VARCHAR2(20), ...);
//Example of a table-level constraint:
CREATE TABLE employees(
employee_id NUMBER(6),
first_name VARCHAR2(20),
job_id VARCHAR2(10) NOT NULL,
CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID指定));
1
2
3
4
5
6
7
8
9
10
NOT NULL Constraint非空約束:Ensures that null values are not permitted for the column:
UNIQUE Constraint惟一值,無重複:Defined at either the table level or the column level:
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),//unique約束
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
CONSTRAINT emp_email_uk UNIQUE(email)字段名;
1
2
3
4
5
6
7
8
PRIMARY KEY Constraint主鍵約束:非空且惟一
FOREIGN KEY Constraint:外鍵Defined at either the table level or the column level:
CREATE TABLE employees(
employee_id NUMBER(6),
last_name VARCHAR2(25) NOT NULL,
email VARCHAR2(25),
salary NUMBER(8,2),
commission_pct NUMBER(2,2),
hire_date DATE NOT NULL,
department_id NUMBER(4),
CONSTRAINT emp_dept_fk FOREIGN KEY (department_id)//外鍵:關係數據庫的參照完整性,定義從表
REFERENCES departments(department_id),引用主表
CONSTRAINT emp_email_uk UNIQUE(email));
1
2
3
4
5
6
7
8
9
10
11
KEY Constraint: Keywords含有外鍵從表
• FOREIGN KEY: Defines the column in the child table at the table-constraint level
• REFERENCES: Identifies the table and column in the parent table
• ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent table is deleted
主表刪除時,主從表都刪除記錄
• ON DELETE SET NULL: Converts dependent foreign key values to null從表改成空,主表刪除
salary NUMBER(2)
CONSTRAINT emp_salary_min CHECK (salary > 0);//使用整數校驗
1
2
Violating Constraint違反約束
UPDATE employees//更新從表employess數據
SET department_id = 55//報錯291,55在主表department中未出現
WHERE department_id = 110;
1
2
3
You cannot delete a row that contains a primary key that is used as a foreign key in another table.
1
DELETE FROM departments刪除主表中數據
WHERE department_id = 60;錯誤
1
2
Creating a Table Using a Subquery使用子查詢,用另外表添加數據
• Create a table and insert rows by combining the CREATE TABLE statement and the AS subquery option.
CREATE TABLE table
[(column, column...)]
AS subquery;匹配字段
1
2
3
• Match the number of specified columns to the number of subquery columns.
• Define columns with column names and default values.
Creating a Table Using a Subquery
CREATE TABLE dept80
AS
SELECT employee_id, last_name,salary*12 ANNSAL, hire_date
FROM employees
WHERE department_id = 80;
1
2
3
4
5
6
ALTER TABLE Statement修改表的結構
Use the ALTER TABLE statement to:
• Add a new column
• Modify an existing column definition
• Define a default value for the new column
• Drop a column
• Rename a column
• Change table to read-only status
Use the ALTER TABLE statement to add, modify, or drop columns:
Adding a Column增長字段
• You use the ADD clause to add columns:
ALTER TABLE dept80
ADD (job_id VARCHAR2(9));
1
2
• The new column becomes the last column:全部值自動設置爲空
Modifying a Column修改字段
• You can change a column’s data type, size, and default value.
ALTER TABLE dept80
MODIFY (last_name VARCHAR2(30));
1
2
• A change to the default value affects only subsequent insertions to the table.
Dropping a Column刪除字段
Use the DROP COLUMN clause to drop columns that you no longer need from the table:
ALTER TABLE dept80
MODIFY (last_name VARCHAR2(30));
1
2
SET UNUSED Option某個字段設置不可用
• You use the SET UNUSED option to mark one or more columns as unused.
• You use the DROP UNUSED COLUMNS option to remove the columns that are marked as unused.
• You can specify the ONLINE keyword to indicate that DML operations on the table will be allowed while marking the column or columns UNUSED.
Read-Only Tables只讀表
You can use the ALTER TABLE syntax to:
• Put a table in read-only mode, which prevents DDL or DML changes during table maintenance
• Put the table back into read/write mode
ALTER TABLE employees READ ONLY;//設定爲只讀表,不容許修改
1
--perform table maintenance and then return table back to read/write mode
1
ALTER TABLE employees READ WRITE;
1
Dropping a Table刪除表
• Moves a table to the recycle bin
• Removes the table and all its data entirely if the PURGE clause is specified
• Invalidates dependent objects and removes object privileges on the table
DROP TABLE 表名; //結構和數據所有刪除,存在回收站,還能夠閃回操做
1
View視圖
建立在一個表上的視窗,不存放數據,邏輯視窗
Advantage of views:
to restrict data access
to make complex queries easy
to provide data independence
to present different views of the same data
兩種視圖:簡單視圖和複雜視圖
Create view建立視圖
You embed a subquery in the CREATE VIEW statement:
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view識圖名 [(alias[, alias] ...) ]
AS subquey子查詢
[WITH CHECK OPTION [CONSTRAINT constraint] ]
[WITH READ ONLY [CONSTRAINT constraint]];
1
2
3
4
· Create the EMPVU80 view,which contains details of the employees in department 80:
CREATE VIEW empvu80
AS SELECT employee_id, last_name,salary
FROM employees
WHERE department id=80;
1
2
3
4
· Describe the structure of the view by using the SQL*Plus DESCRIBE command:
DESCRIBE emp vu 80
The subquery can contain complex SELECT syntax
Modify view 修改視圖:
create or replace view 識圖名 as 子查詢
· Modify the EMPVU80 view by using a CREATE OR REPLACE VIEW clause.Add an alias for each columnname:
· Column aliases in the CREATE OR REPLACE VIEW clause are listed in the same order as the columns in the subquery.
Complex view 複雜視圖:使用子查詢鏈接
Create a complex view that contains group functions to display values from two tables:
不建議使用DML語句修改視圖,WITH READ ONLY;
· You can usually perform DML operations on simple views.
· You can not remove a row if the view contains the following:
Group functions
A GROUP BY clause
The DISTINCT keyword
The pseudo column ROWNUM keyword
You can not modify data in a view if it contains:
· Group functions
· A GROUP BY clause
· The DISTINCT keyword
· The pseudo column ROWNUM keyword
· Columns defined by expressions
You can not add data through a view if the view includes:
· The pseudo column ROWNUM keyword
· Group functions
· A GROUP BY clause
· The DISTINCT keyword
· Columns defined by expressions
· NOT NULL columns in the base tables that are not selected by the view
Drop view 視圖名;刪除視圖
1
Sequence序列號
A sequence:
Can automatically generate unique numbers
is a shareable object
Can be used to create a primary key value
Replaces application code
Speeds up the efficiency of accessing sequence values when cached in memory
CREATE SEQUENCE 序列名
[INCREMENT BY n]增加值
[START WITH n]第一個值
[(MAXVALUE n | NOMAXVALUE)]最大
[(MINVALUE n | NOMINVALUE)]是否包含最小
[(CYCLE | NOCYCLE) ]循環使用,不建議
[(CACHE n | NOCACHE) ]內存一次性裝在幾個,系統崩潰後出錯
1
2
3
4
5
6
7
引用序列號NEXTVAL and CURRVAL Pseudocolun
· NEXTVAL returns the next available sequence value.It returns a unique value everytime it is referenced, even for different users.
· CURRVAL obtains the current sequence value.
· NEXTVAL must be issued for that sequence before CURRVAL contains a value.
Insert a new department named「Support」in location ID 2500:
View the current value for the DEPT_DEPTID_SEQ sequence:
Caching Sequence Values
· Caching sequence values in memory gives faster access to those values.
· Gaps in sequence values can occur when:序列號斷層
—A rollback occurs
—The system crashes
—A sequence is used in another table
Guidelines for Modifying a Sequence
ALTER SEQUENCE 序列名
[INCREMENT BY n]
[START WITH n]不能修改初始值,必須先刪除
[(MAXVALUE n | NOMAXVALUE)]
[(MINVALUE n | NOMINVALUE)]
[(CYCLE | NOCYCLE) ]
[(CACHE n | NOCACHE) ]
1
2
3
4
5
6
7
· You must be the owner or have the ALTER privilege for the sequence.
· Only future sequence numbers are affected.
· The sequence must be dropped and re-created to restart the sequence at a different number.
· Some validation is performed.
· To remove a sequence, use the DROP statement:
DROP SEQUENCE dept_dept id_seq;
Index索引
An index:樹狀結構,單獨存儲,
· is a schema object
· Can be used by the Oracle server to speed up the retrieval of rows by using a pointer
· Can reduce disk input/output(I/O) by using a rapid path access method to locate data quickly
· is independent of the table that it indexes
· is used and maintained automatically by the oracle server
· 自動建立:主鍵或unique的字段
Automatically:A unique index is created automatically when you define a PRIMARY KEY or UNIQUE constraint in a table definition.
· 手動建立Manually:Users can create nonunique indexes on columns to speed up access to the rows.
create [unique][bitmap]index 索引名
on table表名(column字段,…)和表的字段對應
1
2
Drop index 索引名;刪除1Synonym同義詞複雜的對象設置一個簡單的名稱Simplify access to objects by creating a synonym(another name for an object) .With synonyms, you can:· Create an easier reference to a table that is owned by another user· Shorten lengthy object names————————————————