1. Create a table
Use the CREATE TABLE clause to create a new table. During the creation process, you must indicate the name of the new table, as well as the names and definitions of the table columns.
Example: Create customers table
SQL语句:CREATE TABLE customers
(
cust_id int NOT NULL AUTO_INCREMENT,
cust_name char(50) NOT NULL,
cust_city char(50) NULL DEFAULT 1,
cust_email char(255) NULL,
PRIMARY KEY(cust_id)
)ENGINE = InnoDB;
AUTO_INCREMENT is an automatic increment. ENGINE = InnoDB is MySQL's internal engine for specifically managing and processing data. When using SELECT statements or other database processing, the engine processes requests internally.
Several common engines:
- InnoDB is a reliable transaction processing engine, it does not support full text search;
- MEMORY is functionally equivalent to MyISAM, but because the data is stored in memory (not disk), the speed is very fast (especially suitable for temporary tables);
- MyISAM is an extremely high-performance engine that supports full-text search, but does not support transaction processing.
note:
- Allowing NULL columns also allows the value of the column not to be given when inserting rows. Columns that do not allow NULL values do not accept rows where the column has no value, that is, when inserting or updating rows, the column must have a value.
- Don't confuse NULL values with empty strings. NULL value is no value, it is not an empty string. If you specify '', this is allowed in the NOT NULL column. The empty string is a valid value, it is not valueless. The NULL value is specified with the keyword NULL instead of the empty string.
2. Update the table
To change the table structure using ALTER TABLE, you must give the changed table name (the table must exist, otherwise an error is reported) and the column name to be changed.
Example 1: Add a column to the vendors table
SQL语句:ALTER TABLE vendors ADD vend_phone CHAR(20);
Example 2: Delete the new column vend_phone
SQL语句:ALTER TABLE vendors DROP COLUMN vend_phone;
Example 3: Define a foreign key
SQL语句:ALTER TABLE orderitems ADD CONSTRAINT fk_orderitems_orders FOREIGN KEY(order_num) REFERENCES orders(order_num);
3. Delete the table
Example: Delete table customers
SQL语句:DROP TABLE customers;
4. Rename the table
Example: Name the table customers1 and rename multiple tables
SQL语句:RENAME TABLE customers TO customers1;