SQL must know part 4

Lesson 15

        This lesson describes how to use SQL's INSERT statement to insert data into a table

        The main code is as follows:

select *
into Custcopy
from Customers;
insert into Custcopy(cust_id,
					 cust_name,	
					 cust_address,
					 cust_city,
					 cust_state,
					 cust_zip,
					 cust_country,
					 cust_contact,
					 cust_email)
values('1000000006',
	   'Toy Land',
	   '123 Any Street',
	   'New York',
	   'NEW',
	   '11111',
	   'USA',
	   NULL,
	   NULL);
insert into Custcopy(cust_id,
					 cust_name,
					 cust_address,
					 cust_city,
					 cust_state,
					 cust_zip,
					 cust_country)
values('1000000006',
	   'Toy Land',
	   '123 Any Street',
	   'New York',
	   'NEW',
	   '11111',
	   'USA');
insert into Custcopy(cust_id,
					 cust_contact,
					 cust_email,
					 cust_name,
					 cust_address,
					 cust_city,
					 cust_state,
					 cust_zip,
					 cust_country)
select cust_id,
	   cust_contact,
	   cust_email,
	   cust_name,
	   cust_address,
	   cust_city,
	   cust_state,
	   cust_zip,
	   cust_country
from CustNew;

        1. INSERT is used to insert (or add) rows into a database table. There are several ways to insert

  • insert complete row
  • insert part of a row
  • Insert the results of some queries

        2. Use of INSERT statements may require specific security privileges in the client/server DBMS

        3. When providing column names, VALUES must match the specified column names in the specified order, and a value must be given to each column listed

        4. If the definition of the table allows, some columns can be omitted in the INSERT operation. The omitted columns must meet the following conditions

  • The column definition allows NULL values ​​(no value or null)
  • Default values ​​are given in the table definition. This means that if no value is given, the default value will be used

        5. If NULL values ​​or default values ​​are not allowed in the table, but the values ​​in the table are omitted, an error will occur

        6. In the INSERT SELECT statement, only care about the position of the column and not the column name. The primary key values ​​of the two tables cannot be repeated. The SELECT statement can contain a WHERE statement for filtering.

        7. The SELECT INTO statement can copy the contents of a table to a new table

        8. When using SELECT INTO, care should be taken

  • Any SELECT option and clause can be used, including WHERE and GROUP BY
  • Insert data from multiple tables using joins
  • No matter how many tables you insert data from, data can only be inserted into one table

        9. SELECT INTO is a great tool to replicate before experimenting with new SQL statements, you can test SQL code on replicated data without affecting the actual data

Summary: This lesson describes how to insert rows into database tables. We learned several ways of how to use INSERT, why to use column names explicitly, how to use INSERT SELECT to import rows from another table, and how to use SELECT INTO to export rows to a new table


Lesson 16

        This lesson describes how to further manipulate table data using UPDATE and DELETE statements

        The main code is as follows:

update custcopy
set cust_email = '[email protected]'
where cust_id = '1000000005';
update custcopy
set cust_contact = 'Sam Roberts',
    cust_email = '[email protected]'
where cust_id = '1000000006';
update custcopy
set cust_email = null
where cust_id = '1000000005';
delete from Custcopy
where cust_id = '1000000006';

        1. To update (modify) the data in the table, you can use the UPDATE statement, there are two ways to use it

  • Update a specific row in a table
  • Update all rows in the table

        2. Be careful not to omit the WHERE clause before using the UPDATE statement

        3. Before using UPDATE, ensure that you have sufficient security permissions

        4. The basic UPDATE statement consists of three parts, namely

  • table to update
  • column names and their new values
  • A filter that determines which rows to update

        5. Subqueries can be used in the UPDATE statement to update the column data with the data retrieved by the SELECT statement

        6. To delete the value of a column, set it to NULL (if the table definition allows NULL values)

        7. Some SQL implementations support the use of the FROM clause in an UPDATE statement to update rows from one table with data from another table

        8. To delete (remove) data from a table, use the DELETE statement, there are two ways to use it

  • Delete a specific row from a table
  • delete all rows from the table

        9. Be careful not to omit the WHERE clause before using the DELETE statement

        10. Before using DELETE, ensure that you have sufficient security permissions

        11. Foreign keys can ensure referential integrity, and DBMSs can often prevent deletion of rows that are needed for a relationship

        DELETE statement deletes rows from a table, even deletes all rows, but not the table itself

        13. If you want to delete all rows from the table, don't use DELETE, you can use the faster TRUNCATE TABLE

        14. Here are some important principles to follow when using UPDATE or DELETE

  • Never use an UPDATE or DELETE statement without a WHERE clause unless you really intend to update and delete every row
  • Make sure every table has a primary key, use it like a WHERE clause whenever possible
  • Before using the WHERE clause in an UPDATE or DELETE statement, you should test with SELECT to ensure that it filters the correct records
  • Use a database that enforces referential integrity
  • Some DBMSs allow database administrators to impose constraints that prevent the execution of DELECT or UPDATE statements without a WHERE clause

Summary: This lesson describes how to use UPDATE and DELETE statements to manipulate data in tables. We learned the syntax of these statements, their potential dangers, why the WHERE clause is important for UPDATE and DELETE statements, and some guidelines to follow to keep your data safe


Lesson 17

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

        The main code is as follows:

create table products1
(
    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(100) NULL
);
create table orders1
(
    order_num    INTEGER    NOT NULL,
	order_date   DATETIME   NOT NULL,
	cust_id      CHAR(10)   NOT NULL
);
create table vendors1
(
    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_countyr  CHAR(50)    
);
create table orderitems1
(
    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
);
alter table vendors1
add vend_phone CHAR(20);
alter table vendors1
drop column vend_phone;
drop table custcopy;

        1. 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
  • Table column names and definitions, separated by commas
  • Some DBMS also require the location of the specified table    

        2. Code is arranged on multiple lines, and column definitions are properly indented for easier reading and editing

        3. When creating a new table, the specified table name must not exist, otherwise an error will occur. To prevent accidental overwriting of existing tables, SQL requires that the table be manually deleted first

        4. When NOT NULL is specified, most DBMSs think that NULL is specified, but not all DBMSs do so

        5. Only columns that do not allow NULL can be used as primary keys, and columns that allow NULL values ​​cannot be used as unique identifiers

        6. A NULL value is no value, not an empty string, not ' '

        7. SQL allows to specify default values, if no value is given when inserting a row, the DBMS will automatically adopt the default value. The default value is specified with the keyword DEFAULT in the column definition of the CREATE TABLE statement

        8. Default values ​​are usually used for date or timestamp columns

        9. To update the table definition, you can use the ALTER TABLE statement. What different DBMSs allow to update varies widely, here are some things to consider when using ALTER TABLE

  • Ideally, don't update the table when it contains data. Fully consider possible future needs in the design process of the table
  • 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)
  • Most DBMSs do not allow dropping or changing columns in a table
  • Most DBMSs allow renaming of columns in a table
  • Many DBMS restrictions make changes to columns that are already filled with data, and almost no restrictions on columns that are not filled with data

        10. What changes can be made to the structure of the table, please refer to the specific DBMS documentation

        11. 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)
  • List what changes are to be made

        12. Complex table structure changes generally require a manual delete process, which involves the following steps

  • Create a new table with the new column layout
  • Copy data from the old table to the new table using the INSERT SELECT statement. Use conversion functions and calculated fields if necessary
  • Validate the new table with the required data
  • rename old table
  • Rename the new table with the original name of the old table
  • Recreate triggers, stored procedures, indexes, and foreign keys as needed

        13. Be extremely careful when using ALTER TABLE, you should make a full backup (table structure and data backup) before making changes. Changes to database tables cannot be undone, and if unneeded columns are added, they may not be dropped. Similarly, if you delete a column that shouldn't be deleted, you may lose all data in that column

        14. Dropping a table is very simple, just use the DROP TABLE statement

        15. If you can, use relationship rules to prevent accidental deletions

        16. The basic syntax for all rename operations requires specifying the old and new table names. However, there are differences in different DBMS implementations, and the specific syntax should refer to the documentation

Summary: This lesson introduces several new SQL statements. CREATE TABLE originally created a new table, ALTER TABLE was used to alter table columns (or other objects such as constraints or indexes), and DROP TABLE was used to completely drop a table. These statements must be used with care and should be used after a backup. Since the syntax of these statements varies in different DBMSs, refer to the corresponding DBMS documentation for more details





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325795525&siteId=291194637