CHAPTER 6 IN THIS CHAPTER Adding Data 105 Modifying Data Deleting Data 108 111 SQL Data Manipulation Chapter 5, “Introducing SQL,” introduced data drivers, data sources, SQL, and data retrieval (using the SELECT statement). You’ll probably find that you spend far more time retrieving data than you do inserting, updating, or deleting data (which is why we concentrated on SELECT first). NOTE As in the last chapter, the SQL Query Tool in the ows/sql directory will be used to execute the SQL statements. For security’s sake (to prevent accidental data changes) the SQL Query Tool defaults to on allowing execution of SELECT statements (and no other SQL statements). To change this behavior edit the Application.cfm file in the ows/sql directory. You will see a series of variables that are set, one of which is select_only which is a flag that is set to yes (the default setting) instructing the utility to only execute SELECT statements. Change this value to no before proceeding (and save the updated Application.cfm) with the examples in this chapter (or an error will be thrown). And you might want to set the flag back to yes when done, just to be safe. Adding Data You will need to insert data into tables at some point, so now let’s take a look at data inserting using the INSERT statement. NOTE In this chapter, you will add, update, and delete rows from tables in the ows data source. The reason you delete any added rows is to ensure that any example code and screenshots later in the book actually look like you’d expect them to. Feel free to add more rows if you’d like, but realize that if you do not clean up when you’re finished, your screens will look different from the ones shown in the figures. This is not a problem, and you are welcome to do so; just keep it in mind so you know why things don’t look the same. 106 CHAPTER 6 SQL Data Manipulation Using the INSERT Statement You use the INSERT statement to add data to a table. INSERT is usually made up of three parts: ■ The table into which you want to insert data, specified with the INTO keyword. ■ The column(s) into which you want to insert values. If you specify more than one item, each must be separated by a comma. ■ The values to insert, which are specified with the VALUES keyword. The Directors table contains the list of movie directors working with (or for) Orange Whip Studios. Directors cannot be assigned projects (associated with movies) if they are not listed in this table, so any new directors must be added immediately. ➜ See Appendix G, “Sample Application Data Files” for an explanation of each of the data files and their contents. Now you’re ready to add the new director. The following code contains the SQL INSERT statement: INSERT INTO Directors(FirstName, LastName) VALUES(‘Benjamin’, ‘FORTA’) Enter this statement into the SQL Query field as seen in Figure 6.1. Feel free to replace my name with your own. When you’re finished, click the Execute button to insert the new row. Assuming no problems occur, you should see a confirmation screen similar to the one shown in Figure 6.2. TIP So how can you tell if an INSERT succeeds or fails? Well, no news is good news – if no error is returned then the INSERT has succeeded, but if an error occurs then it will be displayed. Understanding INSERT Now that you’ve successfully inserted a row using the SQL INSERT statement, take a minute to look at the statement’s syntax. The first line of your statement reads as follows: INSERT INTO Directors(FirstName, LastName) The text immediately following the INTO keyword is the name of the table into which the new row is being inserted. In this case, it is the Directors table. Next, the columns being added are specified. The columns are listed within parentheses, and if multiple columns are specified, each must be separated by a comma. A row in the Directors table requires both a FirstName and a LastName, so the INSERT statement specifies both columns. NOTE When you insert a row into a table, you can provide values for as many (or as few) columns as you prefer. The only restriction is that any columns defined as NOT NULL columns—meaning they can’t be left empty—must have values specified. If you do not set a value for a NOT NULL column, the database driver returns an error message and the row is not inserted. Adding Data Figure 6.1 Type the statement into the SQL Query field, and then click Execute. Figure 6.2 As INSERT statements do not return data, no results will be returned. The next line reads as follows: VALUES(‘Benjamin’, ‘FORTA’) A value must be specified for every column listed whenever you insert a row. Values are passed to the VALUES keyword; all values are contained within parentheses, just like their column names. Two columns are specified, so two values are passed to the VALUES keyword. NOTE When inserting rows into a table, columns can be specified in any order. But be sure that the order of the values in the VALUES keyword exactly matches the order of the columns after the table name or you’ll insert the wrong data into the columns. To verify that the new director was added to the table, retrieve the complete list of directors using the following SQL statement: SELECT * FROM Directors As explained in Chapter 5, SELECT * means select all columns. As you can see in Figure 6.3, the new row was added to the table. Make a note of the DirectorID, which you’ll need later to update or delete this row. 107 108 CHAPTER 6 SQL Data Manipulation Figure 6.3 Use SELECT statements to verify that INSERT operations were successful. NOTE In the previous INSERT statement, no value was provided for the DirectorID column. So, where did that value come from? The Directors table was set up to automatically assign primary key values every time a new row is inserted. This is a feature supported by many databases—Access calls these AutoNumber columns, SQL Server uses the term Identity, and other databases have other names for the same feature. The end result is that you don’t have to worry about creating unique values because the database does that for you. TIP INSERT can insert only one row at a time, unless the data being inserted is being retrieved from another table. In that case, a special form of the INSERT statement (called INSERT SELECT) can be used to insert all retrieved rows in a single operation. Modifying Data You use the SQL UPDATE statement to update one or more columns. This usually involves specifying the following: ■ The table containing the data you want to update. ■ The column or columns you want to update, preceded by the SET keyword. If you specify more than one item, each must be separated by a comma. ■ An optional WHERE clause to specify which rows to update. If no WHERE clause is provided, all rows are updated. Modifying Data Try updating a row. Enter the following SQL statement (ensuring that the ID number used in the WHERE clause is the DirectorID you noted earlier). UPDATE Directors SET FirstName=’Ben’ WHERE DirectorID = 14 Your code should look similar to the example shown in Figure 6.4 (although the DirectorID might be different). Click Execute to perform the update. Again, no results will be displayed as UPDATE does not return data. Figure 6.4 Update statements can be entered manually and entered on one line or broken over many lines. If you now select the contents of the Directors table, you see that the new director’s first name has been changed. Understanding UPDATE Now, take a closer look at the SQL statement you just used. The first line issued the UPDATE statement and specified the name of the table to update. As with the INSERT and DELETE statements, the table name is required. You next specified the column you wanted to change and its new value: SET FirstName=’Ben’ This is an instruction to update the FirstName column with the text Ben. The SET keyword is required for an UPDATE operation because updating rows without specifying what to update makes little sense. The SET keyword can be used only once in an UPDATE statement. If you are updating multiple rows—for example, to change Benjamin to Ben and to set the LastName to Forta in one operation— the SET keyword would look like this: SET FirstName=’Ben’, LastName=’Forta’ 109 110 CHAPTER 6 SQL Data Manipulation When updating multiple columns, each column must be separated by a comma. The complete (revised) UPDATE statement would then look like this: UPDATE Directors SET FirstName=’Ben’, LastName=’Forta’ WHERE DirectorID = 14 The last line of the code listing specifies a WHERE clause. The WHERE clause is optional in an UPDATE statement. Without it, all rows will be updated. The following code uses the primary key column to ensure that only a single row gets updated: WHERE DirectorID = 14 To verify that the updates worked, try retrieving all the data from the Directors table. The results should be similar to those seen in Figure 6.5 (showing the updated final row). CAUTION Be sure to provide a WHERE clause when using the SQL UPDATE statement; otherwise, all rows will be updated. Figure 6.5 When experimenting with updates, it is a good idea to retrieve the table contents to check that the update worked properly. Making Global Updates You occasionally will want to update all rows in a table. To do this, you use UPDATE, too—you’d just omit the WHERE clause or specify a WHERE clause that matches multiple rows. When updating multiple rows using a WHERE clause, always be sure to test that WHERE clause with a simple SELECT statement before executing the UPDATE. If the SELECT returns the correct data (the data you want updated), you’ll know that it is safe to use with UPDATE. Failure to do this can result in you updating the wrong data! Deleting Data TIP Before executing INSERT, UPDATE, or DELETE operations that contain complex statements or WHERE conditions, you should test the statement or condition by using it in a SELECT statement. If SELECT returns incorrect statement results or an incorrect subset of data filtered by the WHERE clause, you’ll know that the statement or condition is incorrect. The SELECT statement never changes any data, unlike INSERT, UPDATE, and DELETE. So, if an error exists in the statement or condition, you’ll find out about it before any damage is done. Deleting Data Deleting data from a table is even easier than adding or updating data—perhaps too easy. You use the SQL DELETE statement to delete data. The statement takes only two parameters—one required and one optional: ■ The name of the table from which to delete the data must be specified immediately following the words DELETE FROM. ■ An optional WHERE clause can be used to restrict the scope of the deletion process. The DELETE statement is dangerously easy to use. Look at the following line of code (but don’t execute it): DELETE FROM Directors This statement removes all directors from the Directors table without any warnings or confirmation. TIP Some databases, client/server databases (such as Microsoft SQL Server and Oracle) in particular, offer safeguards against accidental (or malicious) deletions. There generally are two approaches to preventing mass deletion. One is to create a trigger (a piece of code that runs on the server when specific operations occur) that verifies every DELETE statement and blocks any DELETE without a WHERE clause. Another popular option is to restrict the use of DELETE without a WHERE clause based on login name. Only certain users, usually those with administrative rights, are granted permission to execute DELETE without a WHERE clause. Any other user attempting a mass DELETE will receive an error message, and the operation will abort. Not all database systems support these techniques. Consult the database administrator’s manuals to ascertain which safeguards are available to you. The DELETE statement is most often used with a WHERE clause. For example, the following SQL statement deletes a single director from the Directors table (the one you just added): DELETE FROM Directors WHERE DirectorID=14 To verify that the row was deleted, retrieve all the Directors one last time (as seen in Figure 6.6). 111 112 CHAPTER 6 SQL Data Manipulation Figure 6.6 Most databases delete rows immediately (as opposed to flagging them for deletion), and this will be reflected when listing the table contents. As with all WHERE clauses, the DELETE statement’s WHERE clause can be a SELECT statement that retrieves the list of rows to delete. If you do use a SELECT statement for a WHERE clause, be careful to test the SELECT statement first to ensure that it retrieves all the values you want, and only those values you want. TIP Feel free to INSERT, UPDATE, and DELETE rows as necessary, but when you’re finished either clean up the changes or just copy overwrite the data file with the original (to restore it to its original state). NOTE Primary key values are never reused. If you INSERT rows after you have performed delete operations, the new rows will be assigned brand new IDs, and the old (deleted) IDs will not be reused. This behavior is a required part of how relational databases work as was explained in Chapter 2, “Building the Databases.”