Populating Tables with New Data

Team-Fly    

 
Sams Teach Yourself SQL in 24 Hours, Third Edition
By Ronald R. Plew, Ryan K. Stephens
Table of Contents
Hour 5.  Manipulating Data


graphics/newterm_icon.gif

Populating a table with data is simply the process of entering new data into a table, whether through a manual process using individual commands or through batch processes using programs or other related software. Manual population of data refers to data entry via a keyboard. Automated population normally deals with obtaining data from an external data source (such as another database) and loading the obtained data into the database.

Many factors can affect what data and how much data can be put into a table when populating tables with data. Some major factors include existing table constraints, the physical table size , column data types, the length of columns , and other integrity constraints, such as primary and foreign keys. The following sections help you learn the basics of inserting new data into a table, in addition to offering some Dos and Don'ts.

graphics/note_icon.gif

Do not forget that SQL statements can be in uppercase or lowercase. However, data is always case-sensitive. For example, if data is entered into the database as uppercase, it must be referenced in uppercase. These examples use both lowercase and uppercase just to show that it does not affect the outcome.


Inserting Data into a Table

Use the INSERT statement to insert new data into a table. There are a few options with the INSERT statement; look at the following basic syntax to begin:

 graphics/syntax_icon.gif insert into table_name VALUES ('value1', 'value2', [ NULL ]); 

Using this INSERT statement syntax, you must include every column in the specified table in the VALUES list. Notice that each value in this list is separated by a comma. The values inserted into the table must be enclosed by quotation marks for character and date/time data types. Quotation marks are not required for numeric data types or NULL values using the NULL keyword. A value should be present for each column in the table.

In the following example, you insert a new record into the PRODUCTS_TBL table.

Table structure:

 products_tbl  COLUMN Name                     Null?    DATA Type ------------------------------ -------- ------------- PROD_ID                         NOT NULL VARCHAR2(10) PROD_DESC                       NOT NULL VARCHAR2(25) COST                            NOT NULL NUMBER(6,2) 

Sample INSERT statement:

 graphics/input_icon.gif  INSERT INTO PRODUCTS_TBL   VALUES ('7725','LEATHER GLOVES',24.99);  graphics/output_icon.gif 1 row created. 

In this example three values were inserted into a table with three columns. The inserted values are in the same order as the columns listed in the table. The first two values are inserted using quotation marks because the data types of the corresponding columns are of character type. The third value's associated column, COST, is a numeric data type and does not require quotation marks, although they can be used.

graphics/note_icon.gif

Although single quotation marks are not required around numeric data that is being inserted, they may be used with any data type. Said another way, single quotation marks are optional when referring to numeric data values in the database, but required for all other data values (data types). Although usually a matter of preference, most SQL users choose not to use quotation marks with numeric values.


Inserting Data into Limited Columns of a Table

There is a way you can insert data into specified columns. For instance, suppose you want to insert all values for an employee except a pager number. You must, in this case, specify a column list as well as a VALUES list in your INSERT statement.

 graphics/input_icon.gif  INSERT INTO EMPLOYEE_TBL   (EMP_ID, LAST_NAME, FIRST_NAME, MIDDLE_NAME, ADDRESS, CITY, STATE, ZIP, PHONE)   VALUES   ('123456789', 'SMITH', 'JOHN', 'JAY', '12 BEACON CT',   'INDIANAPOLIS', 'IN', '46222', '3172996868');  graphics/output_icon.gif 1 row created. 

The syntax for inserting values into a limited number of columns in a table is as follows :

 graphics/syntax_icon.gif INSERT INTO TABLE_NAME ('COLUMN1', 'COLUMN2') VALUES ('VALUE1', 'VALUE2'); 

You use ORDERS_TBL and insert values into only specified columns in the following example.

Table structure:

 ORDERS_TBL  COLUMN NAME                     Null?    DATA TYPE ------------------------------ --------- ------------ ORD_NUM                         NOT NULL VARCHAR2(10) CUST_ID                         NOT NULL VARCHAR2(10) PROD_ID                         NOT NULL VARCHAR2(10) QTY                             NOT NULL NUMBER(4) ORD_DATE                                 DATE 

Sample INSERT statement:

 graphics/input_icon.gif  insert into orders_tbl (ord_num,cust_id,prod_id,qty)   values ('23A16','109','7725',2);  graphics/output_icon.gif 1 row created. 

You have specified a column list enclosed by parentheses after the table name in the INSERT statement. You have listed all columns into which you want to insert data. ORD_DATE is the only excluded column. You can see, if you look at the table definition, that ORD_DATE does not require data for every record in the table. You know that ORD_DATE does not require data because NOT NULL is not specified in the table definition. NOT NULL tells us that NULL values are not allowed in the column. Furthermore, the list of values must appear in the same order as the column list.

graphics/note_icon.gif

The column list in the INSERT statement does not have to reflect the same order of columns as in the definition of the associated table, but the list of values must be in the order of the associated columns in the column list.


Inserting Data from Another Table

You can insert data into a table based on the results of a query from another table using a combination of the INSERT statement and the SELECT statement. Briefly , a query is an inquiry to the database that either expects or not expects data to be returned. See Hour 7, "Introduction to the Database Query," for more information on queries. A query is a question that the user asks the database, and the data returned is the answer. In the case of combining the INSERT statement with the SELECT statement, you are able to insert the data retrieved from a query into a table.

The syntax for inserting data from another table is

 graphics/syntax_icon.gif insert into table_name [('column1', 'column2')] select [*('column1', 'column2')] from table_name [where condition(s)]; 

You see three new keywords in this syntax, which are covered here briefly. These keywords are SELECT, FROM, and WHERE. SELECT is the main command used to initiate a query in SQL. FROM is a clause in the query that specifies the names of tables in which the target data should be found. The WHERE clause, also part of the query, is used to place conditions on the query itself. An example condition may state: WHERE NAME = 'SMITH'. These three keywords are covered extensively during Hour 7 and Hour 8, "Using Operators to Categorize Data."

graphics/newterm_icon.gif

A condition is a way of placing criteria on data affected by a SQL statement.

The following example uses a simple query to view all data in the PRODUCTS_TBL table. SELECT * tells the database server that you want information on all columns of the table. Because there is not a WHERE clause, you will see all records in the table as well.

 graphics/input_icon.gif  select * from products_tbl;  graphics/output_icon.gif PROD_ID    PROD_DESC                       COST ---------- ------------------------------ ----- 11235      WITCHES COSTUME                29.99 222        PLASTIC PUMPKIN 18 INCH         7.75 13         FALSE PARAFFIN TEETH            1.1 90         LIGHTED LANTERNS               14.5 15         ASSORTED COSTUMES              10 9          CANDY CORN                      1.35 6          PUMPKIN CANDY                   1.45 87         PLASTIC SPIDERS                 1.05 119        ASSORTED MASKS                  4.95 1234       KEY CHAIN                       5.95 2345       OAK BOOKSHELF                  59.99 11 rows selected. 

Now, insert values into the PRODUCTS_TMP table based on the preceding query. You can see that 11 rows are created in the temporary table.

 graphics/input_icon.gif  INSERT INTO PRODUCTS_TMP   SELECT * FROM PRODUCTS_TBL;  graphics/output_icon.gif 11 rows created. 

The following query shows all data in the PRODUCTS_TMP table that you just inserted:

 graphics/input_icon.gif  SELECT * FROM PRODUCTS_TMP;  graphics/output_icon.gif PROD_ID    PROD_DESC                       COST ---------- ------------------------------ ----- 11235      WITCHES COSTUME                29.99 222        PLASTIC PUMPKIN 18 INCH         7.75 13         FALSE PARAFFIN TEETH            1.1 90         LIGHTED LANTERNS               14.5 15         ASSORTED COSTUMES              10 9          CANDY CORN                      1.35 6          PUMPKIN CANDY                   1.45 87         PLASTIC SPIDERS                 1.05 119        ASSORTED MASKS                  4.95 1234       KEY CHAIN                       5.95 2345       OAK BOOKSHELF                  59.99 11 rows selected. 

Inserting NULL Values

Inserting a NULL value into a column of a table is a simple matter. You might want to insert a NULL value into a column if the value of the column in question is unknown. For instance, not every person carries a pager, so it would be inaccurate to enter an erroneous pager numbernot to mention, you would not be budgeting space. A NULL value can be inserted into a column of a table using the keyword NULL.

The syntax for inserting a NULL value follows:

 graphics/syntax_icon.gif insert into schema.table_name values ('column1', NULL, 'column3'); 

The NULL keyword should be used in the proper sequence of the associated column that exists in the table. That column will not have data in it for that row if you enter NULL. In the syntax, a NULL value is being entered in the place of COLUMN2.

Study the two following examples:

 graphics/mysql_icon.gif graphics/input_icon.gif  INSERT INTO ORDERS_TBL (ORD_NUM,CUST_ID,PROD_ID,QTY,ORD_DATE)   VALUES ('23A16','109','7725',2,NULL);  graphics/output_icon.gif 1 row created. 

In the first example, all columns in which to insert values are listed, which also happen to be every column in the ORDERS_TBL table. You insert a NULL value for the ORD_DATE column, meaning that you either do not know the order date, or there is no order date at this time.

 graphics/input_icon.gif  INSERT INTO ORDERS_TBL   VALUES ('23A16','109','7725',2, '');  graphics/output_icon.gif 1 row created. 

There are two differences from the first statement in the second example, but the results are the same. First, there is not a column list. Remember that a column list is not required if you are inserting data into all columns of a table. Second, instead of inserting the value NULL into the ORD_DATE column, you insert '' (two single quotation marks together), which also symbolizes a NULL value (because there is nothing between them).


Team-Fly    
Top
 


Sams Teach Yourself SQL in 24 Hours
Sams Teach Yourself SQL in 24 Hours (5th Edition) (Sams Teach Yourself -- Hours)
ISBN: 0672335417
EAN: 2147483647
Year: 2002
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net