SQL資料定義

2021-09-11 18:00:39 字數 3468 閱讀 4438

定義模式

create schema test autorization zhang 

create table tab1(col1 smallint,

col2 int,

col3 char(20),

col4 numeric(10,3),

col5 decimal(5,2));

刪除模式
drop schema 《模式名》
drop

schema zhang cascade

資料型別

資料型別

含義char(n)

長度為n的定長字串

varchar(n)

最大長度為n的變長字串

int長整數(也可以寫作integer)

smallint

短整數numeric(p,d)

定點數,由p位數字(不包括符號、小數點)組成,小數後面有d位數字

real

取決於機器精度的浮點數

double precision

取決於機器精度的雙精度浮點數

float(n)

浮點數,精度至少為n位數字

date

日期,包含年、月、日,格式為yyyy-mm-dd

time

時間,包含一日的時、分、秒,格式為hh:mm:ss

基本表定義

create

table

《表名》

(《列名》

《資料型別》

[《列級完整性約束條件》

][,《列名》

《資料型別》

[《列級完整性約束條件》

]] …

[,《表級完整性約束條件》

] );

create

table student

(sno char(9

)primary

key,

/*列級完整性約束條件*/

sname char(20

)unique

,/*sname取唯一值*/

s*** char(2

),sage smallint

, sdept char(20

));

建立乙個「課程」表course

create table course

(cno char(4) primary key,

cname char(40),

cpno char(4), /*先修課*/

ccredit smallint,

foreign key (cpno) references course(cno)); /*cpno是外碼被參照表是course、被參照列是cno*/

建立乙個「學生選課」表sc:

create

table sc

(sno char(9

),cno char(4

),grade smallint

,primary

key(sno,cno)

,foreign

key(sno)

references student(sno)

,foreign

key(cno)

references course(cno)

);

修改基本表
新增那一列一律是空值;

alter

table

《表名》

[add

《新列名》

《資料型別》

[ 完整性約束 ]][

drop

《完整性約束名》][

alter

column

《列名》

《資料型別》

];

向student表增加「入學時間」列,其資料型別為日期型;

alter table student add s_entrance date;
將年齡的資料型別由字元型(假設原來的資料型別是字元型)改為整數。

alter

table student change sage sage int

;

增加課程名稱必須取唯一值的約束條件。

alter table course add unique(cname);
刪除基本表
drop

table

《表名》[restrict

|cascade

];

刪除student表

drop

table student casecade;

建立索引的目的

加快查詢速度;

建立索引

create

[unique

][cluster]

index

《索引名》

on《表名》

(《列名》

[《次序》][

,《列名》

[《次序》

]]…);

在student表的sname(姓名)列上建立乙個聚簇索引:

create cluster index stusname on student(sname);
在student表的sname(姓名)列上建立乙個聚簇索引

在最經常查詢的列上建立聚簇索引以提高查詢效率;

乙個基本表上最多只能建立乙個聚簇索引;

經常更新的列不宜建立聚簇索引;

為學生-課程資料庫中的student,course,sc三個表建立索引。

create unique index stusno on student(sno);     /*student表按學號公升序建唯一索引*/

create unique index coucno on course(cno); /*course表按課程號公升序建唯一索引*/

create unique index scno on sc(sno asc,cno desc); /*sc表按學號公升序和課程號降序建唯一索引*/

刪除索引

刪除索引時,系統會從資料字典中刪去有關該索引的

描述。

drop index 《索引名》;
刪除student表的stusname索引

drop

index stusname on student;

SQL 資料定義

定義模式 如果沒有指定 模式名 那麼 模式名 隱含為 使用者名稱 create schema 模式名 aothorization 使用者名稱 example 為使用者 wang 定義乙個學生 課程模式s t create schema authorization wang 刪除模式 drop sch...

SQL之資料定義

sql是關聯式資料庫標準語言,主要功能有資料定義 資料查詢 資料操縱和資料控制。其特點是高度非過程化 綜合統 一 物件導向操作 對應資料系統結構的 模式結構,其包含的檢視和部分基本表與外模式相對應 基本表與模式相對應 索引與內模式相對應。sql 有一些語法約定符號,如下 方括號 中的內容為任選項,根...

SQL之定義資料

sql 2012使用 2020.3.26 今天開始學習sql的打碼,主要學習了資料定義中的定義資料庫,定義基本表 約束條件 修改基本表 刪除 定義索引的操作。首先,由於使用的教材中的例題基本上全是大寫字母,所以我打碼的時候要左手一直按著shift鍵 好累 後來直接開了caps lock,然而這並沒有...