[SQL must know and know] - Lesson 17 Create and manipulate tables

Table of contents

17.1 Creating tables

        17.1.1 Table Creation Basics

        replace existing table

        17.1.2 Using NULL values

        Primary keys and NULL values

        understand NULL

        17.1.3 Specifying default values

        Use DEFAULT instead of NULL values

17.2 Update table

        Be careful with ALTER TABLE

17.3 Dropping tables

        Use relationship rules to prevent accidental deletion

17.4 Renaming tables

17.5 Summary


        This lesson teaches the basics of creating, altering, and dropping tables.

17.1 Creating tables

        To create a table with a program, you can use the SQL CREATE TABLE statement. It should be noted that when using interactive tools, you are actually using SQL statements. These statements are not written by the user, the interface tool will automatically generate and execute the corresponding SQL statement (the same is true when changing an existing table ).

        17.1.1 Table Creation Basics

        To create a table using CREATE TABLE, the following information must be given:

  • The name of the new table, given after the keyword CREATE TABLE;
  • The names and definitions of the table columns, separated by commas;
  • Some DBMS also require specifying the location of the table.

        The following SQL statement creates the Products table used in this book:

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
);

        The syntax for CREATE TABLE varies between DBMSs, and this simple script illustrates that. This statement is valid in Oracle, PostgreSQL, SQL Server and SQLite, while for MySQL, varchar must be replaced with text; for DB2, NULL must be stripped from the last column. This is why different table creation scripts are written for different DBMSs.


        replace existing table

        When creating a new table, the specified table name must not exist, otherwise an error will occur. To prevent accidental overwriting of an existing table, SQL requires that the table be first dropped manually (see below) and then recreated instead of simply overwriting it with a CREATE TABLE statement.


        17.1.2 Using NULL values

        A NULL value is no value or missing value. Columns that allow NULL values ​​also allow rows to be inserted without a value for that column. A column that does not allow NULL values ​​does not accept rows without a value for the column, in other words, when a row is inserted or updated, the column must have a value.

        Each table column is either a NULL column or a NOT NULL column, which state is specified by the table definition when it is created.

CREATE TABLE Orders
(
    order_num INTEGER NOT NULL,
    order_date DATETIME NOT NULL,
    cust_id CHAR(10) NOT NULL
);

        If a column without a value is inserted, an error will be returned and the insert will fail. The next example will create a table with a mix of NULL and NOT NULL columns:

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)
);

        Primary keys and NULL values

        As introduced in Lesson 1, a primary key is a column whose value uniquely identifies each row in a table. Only columns that do not allow NULL values ​​can be used as primary keys, and columns that allow NULL values ​​cannot be used as unique identifiers.


        understand NULL

        Do not confuse NULL values ​​with empty strings. A NULL value is no value, not an empty string. This is allowed in NOT NULL columns if you specify '' (two single quotes with no characters between them). An empty string is a valid value, it's not a null value. NULL values ​​are specified with the keyword NULL rather than an empty string.


        17.1.3 Specifying default values

        SQL allows specifying a default value, and if no value is given when inserting a row, the DBMS will automatically assume the default value. The default value is specified with the keyword DEFAULT in the column definition of the CREATE TABLE statement.

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
);

        Default values ​​are often used for date or timestamp columns.


        Use DEFAULT instead of NULL values

        Many database developers prefer to use DEFAULT values ​​instead of NULL columns, especially for columns used for calculations or data grouping. 


17.2 Update table

        To update a table definition, you can use the ALTER TABLE statement. Here are some things to consider when using ALTER TABLE:

  • Ideally, don't update the table while it contains data . The possible future needs should be fully considered in the table design process to avoid major changes to the table structure in the future.
  • All DBMSs allow adding columns to existing tables, but there are restrictions on the data type of the added columns (and the use of NULL and DEFAULT).
  • Many DBMSs do not allow dropping or changing columns in a table.
  • Most DBMSs allow renaming of columns in a table.
  • Many DBMSs restrict changes to columns that are already filled with data, and have few restrictions on columns that are not.

        To use ALTER TABLE to change the table structure, the following information must be given:

  • Give the name of the table to be changed after ALTER TABLE (the table must exist, otherwise an error will occur);
  • List what changes to make.

        Since adding a column to an existing table is probably the only operation supported by any DBMS, let's take this example:

ALTER TABLE Vendors ADD vend_phone CHAR(20);

        This statement adds a column named vend_phone to the Vendors table, whose data type is CHAR.

        Altering or dropping columns, adding constraints, or adding keys also use similar syntax (note that the examples below are not valid for all DBMSs).

ALTER TABLE Vendors DROP COLUMN vend_phone;

        Complex table structure changes generally require a manual drop process, which involves the following steps:

  • Create a new table with the new column layout;
  • Use the INSERT SELECT statement (for a detailed introduction to this statement, see Lesson 15) to copy data from the old table to the new table. If necessary, conversion functions and calculated fields can be used;
  • Check out the new table containing the required data;
  • Rename the old table (you can drop it if you are sure);
  • Rename the new table with the original name of the old table;
  • Recreate triggers, stored procedures, indexes, and foreign keys as needed.

        Be careful with ALTER TABLE

        Use ALTER TABLE to be extremely careful , and you should make a complete backup (table structure and data backup) before making changes. Changes to database tables cannot be undone, and if unnecessary columns are added, they may not be dropped. Similarly, if you delete a column that should not be deleted, you may lose all data in that column.


17.3 Dropping tables

        Dropping a table (deleting the entire table rather than its contents) is as simple as using the DROP TABLE statement.

DROP TABLE tableName;

       Deleting a table is not confirmed and cannot be undone. Executing this statement will permanently delete the table.

        For related statements about deleting tables, see the blog: Oracle Common SQL Statements


        Use relationship rules to prevent accidental deletion

        Many DBMSs allow rules to be enforced that prevent dropping tables that are associated with other tables. In enforcing these rules, if a DROP TABLE statement is issued on a table that is part of a relationship, the DBMS blocks execution of the statement until the relationship is dropped. If allowed, these options should be enabled, it prevents accidentally dropping useful tables.


17.4 Renaming tables

        Each DBMS supports table renaming differently. For this operation, no strict standard exists. The basic syntax for all rename operations requires specifying the old and new table names.


17.5 Summary

        CREATE TABLE is used to create a new table, ALTER TABLE is used to change table columns (or other objects such as constraints or indexes), and DROP TABLE is used to completely drop a table. These statements must be used with care and should be used after backup.

Guess you like

Origin blog.csdn.net/qq_57163366/article/details/130200382