基礎sql語句大全

前言

因爲最近要考ocp(全英文考試,所以下文也會中英夾雜,側重oracle標準。),又要把大學學過的數據庫撿起來。特開此文整理基礎sql語句語法和注意事項。
所有示例代碼均來自oracle官方教材。參考資料:數據庫系統教程和oracle提供的官方教材。

一人書寫這麼多內容,難免有錯,歡迎大家留言。

SQL語句概述

1970年,美國IBM研究中心的E.F.Codd提出關係模型,拉開了未來五十年經久不衰的關係數據庫的帷幕。
SQL原來是指“結構化查詢語句Structured Query Language”,經過不斷髮展,已經不表示任何具體的縮寫含義,成爲一個通用標準。
SQL主要包括:
1. DDL(數據定義語言 data definition language ):定義基本表,視圖,索引等結構。
2. DML(數據操作語言 data manipulation language ):分爲數據查詢和數據更新(插入、刪除、修改)
3. DCL(數據權限管理語句data control language):對基本表和視圖的授權、完整性規則的描述。事務控制語句也可以包括在這裏。
4. 事務控制管理語句(transaction control)
5. 嵌入式SQL的使用
SQL語句組成部分

示例所用E-R圖

不看懂也沒關係,也不影響語法學習。
E-R圖:Human Resources (HR) Schema人力資源計劃
HR

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爲小數位數

RAW: 固定長度的二進制數據 最大長度2000 bytes 可存放多媒體圖象聲音等
LONG RAW: 可變長度的二進制數據 最大長度2G 同上
CLOB: 字符數據 最大長度4G
BLOB: 二進制數據 最大長度4G
BFILE: 存放在數據庫外的二進制數據 最大長度4G
ROWID: 數據表中記錄的唯一行號 10 bytes ********.****.****格式,*爲0或1

數據類型

第一章 DDL:Data Definition Language

數據庫對象
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,//段名+數據類型+約束名+約束類型

• You specify:
– The table name
– The column name, column data type, and column size
• Create the table:例子

CREATE TABLE dept//表名
		(deptno	    	NUMBER(2)//字段名和數據類型,
		dname					VARCHAR2(14),
		loc						VARCHAR2(13) NOT NULL,//非空
		create_date 		DATE DEFAULT SYSDATE);

• Confirm table creation:

DESCRIBE 表名;//查看錶的結構(字段和類型)

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. NOT NULL Constraint非空約束:Ensures that null values are not permitted for the column:
  2. 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. PRIMARY KEY Constraint主鍵約束:非空且唯一
  2. 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));

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從表改爲空,主表刪除
5. CHECK Constraint校驗約束
• It defines a condition that each row must satisfy.
• The following expressions are not allowed:
– References to CURRVAL, NEXTVAL, LEVEL, and ROWNUM pseudocolumns
– Calls to SYSDATE, UID, USER, and USERENV functions
– Queries that refer to other values in other rows

salary NUMBER(2) 
CONSTRAINT emp_salary_min CHECK (salary > 0);//使用整數校驗

Violating Constraint違反約束

UPDATE		employees//更新從表employess數據
SET				department_id = 55//報錯291,55在主表department中未出現
WHERE		department_id = 110;
You cannot delete a row that contains a primary key that is used as a foreign key in another table.
DELETE FROM departments刪除主表中數據
WHERE department_id = 60;錯誤

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;匹配字段

• 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;

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));

• 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));

• 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));

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;//設定爲只讀表,不允許修改
--perform table maintenance and then return table back to read/write mode
ALTER TABLE employees READ WRITE;

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 表名;   //結構和數據全部刪除,存在回收站,還可以閃回操作

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]];

· 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

· 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 視圖名;刪除視圖

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) ]內存一次性裝在幾個,系統崩潰後出錯

引用序列號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) ]

· 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字段,)和表的字段對應

在這裏插入圖片描述

Drop index 索引名;刪除

Synonym同義詞

複雜的對象設置一個簡單的名稱
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

CREATE 	[PUBLIC]  SYNONYM   synonym
FOR	object;

DROP SYNONYM 同義詞;刪除
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章