Databases Demystified a self teaching guide phần 4 ppsx

37 326 0
Databases Demystified a self teaching guide phần 4 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

CHAPTER 4 Introduction to SQL 91 Demystified / Databases Demystified / Oppel/ 225364-9 / Chapter 4 marketplace with the first commercial relational database products: Relational Soft - ware’s Oracle and Relational Technology’s INGRES. IBM released SQL/DS in 1982, with the query language now named SQL (System Query Language). When IBM released its next generation RDBMS, called DB2, the SQL acronym remained, but the language name had morphed into Structured Query Language. The name change was likely the result of marketing spin— structured programming was the mantra of the day, and although SQL has nothing to do with programming, struc - tured or otherwise, anything with the word structured in its title got more attention in the marketplace. SQL standards committees were formed by ANSI (American National Standards Institute) in 1986 and ISO (International Organization for Standardization) in 1987. Two years later, the first standard specification, known as SQL-89, was published. The standard was expanded three years later into SQL-92, which weighed in at roughly 600 pages. The third generation was called SQL-99, or SQL3. Most RDBMS products are built to the SQL-92 (now called SQL2) standard. SQL3 includes many of the ob- ject features required for SQL to operate on an object-relational database, as well as language extensions to make SQL computationally complete (adding looping, branching, and case constructs). Only a few vendors have implemented significant components of the SQL3 standard—Oracle being one of them. Nearly every vendor has added extensions to SQL, partly because they wanted to differentiate their products, and partly because market demands pressed them into implementing features before there were standards for them. One case in point is support for the DATE and TIMESTAMP data types. Dates are highly important in business data processing, but the developers of the original RDBMS products were computer scientists and academics, not business computing specialists, so such a need was unanticipated. As a result, the early SQL dialects did not have any special support for dates. As commercial products emerged, vendors responded to pressure from their biggest customers by hurriedly adding support for dates. Unfortunately, this led to each doing so in their own way. Whenever you migrate SQL statements from one vendor to another, beware of the SQL dialect differences. SQL is highly compatible and portable across vendor products, but complete database systems can seldom be moved without some adjustments. Getting Started with Oracle SQL Oracle provides two different client tools for managing the formation and execution of SQL statements and the presentation of results: SQL Plus and the SQL Plus Worksheet. We call these client tools because they normally run on the database user’s workstation and are capable of connecting remotely to databases that run on P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:16 AM Color profile: Generic CMYK printer profile Composite Default screen 92 Databases Demystified Demystified / Databases Demystified / Oppel/ 225364-9 / Chapter 4 other computer systems, which are often shared servers. It is not unusual for the cli - ent tools to also be installed on the server alongside the database for easy administra - tion, allowing the DBA logged in to the server to access the database without the need for a client workstation. Also available are the Personal and Lite editions of Oracle, where the database itself, along with the client tools, is installed on an individual user’s workstation or handheld device. The examples in this chapter focus on Oracle. However, if you are using a differ - ent RDBMS, there will be client tools for it as well, usually provided by the RDBMS vendor. For example, Sybase has a tool called iSQL, whereas Microsoft SQL Server has the GUI tools Enterprise Manager and Query Analyzer as well as a similar im - plementation of iSQL. Regardless of the RDBMS you are using, you may require the assistance of a DBA or system administrator in properly setting up a database ac - count so you may access a database and run the various SQL statements demon - strated in this chapter. If you have no commercial RDBMS products available to you, several notable freeware products, such as MySQL and PostgreSQL (a deriva- tive of INGRES), are also available. These provide reasonable implementations of many features of the SQL language. Oracle’s SQL Plus has a GUI version, which runs on Windows platforms, and a command-line version, which runs on all the platforms Oracle supports. You may start the GUI version of SQL Plus from the Windows Start menu by choosing Start | Programs | Oracle - OraHome92 | Application Development | SQL Plus. In this ex- ample, OraHome92 is the name of the Oracle Home on the client workstation. This value will vary from one workstation to another. Once started, SQL Plus provides a Log On window that prompts for the username, password, and host string to be used to connect to the database. For the Oracle HR sample schema, enter HR into the Username field and then supply the password and host string you obtained from your DBA. The host string helps SQL Plus find the database if it is running on a remote computer system; it is normally not needed if you are running SQL Plus on the same computer that is running the data - base. After SQL Plus has connected to the database, a window similar to the one shown here is displayed. P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:16 AM Color profile: Generic CMYK printer profile Composite Default screen Note that if you installed Oracle yourself, the demonstration accounts, such as HR, are usually locked during the installation as a security precaution. You will have to connect to the database as the SYSTEM user and do the following: 1. Unlock the HR database user account with this SQL command: ALTER USER HR ACCOUNT UNLOCK; 2. Change the HR database user password with this SQL command (the password has been set to HRPASS here, but you may use any password you wish): ALTER USER HR IDENTIFIED BY HRPASS; SQL statements and SQL Plus commands may be entered at the SQL> prompt. Results display after each command, and the screen scrolls as needed. SQL Plus commands help configure SQL Plus, such as setting the width of lines on the screen and the number of lines displayed per page of output. Other SQL Plus commands control the format of the output of SQL statements, such as setting page titles, for- matting columns, and adding subtotals to reports. SQL Plus commands are beyond the scope of this book, but they may be found in the SQL Plus User’s Guide and Ref- erence manual available (along with most other Oracle manuals) on the Oracle Technology Network website (http://otn.oracle.com). One very useful SQL Plus command we will look at, however, is the DESCRIBE command (abbreviated DESCR or DESC). This command lists all the columns in a table or view along with the data type for each. Figure 4-1 shows the output of the DESCRIBE command for the EMPLOYEES table. One of the common difficulties database users have with SQL Plus is that lines that are too long to display wrap to new lines. Another is that the SQL statements scroll off the screen when the results are displayed. Figure 4-2 provides an example of these issues. SQL Plus may be run from the Windows Command Shell using the following command: C:\>sqlplus hr/hrpass When run this way, SQL Plus has all the same capabilities as the Windows GUI version of SQL Plus, but is perhaps not as visually pleasing. In fact, it is exactly the same utility program with only the user interface changed. An example of a com - mand run from the Windows Command Shell version of SQL Plus is shown in Fig - ure 4-3. This screen is quite similar to the one used when SQL Plus is run on other platforms such as VMS VAX, Unix, and Linux. Recognizing the need for a better user interface, Oracle developed SQL Plus Worksheet as part of Oracle Enterprise Manager and started shipping it with CHAPTER 4 Introduction to SQL 93 P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:16 AM Color profile: Generic CMYK printer profile Composite Default screen 94 Databases Demystified Figure 4-1 DESCRIBE command output for the EMPLOYEES table Figure 4-2 SQL Plus window with wrapped lines P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:17 AM Color profile: Generic CMYK printer profile Composite Default screen Oracle8i. When SQL Plus Worksheet is started from the Windows Start menu, the login window appears, as shown here: The Username and Password fields should be familiar from the SQL Plus discus - sion, and the Connect String field from SQL Plus is now called Service instead. The Connect As field is for use by DBAs who require a special role (a named set of privi - leges) when they connect. Once connected, the SQL Plus Worksheet panel appears, as shown in Figure 4-4. SQL statements may be typed in the upper window, and the results are shown in the lower window. The icons in the toolbar at the top of the left margin provide various control functions, including disconnecting from the database, executing the current SQL statement, scrolling back and forth through a history of recent statements, and accessing the help facility. CHAPTER 4 Introduction to SQL 95 Figure 4-3 SQL Plus window, command-line version P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:17 AM Color profile: Generic CMYK printer profile Composite Default screen The SQL Plus Worksheet panel is used for the presentation of the examples that follow because of its superior formatting of query results. Where’s the Data? You probably noticed that although SQL Plus and SQL Plus Worksheet help you for - mat and run SQL statements, they don’t provide an easy way for you to see the names and definitions of the database objects available to you. This is a typical arrangement for an RDBMS. If you are not familiar with the database schema you are using, you can obtain some basic information in one of two ways: through catalog views or a tool such as the Oracle Enterprise Manager. Catalog views are special views provided by the RDBMS that present database metadata that documents the database contents. 96 Databases Demystified Figure 4-4 SQL Plus Worksheet panel P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:17 AM Color profile: Generic CMYK printer profile Composite Default screen Finding Database Objects Using Catalog Views Oracle provides a comprehensive set of catalog views that may be queried to show the names and definitions of all database objects available to a database user. Most other RDBMSs have a similar capability, but of course the names of the views vary. By issuing a SELECT statement against any of these views, you may display infor - mation about your database objects. Consult the Oracle Server Reference manual (available from Oracle Technology Network website) for complete information on the available catalog views. Here are two of the most useful ones: • USER_TABLES Contains one row of information for each table in the user schema. This view contains a lot of columns, but the one of most interest, TABLE_NAME, is the first column in the view. Once you know the table names, the DESCRIBE command (already introduced) can be used on each to show more information about the table definitions. Figure 4-5 shows an example of selecting everything from the USER_TABLES view. The SQL SELECT statement, shown in Figure 4-5, is described in more detail a little further along in this chapter. • USER_VIEWS Contains one row of information for each view in the user schema, containing, among other things, the name of the view and the text of the SQL statement that forms the view. CHAPTER 4 Introduction to SQL 97 Figure 4-5 Selecting from the USER_TABLES view P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:17 AM Color profile: Generic CMYK printer profile Composite Default screen 98 Databases Demystified Demystified / Databases Demystified / Oppel/ 225364-9 / Chapter 4 Viewing Database Objects Using Oracle Enterprise Manager For those less inclined to type SQL commands, Oracle provides a GUI tool known as Oracle Enterprise Manager (OEM). Other RDBMS vendors provide similar tools, such as the Enterprise Manager tool that comes with Sybase and Microsoft SQL Server. The Oracle Enterprise Manager Console can be started from the Windows Start menu, by choosing Start | Programs | Oracle - OraHome92 | Enterprise Manager Console. Once started, OEM presents a window asking whether it should be launched in standalone mode or if instead you wish to log in to the Oracle management server. Unless directed otherwise by your DBA, you should always launch OEM in standalone mode. Next, the Oracle Enterprise Manager login window will be dis - played, as already shown in a previous illustration. For OEM to work perfectly, you should connect to the database as the SYSTEM user. However, if you are working on an employer’s database system, your DBA may not be very interested in handing over the keys to the database to a beginner, so you may have to settle for signing in with the Oracle database username provided by the DBA. If you do so, some error messages related to privileges may appear, and some features may not work. Once connected to OEM, you will see a panel similar to the one in Figure 4-6. Here are the exact steps to follow to get to the EMPLOYEES table as shown in Figure 4-6: 1. Start the OEM Console from the Start menu, as described earlier. 2. Select Launch Standalone on the Oracle Enterprise Manager Console login window and then click OK. 3. Click the plus sign (+) next to Databases in the left column to expand the list of databases. 4. Click the plus sign (+) next to the name of your Oracle database (ORA9I in this example) to expand the list of database object types. 5. The Database Connect Information window will appear. In this window, type SYSTEM in the Username field and type the password for the SYSTEM user in the Password field. Click OK. 6. Click the plus sign (+) next to Schema to expand the list of schemas in the database. 7. Click the plus sign (+) next to HR to expand the list of objects belonging to the HR schema. P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:18 AM Color profile: Generic CMYK printer profile Composite Default screen 8. Click the plus sign (+) next to Tables to expand the list of tables in the HR schema. 9. Click the EMPLOYEES table to display its description in the right panel. OEM is so full of features that describing them in detail would take an entire book of at least this size. The feature you will be most interested in is the hierarchical tree of databases and database objects that appears in the column along the left margin of the panel. Expanding the Schema item shows all the schemas in the database (each Oracle database user gets their own schema). Expanding any schema shows the ob - ject types available in that schema. Expanding any object type (as we did with the Tables type) shows a list of objects of that type in the selected schema, and clicking or expanding any individual object shows more information about that object (as we did by clicking the EMPLOYEES table object). You’ve seen a little bit of the SQL SELECT statement so far. In the next section we take a detailed look at SQL. CHAPTER 4 Introduction to SQL 99 Figure 4-6 Oracle Enterprise Manager Console P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:18 AM Color profile: Generic CMYK printer profile Composite Default screen 100 Databases Demystified Demystified / Databases Demystified / Oppel/ 225364-9 / Chapter 4 Data Query Language (DQL): The SELECT Statement The SELECT statement retrieves data from the database. The clauses of the state - ment, as demonstrated in the following sections, are as follows: • SELECT Lists the columns that are to be returned in the results • FROM Lists the tables or views from which data is to be selected • WHERE Provides conditions for the selection of rows in the results • ORDER BY Specifies the order in which rows are to be returned • GROUP BY Groups rows for various aggregate functions Although it is customary in SQL to write keywords in upper case, this is not nec- essary in most implementations. The RDBMS SQL interpreter will usually recog- nize keywords written in upper, lower or mixed case. In Oracle SQL, all database object names (tables, views, synonyms, etc.) may be written in any case, but Oracle automatically changes them to upper case during processing because all Oracle da- tabase object names are stored in upper case in Oracle’s metadata. Be careful with other versions of SQL, however. For example, both Sybase and MS SQL Server can be set to a case-sensitive mode where object names written in different cases are treated as different objects. In case-sensitive mode, the following names would be considered different tables: EMPLOYEES, Employees, employees. Example 4-1: Listing All Employees The asterisk (*) symbol may be used in place of a column list in order to select all columns in a table or view. This is a useful feature for quickly listing data, but it should be avoided in statements that will be reused because it compromises logical data independence because any new column will be automatically selected the next time the statement is run. Note also that in SQL syntax, tables, views, and synonyms (an alias for a table or view) are all referenced in the same way. It should follow that the names of these come for the same namespace, meaning that a name of a table, for example, must be unique among all tables, views, and synonyms defined in particu - lar schema. Figure 4-7 shows the Example 4-1 SQL statement and its results. Example 4-2: Limiting Columns to Display To specify the columns to be selected, provide a comma-separated list following the SELECT keyword. Keep in mind that the list actually provides expressions that P:\010Comp\DeMYST\364-9\ch04.vp Monday, February 09, 2004 9:03:18 AM Color profile: Generic CMYK printer profile Composite Default screen [...]... example, in Oracle, the STORAGE clause may be included to specify the amount of physical space that is to be allocated to the table, and a TABLESPACE clause may be included to specify the tablespace that will hold the table’s data The ALTER TABLE Statement The ALTER TABLE statement may be used to change many aspects of the definition of a database table Again, there is a wide variation in implementation... Oracle: a Ends a transaction b Begins a new transaction c Makes changes effected by a transaction visible to all users d Causes changes made by a transaction to become permanent e Is automatic just before any DDL statement is run 14 An INSERT statement: a Must contain a column list b Must contain a VALUES list c May create multiple table rows d May contain a subquery e Creates a new table 15 An UPDATE... support is not as automatic The database user must issue a BEGIN TRANSACTION statement to start a transaction Once a transaction is started, changes made to the database can be made permanent with a COMMIT TRANSACTION statement, or they can be reversed using a ROLLBACK TRANSACTION statement Some RDBMSs, such as Microsoft Access and MySQL, do not provide transaction support at all The INSERT Statement The... statement is just the keyword followed by the semicolon that ends every SQL statement In Oracle, a transaction is automatically started for each database user session as soon as the user connects to the database At any time, the database user can issue a COMMIT, which makes all the database changes completed up to that point permanent and therefore visible to any other database user The user can also... may be used as a positional wildcard, meaning it matches any character in that position of the character string being evaluated The percent sign (%) may be used as a nonpositional wildcard, meaning it matches any number of characters for any length Note that Microsoft Access has a similar feature, but the wildcard characters are different (they match those in DOS and Visual Basic): The question mark... rules in the database, we will take a closer look at them here In Oracle, it is important to name the constraints because the names appear in any error messages generated when constraint violations take place Databases Demystified 120 Referential Constraints Here is an example of a referential constraint definition using the ALTER TABLE statement: ALTER TABLE EMPLOYEE_INPUT ADD CONSTRAINT EMP_DEPT_FK... DELETE statement; if the WHERE clause is omitted, the statement attempts to delete all the rows in the referenced table Figure 4- 25 shows an example of a DELETE statement 117 Databases Demystified 118 Figure 4- 25 Example 4- 20, “The DELETE Statement” Data Definition Language (DDL) Statements Data Definition Language (DDL) statements define the database objects but do not insert or update any data stored... database privilege is the authorization to do something in the database The database user granting the privilege is called the grantor, and the database user receiving the privilege is called the grantee Privileges fall into two broad categories: • System privileges Permit the grantee to perform a general database function, such as creating new user accounts or connecting to the database CHAPTER 4. .. meaning that any database changes a transaction makes must be made permanent when the transaction successfully completes On the other hand, these changes must be entirely removed from the database if the transaction fails before completion For example, we could start a transaction at the beginning of a process that creates a new order and then, at the end of the process when all the order information has... Figure 4- 10 Example 4- 4, A Simple WHERE Clause” 103 Databases Demystified 1 04 Example 4- 5: The BETWEEN Operator SQL provides the BETWEEN operator to assist in finding ranges of values The end points are included in the returned rows Figure 4- 11 shows the use of the BETWEEN operator to find all rows where SALARY is greater than or equal to 10000 and SALARY is less than or equal to 11000 Here’s an alternative . hierarchical tree of databases and database objects that appears in the column along the left margin of the panel. Expanding the Schema item shows all the schemas in the database (each Oracle database. tool such as the Oracle Enterprise Manager. Catalog views are special views provided by the RDBMS that present database metadata that documents the database contents. 96 Databases Demystified Figure 4- 4. assistance of a DBA or system administrator in properly setting up a database ac - count so you may access a database and run the various SQL statements demon - strated in this chapter. If you have

Ngày đăng: 08/08/2014, 18:22

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan