# SQL Drop

## 2. 前言

``````DROP TABLE IF EXISTS imooc_user;
CREATE TABLE imooc_user
(
age int
);
ALTER TABLE imooc_user ADD INDEX age_index(age);
``````

``````CREATE TABLE imooc_user
(
age int
);
CREATE INDEX age_index ON imooc_user(age);
``````

## 3. 删除数据库

Drop 指令可用于删除数据库。

``````DROP DATABASE [db_name];
``````

### 3.1 例1 删除 imooc

``````DROP DATABASE imooc;
``````

## 4. 删除数据表

``````DROP TABLE [table_name];
``````

### 4.1 例2 删除 imooc_user

``````DROP TABLE imooc_user;
``````

## 5. 清空表数据

Truncate 是另外一种实用的指令，可以在`保留数据表`的情况下清空数据表数据。

``````TRUNCATE TABLE [table_name];
``````

### 5.1 例3 清空 imooc_user 数据

``````TRUNCATE TABLE imooc_user;
``````

## 6. 删除表字段

Drop 可与 Alter 指令搭配来删除数据表字段。

``````ALTER TABLE [table_name] DROP [col];
``````

### 6.1 例4 删除 age 字段

``````ALTER TABLE imooc_user DROP age;
``````

``````+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| username | varchar(20) | YES  |     | <null>  |       |
+----------+-------------+------+-----+---------+-------+
``````

## 7. 删除索引

Drop 还可与 Alter 指令搭配用来删除索引。

``````ALTER TABLE [table_name] DROP INDEX [index_name];
``````

PostgreSQL 删除索引语法如下：

``````DROP INDEX [index_name];
``````

### 7.1 例5 删除 age_index 索引

``````ALTER TABLE imooc_user DROP INDEX age_index;
``````

PostgreSQL 略有不同，语句如下：

``````DROP INDEX age_index;
``````

## 8. 删除视图

``````DROP VIEW [view_name];
``````

## 9. 小结

• Drop 是一个非常强大却又非常简单的指令，想要熟练地使用并不难，但是如何正确地使用、保证数据库的安全却不简单。
{"ft_lang_label":"__label__zh","ft_lang_prob":0.84696645,"math_prob":0.41032463,"size":2154,"snap":"2022-05-2022-21","text_gpt3_token_len":1135,"char_repetition_ratio":0.21813953,"word_repetition_ratio":0.053846154,"special_character_ratio":0.31104922,"punctuation_ratio":0.10897436,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9556081,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-05-24T04:56:11Z\",\"WARC-Record-ID\":\"<urn:uuid:9e2ffe8b-5365-4f31-bdcc-19aed43d1419>\",\"Content-Length\":\"136882\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:2fe65cec-0dab-48ae-95e1-559a056287f8>\",\"WARC-Concurrent-To\":\"<urn:uuid:5f3c615d-6964-4219-a21f-556cc4212ea1>\",\"WARC-IP-Address\":\"117.121.101.134\",\"WARC-Target-URI\":\"http://www.imooc.com/wiki/sqlbase/sqldrop.html\",\"WARC-Payload-Digest\":\"sha1:D24SVYO6OAQWSEM6TANHGDXBYQNREJ44\",\"WARC-Block-Digest\":\"sha1:BMUC6HNW3FGWNOR7FIOIRT2MX4TLA2S3\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-21/CC-MAIN-2022-21_segments_1652662564830.55_warc_CC-MAIN-20220524045003-20220524075003-00166.warc.gz\"}"}