SQL语言主要分为两个部分,数据定义语言(DDL)和数据操作语言(DML)。
- 数据定义语言(DDL)用于创建或删除表格,也可以定义索引(键),规定表之间的链接、以及表之间的约束等。
- 数据操作语言(DML)用于执行查询、插入、删除、更新记录。
注意:SQL语法不区分大小写。
数据定义语言(DDL)
DDL语句 | 含义 |
---|---|
create database | 创建新数据库 |
drop database | 删除数据库 |
create table | 创建新表 |
alter table | 变更数据库表 |
drop table | 删除表 |
create index | 创建索引 |
drop index | 删除索引 |
数据库和表操作
# 创建新数据库
create database db_name
# 删除数据库
drop database db_name
# 创建新表,列名为'id','name','birth','address','city'
create table student(id integer,name varchar(255),birth date,address varchar(255),city varchar(255))
# 变更数据库表
## 在表中添加列
alter table table_name add column_name datatype
## 修改某一列的数据类型
alter table table_name alter column column_name datatype
## 删除某一列
alter table table_name drop column column_name
# 删除表
drop table table_name
索引
索引有助于加快select查询和where子句,但会减慢update和insert语句的数据输入。索引分为单一索引、唯一索引、组合索引和隐式索引。
单一索引:在表的某一列设置索引
create index index_name on table_name(column_name)
唯一索引:不允许任何重复的值插入到表中
create unique index index_name on table_name(column_name)
组合索引:可以对表中的几列进行索引
create index index_name on table_name(column1,column2)
隐式索引:在创建对象时,由数据库服务器自动创建的索引
# 在student表中对列name添加名称为name_index的索引
create index name_index on student(name)
# 删除索引
drop index index_name
数据操作语言(DML)
主要讲解增删改查四种语句:
select语句用于查询数据库表中的数据
update语句用于更新数据库表中的数据
delete语句用于从数据库表中删除数据
insert into语句用于向数据库表中插入数据
查询语句
# 查询表中所有列
select * from table_name
# 查询表中部分列
select column1,column2,... from table_name
# 关键字distinct返回列中唯一不同的值
select distinct column1,column2 from table_name
# 条件查询where子句
select name,city from student where id > 2
select * from student where id > 2 or city = 'beijing'
select * from student where name = 'marry' and city = 'beijing'
select * from student where (name = 'marry' and city = 'beijing') or id > 2
# 对查询的数据进行排序order by子句
## 按照单一条件升序排列
select name,city from student order by id
## 按照多条件升序排列,先按name字母排列,name相同再按id排列
select name,city from student order by name,id
## 指定排列方式,desc降序排列,asc升序排列
select name,city from student order by name desc,id asc
update语句
update table_name set column1 = 新值 where column2 = 某值
delete语句
用于删除表中的记录
delete from table_name where column_name = 某值
insert into语句
用于向表中插入新的记录
insert into table_name(column1,column2,...) values(value1,value2,...)