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

Slides:



Advertisements
Similar presentations
Microsoft® Access® 2010 Training
Advertisements

Access 2007 ® Use Databases How can Microsoft Access 2007 help you structure your database?
A Guide to SQL, Seventh Edition. Objectives Create a new table from an existing table Change data using the UPDATE command Add new data using the INSERT.
Introduction to Structured Query Language (SQL)
SQL Data Definition II Stanislava Armstrong 1SQL Data Definition II.
A Guide to SQL, Seventh Edition. Objectives Understand the concepts and terminology associated with relational databases Create and run SQL commands in.
30-Jun-15 SQL A Brief Introduction. SQL SQL is Structured Query Language Some people pronounce SQL as “sequel” Other people insist that only “ess-cue-ell”
Introduction to Structured Query Language (SQL)
A Guide to SQL, Seventh Edition. Objectives Understand, create, and drop views Recognize the benefits of using views Grant and revoke user’s database.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Chapter 9 SQL and RDBMS Part C. SQL Copyright 2005 Radian Publishing Co.
ASP.NET Programming with C# and SQL Server First Edition
XP New Perspectives on Microsoft Access 2002 Tutorial 51 Microsoft Access 2002 Tutorial 5 – Enhancing a Table’s Design, and Creating Advanced Queries and.
Chapter 10 Queries and Updating Part C. SQL Copyright 2005 Radian Publishing Co.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
1 MySQL and phpMyAdmin. 2 Navigate to and log on (username: pmadmin)
SQL Unit 5 Aggregation, GROUP BY, and HAVING Kirk Scott 1.
PHP meets MySQL.
Analyzing Data For Effective Decision Making Chapter 3.
Ad Hoc Constraints Objectives of the Lecture : To consider Ad Hoc Constraints in principle; To consider Ad Hoc Constraints in SQL; To consider other aspects.
1 What is database 2? What is normalization? What is SQL? What is transaction?
Introduction to Databases Trisha Cummings. What is a database? A database is a tool for collecting and organizing information. Databases can store information.
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Chapter 10: The Data Tier We discuss back-end data storage for Web applications, relational data, and using the MySQL database server for back-end storage.
M1G Introduction to Database Development 2. Creating a Database.
Views Lesson 7.
M1G Introduction to Database Development 5. Doing more with queries.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Access 2007 ® Use Databases How can Microsoft Access 2007 help you structure your database?
M1G Introduction to Database Development 4. Improving the database design.
ITGS Databases.
Maintaining a Database Access Project 3. 2 What is Database Maintenance ?  Maintaining a database means modifying the data to keep it up-to-date. This.
Microsoft Access. Microsoft access is a database programs that allows you to store retrieve, analyze and print information. Companies use databases for.
Microsoft Access 2010 Chapter 3 Maintaining a Database.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
SQL Unit 6 Set Operations Kirk Scott. 6.1 Introduction 6.2 UNION Queries 6.3 Queries with IN (Intersection) 6.4 Queries with NOT IN (Set Subtraction)
SQL Unit 10 Creating Tables, Adding Constraints, and Defining Indexes Kirk Scott 1.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Managing Constraints. 2 home back first prev next last What Will I Learn? Four different functions that the ALTER statement can perform on constraints.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
1 DBS201: More on SQL Lecture 3. 2 Agenda How to use SQL to update table definitions How to update data in a table How to join tables together.
SQL Unit 7 Set Operations Kirk Scott Introduction 7.2 UNION Queries 7.3 Queries with IN (Intersection) 7.4 Queries with NOT IN (Set Subtraction)
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Constraints Lesson 8. Skills Matrix Constraints Domain Integrity: A domain refers to a column in a table. Domain integrity includes data types, rules,
Work with Tables and Database Records Lesson 3. NAVIGATING AMONG RECORDS Access users who prefer using the keyboard to navigate records can press keys.
A Guide to SQL, Eighth Edition Chapter Six Updating Data.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Starting with Oracle SQL Plus. Today in the lab… Connect to SQL Plus – your schema. Set up two tables. Find the tables in the catalog. Insert four rows.
Access Module Implementing a Database with Microsoft Access A Great Module on Your CD.
A Guide to MySQL 6. 2 Objectives Create a new table from an existing table Change data using the UPDATE command Add new data using the INSERT command.
Unit-8 Introduction Of MySql. Types of table in PHP MySQL supports various of table types or storage engines to allow you to optimize your database. The.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
Copyright © Curt Hill SQL The Data Manipulation Language.
Fundamentals of DBMS Notes-1.
Tables and Triggers.
SQL and SQL*Plus Interaction
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
SQL Creating and Managing Tables
SQL Unit 11 Inserting, Updating, and Deleting Data; Changing the Database Design Kirk Scott.
SQL Creating and Managing Tables
SQL Creating and Managing Tables
CMSC-461 Database Management Systems
IST 318 Database Administration
Presentation transcript:

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

11.1 The Keywords INSERT, UPDATE, and DELETE 11.2 Changing the Design of a Database with the Keywords ALTER, ADD, and DROP 2

11.1 The Keywords INSERT, UPDATE, and DELETE 3

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. 4

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. 5

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. 6

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 7

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

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. 9

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. 10

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

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. 12

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') 13

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. 14

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

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. 16

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. 17

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 (conameTEXT(18)) 18

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 19

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' 20

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. 21

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. 22

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. 23

This table design still doesn't have a primary key, but that will not be important for the examples: CREATE TABLE Mfr (conameTEXT(18) prodidTEXT(18) purchcostCURRENCY) 24

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 25

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

Going in the other direction, this will also work: INSERT INTO Car(make, model, dealercost) SELECT * FROM Mfr 27

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 28

Going in the other direction, you could also do this: INSERT INTO Car(make, dealercost) SELECT coname, purchcost FROM Mfr 29

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. 30

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 31

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. 32

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. 33

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 34

Here is an example of an update query that would affect all of the records in a table: UPDATE Mfr SET purchcost = 0 35

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' 36

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. 37

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. 38

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 39

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 40

You can also pick which rows to delete by adding a WHERE clause: DELETE * FROM Mfr WHERE coname = 'Dodge' AND purchcost <

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. 42

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

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. 44

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 45

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: 46

ALTER TABLE Car ADD color TEXT(6) 47

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 48

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. 49

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 50

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. 51

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

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. 53

This command would remove the color field from the Car table: ALTER TABLE Car DROP color 54

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

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. 56

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. 57

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 58

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. 59

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

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. 61

The uniqueness constraint can be removed by entering this command. It has to be removed by name. ALTER TABLE Person DROP CONSTRAINT SSNunique 62

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 63

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. 64

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. 65

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. 66

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. 67

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. 68

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. 69

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

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 71

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. 72

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 73

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. 74

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. 75

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

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. 77

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 78

The End 79