当前位置:网站首页>100 important knowledge points that SQL must master: creating and manipulating tables
100 important knowledge points that SQL must master: creating and manipulating tables
2022-06-30 22:05:00 【Game programming】
17.1 Create table
SQL Not only for table data manipulation , It is also used to perform all operations on databases and tables , package
Including the creation and processing of the table itself .
There are generally two ways to create tables :
Most of the DBMS Both have interactive tools for creating and managing database tables ;
Tables can also be used directly SQL Statement manipulation .
Create a table with a program , have access to SQL Of CREATE TABLE sentence . It should be noted that , send
When you use interactive tools, you actually use SQL sentence . These statements are not written by the user , world
The face tool automatically generates and executes the corresponding SQL sentence ( The same is true when changing an existing table ).
Be careful : Grammatical differences
In different SQL In the implementation , CREATE TABLE The syntax of the statement may be different . Yes
Specific DBMS What syntax is supported , Please refer to the corresponding documentation .
This lesson will not cover all the options available when creating tables , That's beyond the scope of this lesson ,
I'll just give you some basic options . Detailed information description , Please refer to the specific DBMS file .
explain : Various DBMS Specific examples of creating tables
About difference DBMS Of CREATE TABLE Specific examples of statements , Please refer to the appendix A in
The sample table creation script .
17.1.1 Table creation foundation
utilize CREATE TABLE Create table , The following information must be given :
Name of the new table , In keywords CREATE TABLE Then give ;
Table column names and definitions , Separate with commas ;
yes , we have DBMS It is also required to specify the location of the table .
Below SQL Statement to create the... Used in this book Products surface :
Input ▼
CREATE TABLE Products
(
prod_id CHAR(10) NOT NULL,
vend_id CHAR(10) NOT NULL,
prod_name CHAR(254) NOT NULL,
prod_price DECIMAL(8,2) NOT NULL,
prod_desc VARCHAR(1000) NULL
);
analysis ▼
As you can see from the above example , Table name follows CREATE TABLE keyword . The actual table is fixed
The righteous ( All columns ) Enclosed in parentheses , The columns are separated by commas . This watch consists of 5 Line up
become . Each column is defined by column name ( It must be unique in the table ) Start , Data followed by column
type ( Explanation of data types , Please refer to the first 1 course . Besides , appendix C Lists common
Data type and compatibility ). The entire statement ends with a semicolon after parentheses .
Mentioned earlier , Different DBMS Of CREATE TABLE The grammar of is different , This simple foot
Ben also explains this . This statement is used in most DBMS Effective in , But for the DB2,
Must be removed from the last column NULL . This is for different DBMS, To write different
Table reasons for creating scripts ( See Appendix A).
Tips : Statement formatting
Think back in SQL Space ignored in statement . Statement can be entered on a long line , also
It can be divided into many lines , They make no difference . such , You can use the best formula for yourself
Arrange the format of the statement . Ahead CREATE TABLE The statement is SQL Statement formatting
A good example of , The code is arranged on multiple lines , Column definitions are properly indented , more
Easy to read and edit . In what format SQL The statement does not specify , But I highly recommend
Use some sort of indentation format .
Tips : Replace existing table
When creating a new table , The specified table name must not exist , Otherwise it will go wrong . Prevent accidental cover
Cover the existing watch ,SQL It is required to delete the table manually first ( See the following ), however
Then rebuild it , Instead of simply overwriting it with a CREATE TABLE statement .
17.1.2 Use NULL value
The first 4 Class mentioned , NULL Value means no value or missing value . allow NULL Value columns are also allowed to insert
The value of this column is not given when entering a row . Don't allow NULL Columns with values do not accept rows without column values , in
In a word , When inserting or updating rows , The column must have a value .
Each table column is either NULL Column , Or NOT NULL Column , This state is created by the table
The definition of defines . Please see the following example :
Input ▼
CREATE TABLE Orders
(
order_num INTEGER NOT NULL,
order_date DATETIME NOT NULL,
cust_id CHAR(10) NOT NULL
);
analysis ▼
This statement creates the Orders surface . Orders It contains three columns : The order number 、 book
Single date and customer ID. All three columns need , Therefore, the definition of each column contains keywords NOT
NULL . This prevents the insertion of columns without values . If you insert a column without a value , Will return an error ,
And the insertion failed .
The next example will create a hybrid NULL and NOT NULL List of columns :
Input ▼
CREATE TABLE Vendors
(
vend_id CHAR(10) NOT NULL,
vend_name CHAR(50) NOT NULL,
vend_address CHAR(50) ,
vend_city CHAR(50) ,
vend_state CHAR(5) ,
vend_zip CHAR(10) ,
vend_country CHAR(50)
);
analysis ▼
This statement creates the Vendors surface . supplier ID And the name of the supplier
Required , So it's designated as NOT NULL . All the other five columns allow NULL value , So don't specify NOT
NULL . NULL For default settings , If you don't specify NOT NULL , I think the designation is NULL .
Be careful : Appoint NULL
Not specified NOT NULL when , Most of the DBMS It is thought that what is specified is NULL , But not all
Of DBMS It's all like this . some DBMS Require keyword to be specified NULL , If not specified, it will
error . For complete syntax information , Please refer to the specific DBMS file .
Tips : Primary key and NULL value
The first 1 The class has introduced , A primary key is a column whose value uniquely identifies each row in a table . Only not allowed NULL
Value column can be used as primary key , allow NULL The column of the value cannot be used as a unique identity .
Be careful : understand NULL
Don't put the NULL Values are confused with empty strings . NULL Value is no value , Not an empty string .
If specified '' ( Two single quotes , No characters in between ), This is in NOT NULL Column is allowed
Xu's . An empty string is a valid value , It's not worthless . NULL Key for value NULL
Instead of an empty string specifying .
17.1.3 Specify default
SQL Allows you to specify default values , If no value is given when inserting a row ,DBMS The default will be automatically applied
Recognition . The default value is in CREATE TABLE Use the keyword... In the column definition of the statement DEFAULT Appoint .
Please see the following example :
Input ▼
CREATE TABLE OrderItems
(
order_num INTEGER NOT NULL,
order_item INTEGER NOT NULL,
prod_id CHAR(10) NOT NULL,
quantity INTEGER NOT NULL DEFAULT 1,
item_price DECIMAL(8,2) NOT NULL
);
analysis ▼
This statement creates OrderItems surface , Contains the items that make up the order ( The order itself is stored in
Orders In the table ). quantity List the quantity of each item in the order . In this case , this
A column description is added DEFAULT 1 , instructions DBMS, If no quantity is given, use quantity 1 .
Default values are often used for date or timestamp columns . for example , By specifying a function that references the system date
Or variable , Use the system date as the default date .MySQL User specified DEFAULT CURRENT_
DATE() ,Oracle User specified DEFAULT SYSDATE , and SQL Server User specified
DEFAULT GETDATE() . Unfortunately , This command to get the system date is in different
DBMS Most of them are different . surface 17-1 This command is listed in some DBMS Chinese grammar .
If there is no one listed here DBMS, Please refer to the corresponding documentation .
surface 17-1 Get the system date
DBMS function / Variable
DB2 CURRENT_DATE
MySQL CURRENT_DATE()
Oracle SYSDATE
PostgreSQL CURRENT_DATE
SQL Server GETDATE()
SQLite date('now')
Tips : Use DEFAULT instead of NULL value
Many database developers like to use DEFAULT It's worth it, not NULL Column , For the use of
This is especially true for columns of calculation or data grouping .
17.2 Update table
Update table definition , have access to ALTER TABLE sentence . Although all DBMS All support
ALTER TABLE , But what they allow to be updated is very different . Here are the USES ALTER
TABLE Things to consider when .
Ideally , Do not update a table when it contains data . Should be in the table design
During the process, the possible future needs shall be fully considered , Avoid major changes to the structure of the table in the future .
be-all DBMS Are allowed to add columns to existing tables , However, for the data type of the added column
( as well as NULL and DEFAULT Use ) There are limits .
many DBMS Deleting or changing columns in a table is not allowed .
Most of the DBMS Allow renaming columns in a table .
many DBMS Restrict changes to columns already filled with data , For columns not filled with data
There is almost no limit .
It can be seen that , Making changes to existing tables is complex and inconsistent . What changes can be made to the table structure
Change , Please refer to the specific DBMS file .
Use ALTER TABLE Change table structure , The following information must be given :
stay ALTER TABLE Then give the table name to be changed ( The table must exist , Otherwise, it will be wrong );
List what changes to make .
Because adding columns to an existing table may be all DBMS The only operation supported by both , So we take
An example of this :
Input ▼
ALTER TABLE Vendors
ADD vend_phone CHAR(20);
analysis ▼
This statement gives Vendors Add a table named vend_phone The column of , Its data type
by CHAR .
Change or delete columns 、 Add constraints or keys , These operations use a similar syntax .
Be careful , The following example is not for all DBMS Are effective :
Input ▼
ALTER TABLE Vendors
DROP COLUMN vend_phone;
Complex table structure changes generally require manual deletion process , It involves the following steps :
(1) Create a new table with a new column layout ;
(2) Use INSERT SELECT sentence ( A detailed introduction to this statement , Please refer to the first 15
course ) Copy data from old table to new table . If necessary , You can use conversion functions and calculations
Field ;
(3) Verify the new table containing the required data ;
(4) Rename old table ( If determined , You can delete it );
(5) Rename the new table with the original name of the old table ;
(6) According to need , Recreate trigger 、 stored procedure 、 Indexes and foreign keys .
explain : ALTER TABLE and SQLite
SQLite To use ALTER TABLE There are restrictions on what to do . The most important limitation
yes , It doesn't support the use of ALTER TABLE Define primary and foreign keys , These must be created at the beginning
When creating a table, specify .
Be careful : Careful use ALTER TABLE
Use ALTER TABLE Be extremely careful , A full backup should be made before making changes ( surface
Backup of structure and data ). Changes to database tables cannot be undone , If you add unnecessary
Column , Maybe you can't delete them . Similarly , If you delete a column that should not be deleted , Probably
All data in this column will be lost .
17.3 Delete table
Delete table ( Delete the entire table instead of its contents ) It's simple , Use DROP TABLE sentence
that will do :
Input ▼
DROP TABLE CustCopy;
analysis ▼
This statement deletes CustCopy surface ( The first 15 Created in class ). There is no confirmation step for deleting the table ,
It can't be revoked , Executing this statement will permanently delete the table .
Tips : Use relationship rules to prevent accidental deletion
many DBMS Allow enforcement of relevant rules , Prevent deleting tables associated with other tables . stay
When implementing these rules , If a table is published DROP TABLE sentence , And the table is
Part of a relationship , be DBMS Will prevent this statement from executing , Until the relationship is deleted
Until . If allowed , These options should be enabled , It prevents accidental deletion of useful tables .
17.4 rename table
Every DBMS Support for table renaming is different . For this operation , There is no strict
standard .DB2、MariaDB、MySQL、Oracle and PostgreSQL The user to use RENAME
sentence ,SQL Server The user to use sp_rename stored procedure ,SQLite The user to use ALTER
TABLE sentence .
The basic syntax of all renaming operations requires specifying the old table name and the new table name . however , There is
DBMS Realize the difference . About specific grammar , Please refer to the corresponding DBMS file .
author : Guge academic
Game programming , A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome Kernel browser .
边栏推荐
- Go Web 编程入门: 一探优秀测试库 GoConvey
- ML&DL:机器学习和深度学习中超参数优化的简介、评估指标、过拟合现象、常用的调参优化方法之详细攻略
- 1-18 create the most basic express server & API module for creating routes
- Open the jupyter notebook/lab and FAQ & settings on the remote server with the local browser
- 1-20 pre inspection request
- Is the stock account opened in qiniu safe? How to apply for a low commission stock account?
- 1-2 install and configure MySQL related software
- Document layout analysis: a comprehensive survey 2019 paper learning summary
- Is it difficult to get a certified equipment supervisor? What is the relationship with the supervising engineer?
- [backtracking] full arrangement II leetcode47
猜你喜欢

1-2 install and configure MySQL related software

Which direction should college students choose to find jobs after graduation?

《安富莱嵌入式周报》第271期:2022.06.20--2022.06.26

谈谈数字化转型的几个关键问题

Nacos部署及使用

Domestic database disorder

十个最为戳心测试/开程序员笑话,念茫茫人海,该如何寻觅?

Zhoushaojian, rare

国产数据库乱象
![[introduction to MySQL] the first conversation · first time in the](/img/73/cc85eb469384c3df94479318293c6f.png)
[introduction to MySQL] the first conversation · first time in the "database" Mainland
随机推荐
The programmer's girlfriend gave me a fatigue driving test
vncserver: Failed command ‘/etc/X11/Xvnc-session‘: 256!
Troubleshooting the problem of pytorch geometric torch scatter and torch spark installation errors
国产数据库乱象
Uniapp life cycle / route jump
《安富莱嵌入式周报》第271期:2022.06.20--2022.06.26
Femas:云原生多运行时微服务框架
Analysis of doctor Aifen's incident
Is there a shortage? No need to download the free online resources! 2022 favorites must have it!
Modify the name of the launched applet
Anfulai embedded weekly report no. 270: June 13, 2022 to June 19, 2022
吴恩达的机器学习适合入门吗?
1-10 respond to client content according to different URLs
The Jenkins download Plug-in can't be downloaded. Solution
[introduction to MySQL] the first conversation · first time in the "database" Mainland
"Trust machine" empowers development
1-17 express中间件
Label Contrastive Coding based Graph Neural Network for Graph Classification
Vite2 is compatible with lower versions of chrome (such as Sogou 80). Some grammars requiring higher versions are processed through polyfills
机器学习中如何使用数据集?