sql unit 11 inserting, updating, and deleting data; changing the database design

79
SQL Unit 11 Inserting, Updating, and Deleting Data; Changing the Database Design Kirk Scott 1

Upload: ruby-rios

Post on 31-Dec-2015

36 views

Category:

Documents


1 download

DESCRIPTION

SQL Unit 11 Inserting, Updating, and Deleting Data; Changing the Database Design. Kirk Scott. 11.1 The Keywords INSERT, UPDATE, and DELETE 11.2 Changing the Design of a Database with the Keywords ALTER, ADD, and DROP. 11.1 The Keywords INSERT, UPDATE, and DELETE. - PowerPoint PPT Presentation

TRANSCRIPT

1

SQL Unit 11Inserting, Updating, and Deleting Data;

Changing the Database Design

Kirk Scott

2

• 11.1 The Keywords INSERT, UPDATE, and DELETE11.2 Changing the Design of a Database with the Keywords ALTER, ADD, and DROP

3

11.1 The Keywords INSERT, UPDATE, and DELETE

4

11.1.1 The Keywords INSERT INTO and VALUES for Inserting Data into Tables

• Microsoft Access has a simple graphical interface for inserting data into tables.

• It's essentially the same as inserting data into a spreadsheet.

• You can type new data into a row, field by field.

• This will be mentioned off and on in this unit and again in the next unit.

5

• It is also possible to insert a single row of data into a table using an SQL command.

• It's easier to insert a single row using the graphical user interface

• The SQL commands are very useful because they make it possible insert, update, and delete multiple rows at a time.

6

• Just like with the CREATE commands of the previous unit, the commands in this unit will be saved as queries.

• These commands do not retrieve data from table.

• They change the contents of the table.• When you try to run the queries, you will be

prompted whether or not you want to change the table.

7

The Keywords for Inserting

• This is the keyword phrase for the insertion itself:

• INSERT INTO TableName• In simple insertions it is paired with this:• VALUES(fields or values here)• For more complicated insertions, the INSERT

INTO will be followed by a query

8

Inserting a single row

• This query will insert a single row into the table• It isn't necessary to list all of the fields in the

table because a value for each is provided in the right order in the list of values.

• • INSERT INTO Car• VALUES('a1b2c', 'Ford', 'Mustang', '2007',

24000, 22000)

9

• For all practical purposes, new records are appended at the end of existing records

• This is where data entry is done in the graphical user interface.

• Remember that the order of records in a relational table is of no theoretical meaning

• Therefore, it is of no real interest where, in fact, an inserted record goes.

10

11.1.2 Inserting with NULL Values

• The previous example provided a value for every field in the table.

• Assuming that fields do not have the constraint NOT NULL applied to them, it is possible to insert new records with null values.

11

• In this example, the nulls come in the fields at the end

• They could be used for any of the field values (although preferably not for the primary key field).

• INSERT INTO Car• VALUES('3d4e5', 'Dodge', 'Caravan', '2000',

NULL, NULL)

12

• The system will also accept a list of values shorter than the list of fields in a table.

• If the number of values given is shorter, those values will be put into the table's fields, beginning with the first

• The fields at the end, for which no values are provided, will be null by default.

• In other words, the following example has the same effect as the previous one.

13

• Notice that this approach is only practical when the nulls occur in the fields at the end:

• • INSERT INTO Car• VALUES('3d4e5', 'Dodge', 'Caravan', '2000')

14

11.1.3 Specifying the Fields to Insert Into

• If you specify just the name of the table in an insert query, by default, the query applies to all of the fields of the table, in order.

• It is also possible to explicitly list just the fields of interest.

• Then it is not necessary to insert NULL into fields of no interest.

• Instead, the list of values only has to contain values for the fields of interest.

• NULL will be inserted into the other fields by default.

15

• The following example will by default provide null values for fields that aren't specified, and those unspecified fields could be anywhere among the fields of a table:

• • INSERT INTO Car(vin, make, year, dealercost)• VALUES('f6g7h', 'Chevrolet', '2002', 6000)

16

11.1.4 Inserting Multiple Records by Including SELECT with INSERT

• The following examples show the power of a language like SQL over a graphical user interface for inserting records into tables.

• The examples will be artificially simple so that there is no confusion about the tables and fields in question.

• The syntax also turns out to be simple, but this is not artificial.

17

• To accomplish the same thing using the graphical user interface would not be as easy as using SQL.

• You might observe that what is being accomplished here is reminiscent of some of the steps in the unit on temporary tables.

• In these examples, tables exist, and it’s possible to move subsets of their records from one to the other.

18

• Let this table be created for the following example. • Mfr stands for manufacturer and coname stands for

company name. • It would appear that coname, the only field, would be

the primary key field.• For the time being, do not be concerned that the

primary key field of the table isn’t designated.• • CREATE TABLE Mfr• (coname TEXT(18))

19

• Assume that a set of records has been entered into the Car table.

• Then the following command will insert all of the values of the make field from the Car table into the coname field of the Mfr table.

• Notice that this insert command now truly takes the form of a query.

• • INSERT INTO Mfr(coname)• SELECT make• FROM Car

20

• This example can be expanded into a full-scale query by adding a WHERE clause to the SELECT.

• Anything you can do in a regular query you can do in an insertion query:

• • INSERT INTO Mfr(coname)• SELECT make• FROM Car• WHERE year > '2000'

21

• Notice that what goes into the Mfr table are the results of a query, and the results of a query might not consist of a set of unique rows.

• Since the Mfr table has only one field, presumably coname would have to be the primary key field.

• On the other hand, coname wasn't designated as the primary key in the table definition.

22

• In this example we're relying on the system to maintain a hidden primary key field.

• The system does have the ability to do this.• Under that condition, duplicate values could

be inserted into the coname field if the SELECT returns duplicate values.

23

11.1.5 Matching Fields on Insertions with SELECT

• For the sake of a few more illustrative examples, let the definition of the Mfr table be expanded.

• The fields prodid, product id, and purchcost, purchase cost have been added to the table.

• They are of the same type and size as corresponding fields in the Car table.

24

• This table design still doesn't have a primary key, but that will not be important for the examples:

• • CREATE TABLE Mfr• (coname TEXT(18)• prodid TEXT(18)• purchcost CURRENCY)

25

• Assume that some data has been entered into both the Car and Mfr tables.

• It would not be possible to make a query like this one work, because the number of fields in the two tables doesn't match:

• • INSERT INTO Mfr• SELECT *• FROM Car

26

• However, this will work:• • INSERT INTO Mfr• SELECT make, model, dealercost• FROM Car

27

• Going in the other direction, this will also work:

• • INSERT INTO Car(make, model, dealercost)• SELECT *• FROM Mfr

28

• It is also possible to SELECT a subset of fields from both tables.

• For example:• • INSERT INTO Mfr(coname, purchcost)• SELECT make, dealercost• FROM Car

29

• Going in the other direction, you could also do this:

• • INSERT INTO Car(make, dealercost)• SELECT coname, purchcost• FROM Mfr

30

• These kinds of insert queries handle nulls like the earlier, one-row examples.

• Suppose that in the query a source field or value isn't specified for a field in the destination table.

• Suppose also that that the destination field isn’t defined with the “not null” constraint.

• Then the destination field will take on the value null by default.

31

11.1.6 Mismatching Fields on Insertions with SELECT

• The database management system doesn't know the "meaning" of fields, and can't protect you against mistakes like this one:

• • INSERT INTO Mfr(coname, prodid)• SELECT model, make• FROM Car

32

• The order of the respective fields is reversed in the INSERT and the SELECT.

• Since the reversed fields are of the same type, the system will not complain.

• Even if the fields are of different sizes, some systems might not complain

• And if they are of radically different types, like text and numeric, it's hard to say whether you'll get an error message or garbage data in your tables.

33

11.1.7 The Keywords UPDATE and SET for Updating the Data in Tables

• Data in tables can be updated using the graphical user interface.

• As with insertion, if the update applies to a single record, the graphical user interface is easy to use.

• However, it's also possible to update multiple records at a time using SQL.

34

The Keywords for Updating

• This is the keyword for the update itself:• UPDATE TableName• It is paired with this:• SET field = value• For more complicated updates, this can be

followed by a WHERE clause which specifies a subset of rows to update

• Without the WHERE clause, a simple update query affects all of the rows in a table

35

• Here is an example of an update query that would affect all of the records in a table:

• • UPDATE Mfr• SET purchcost = 0

36

• Which records are affected by an update can be controlled by adding a WHERE clause to the SET.

• For example:• • UPDATE Mfr• SET purchcost = 0• WHERE coname = 'Ford'

37

• Before executing any queries of this form, you should make sure that this is what you want to do.

• In a system like Microsoft Access there is no rollback (i.e., no "undo" option), so any old data is completely wiped out by an update.

• When running a query like this, Access will prompt you to see if you really want to make the changes.

38

11.1.8 The Keyword DELETE for Deleting Records from Tables

• Deleting records is like inserting and updating. • It can be done from the graphical user

interface, but it is also possible to write SQL queries that apply to multiple records at the same time.

39

The Keywords for Deleting

• This is the keyword for the update itself:• DELETE *• The * signifies all columns—namely a complete row• It is paired with this:• FROM TableName• For more complicated updates, this can be followed by

a WHERE clause which specifies a subset of rows to be deleted

• Without the WHERE clause, a simple deletion query deletes all of the rows from a table

40

• If you wanted to completely clear a whole table, you could run this query.

• Notice the use of *. • It is not possible to run deletion query and

pick only a subset of columns:

• DELETE *• FROM Mfr

41

• You can also pick which rows to delete by adding a WHERE clause:

• • DELETE *• FROM Mfr• WHERE coname = 'Dodge' AND purchcost <

10000

42

• Just like updates, it is not possible to undo deletions, so you should be careful when using this.

• The system will prompt you for a confirmation before doing the deletion.

• Keep in mind that DELETE eliminates records from a table

• You will see shortly that the keyword DROP is used to eliminate elements like fields and tables from a database design.

43

11.2 Changing the Design of a Database with the Keywords ALTER, ADD, and DROP

44

11.2.1 The Keywords ALTER TABLE and ADD for Adding New Fields to Tables

• If the design of a database is done carefully, it should not be necessary to change the designs of any of its tables after they have been created—but sometimes this happens.

• Designs can be changed using the graphical user interface, and they can also be changed using SQL syntax.

• A relatively trouble-free change would be the inclusion in a table of a new field that wasn't in the original design.

45

The Keywords for Changing the Design of a Table

• This keyword phrase identifies the table to be changed:

• ALTER TABLE TableName• It is paired with this:• ADD fieldname

46

• For example, it might be of interest to record the color of a car.

• A new field, named color, can be added to the Car table with the following command.

• Notice that the data type of the new field has to be specified.

• If there are already records in the table, the value of the new field for those records will be NULL:

47

• ALTER TABLE Car• ADD color TEXT(6)

48

11.2.2 The Keywords ALTER COLUMN for Changing Existing Fields in Tables

• It is also possible to change the type of a field that already exists in a table.

• Some changes are relatively simple• For example, you could make a text field wider

without complications• Or you could change an integer type numeric

field to one that can hold decimal places without complications

49

• If you are making radical changes in type, from text to numeric or vice-versa, this can be problematic

• Also, if you are changing to a size or type which can hold less data, the change can be problematic.

• If there are already records in the table with data in the field in question, this data may be damaged or lost.

50

The Keywords for Changing the Specifications for a Column in the Table

• This keyword phrase identifies the table to be changed:

• ALTER TABLE TableName• It is paired with this:• ALTER COLUMN fieldname and specification

51

• Here is an example which should be relatively trouble-free.

• The names of the common primary colors will fit into a field of only 6 characters.

• However, car colors can have names like 'candy apple red', which obviously requires more characters.

52

• The following command will redefine the color field in the Car table so that it has a new width:

• ALTER TABLE Car• ALTER COLUMN color TEXT(16)

53

11.2.3 The Keyword DROP for Eliminating Fields from Tables

• It is also possible to remove a field from a table design.

• Needless to say, all of the data stored in that field will be lost.

• The keyword for eliminating an element from a database design is DROP.

• Do not confuse this with DELETE, the keyword for eliminating a row from a table.

54

• This command would remove the color field from the Car table:

• ALTER TABLE Car• DROP color

55

11.2.4 Adding and Dropping a Primary Key Constraint after a Table has been Created

• If the Person table had been created without a primary key, the primary key specification could be added later by entering this command.

• Notice that after the keyword ADD, the syntax is the same as what was given in the previous unit.

• • ALTER TABLE Person• ADD CONSTRAINT personpkSSN PRIMARY

KEY(SSN)

56

• You would only want to try and add a primary key constraint later if you had already entered data values into that field for all records, and the data values in each record were unique.

• In other words, the existing data would have to satisfy the requirements for a primary key.

57

• The primary key constraint for the Person table could also be removed.

• This constraint could have been created when the table was designed, as shown in the previous unit.

• Or the constraint could have been added later, as shown above.

58

• This example illustrates why it is necessary to name constraints.

• Only if a constraint is named is it possible to come back later and remove it.

• • ALTER TABLE Person• DROP CONSTRAINT personpkSSN

59

• It would be unusual for the primary key field of a table to change over its lifetime, but anything is possible.

• Suppose you wanted to drop the primary key of an existing table

• You would want to make sure that the values in the new primary key field were set

• Then remove the old primary key constraint• Then specify the new primary key constraint.

60

11.2.5 Adding and Dropping a Uniqueness Constraint after a Table has been Created

• A uniqueness constraint could be added to the Person table later by entering this command.

• Once again notice that after the keyword ADD the syntax is the same as that given in the previous unit.

• • ALTER TABLE Person• ADD CONSTRAINT SSNunique UNIQUE(SSN)

61

• For the field in question, this won't allow non-unique values to be added to the table and it won't allow updates where the new value is not unique.

• If you try to add a uniqueness constraint after there are already data in the table, the constraint will not be accepted if there are non-unique values in the relevant field.

62

• The uniqueness constraint can be removed by entering this command.

• It has to be removed by name.• • ALTER TABLE Person• DROP CONSTRAINT SSNunique

63

11.2.6 Adding and Dropping a NOT NULL Constraint after a Table has been Created

• A NOT NULL constraint could be added later by entering this command:

• • ALTER TABLE Person• ALTER COLUMN lastname TEXT(12) NOT NULL

64

• This won't allow nulls to be added in new records that are added to the table and it won't allow values in this field to be updated to null.

• However, if the table already contains nulls in the field in question when the command is run, no error message will result, and those null values will remain in the table undisturbed.

65

• Notice that in the ALTER TABLE version, what follows the key word COLUMN is exactly what you see in the version where the constraint is included in the table definition.

• This is important. • You have to give the name, type, and size of

the field in question.

66

• The ALTER COLUMN command has the capability of changing all of the characteristics of a column.

• If you don't repeat the column's size in the command, for example, the command will reset the size to its default maximum.

67

• The NOT NULL constraint can be removed by entering this command.

• Because the NOT NULL constraint is unnamed, it is removed by repeating the ALTER COLUMN and changing the column to allow nulls.

• • ALTER TABLE Person• ALTER COLUMN lastname TEXT(12) NULL• This doesn’t work as advertised.• See the next overhead.

68

• It is aggravating, but true, that in Microsoft Access SQL this command will run without an error message, but it will not change the field so that it will accept null values.

• It is apparent that the command is accepted and runs, because if the size of the field is changed in the statement, this does have an effect on the table design.

69

• If you want to make this change and make sure that it happens, you have to use Access's graphical user interface.

• Information on this is given in the next unit.

70

11.2.7 Adding and Dropping a Foreign Key Constraint after a Table has been Created

• A foreign key constraint can be added later with this command.

• As usual, after the keyword ADD the syntax is the same as that given in the previous unit.

• • ALTER TABLE Person• ADD CONSTRAINT personfkmother FOREIGN

KEY(motherSSN)• REFERENCES Mother(SSN)

71

• Suppose this change is made after there are data already in the table

• Suppose also that there are values for the motherSSN field in the Person table that don't exist in the Mother table

• In that case, the command will not be accepted.

• Accepting would cause a violation of referential integrity

72

• In that situation, if nulls are allowed in the motherSSN field, it would be possible to change the unacceptable values to null using an update command

• Then the referential integrity constraint could be added.

• The constraint would apply to all new records entered into the table and it would apply to updates of existing data.

73

• The foreign key constraint could be dropped with the following command.

• As usual, it has to be dropped by name.• • ALTER TABLE Person• DROP CONSTRAINT personfkmother

74

11.2.8 The Keyword DROP for Eliminating Tables from Databases

• It is possible to remove a whole table from a database design.

• Eliminating the primary key table in a pk-fk relation can be a problematic action.

• If a referential integrity constraint exists, eliminating the primary key table would result in a referential integrity violation

• Even if the constraint didn’t exist, eliminating a table that another table refers to would be problematic.

75

• As usual, coming up with a correct design in the first place is preferable to having to make radical changes in the design later.

• For the sake of illustration, the following command would remove the Car table from the database.

• All of the data in it would be lost.

76

• Note again that the keyword for making a change in the database design is DROP, not DELETE:

• • DROP TABLE Car

77

11.2.9 Dropping an Index

• Just like with other constraints, indexes can be removed from tables.

• Notice that the key word for doing this, DROP, is the same key word that is used when getting rid of complete tables.

• This is analogous with the fact that both tables and indexes are created with a CREATE statement.

78

• An index has an independent existence in a database, like a table, and it is disposed of in the same way.

• It is dropped by name.• • DROP INDEX lastnameindex• ON Person

79

The End