Database 11g sql pdf




















The column has the c r a heading Employee Details. The spaces improve the readability of the output. If the literal itself contains a c delimiter. By using the q operator, however, brackets [] are used as the quotation n t e r U s mark delimiters. The string between the brackets delimiters is interpreted as a literal character string.

Note that the department numbers are repeated. The c r a command displays the column names and the data types, and it shows you whether a column must contain data that is, whether the column has a NOT NULL constraint. O ly In the syntax, table name is the name of any existing table, view, or synonym that is accessible to the user.

Type displays the data type for a column. There are four coding errors in the following statement. Can you identify them? When you are modifying an existing script, make sure you use Save As to save it with a different filename. Alternatively, you can press [F9]. Open a new worksheet.

Note: After you have executed the query, make sure that you do not enter your next query in the same worksheet. The HR department wants more descriptive column headings for its report on employees. Then run your query again. The HR department has requested a report of all employees and their job IDs. Display the last name concatenated with the job ID separated by a comma and space and name the column Employee and Title. Separate each column output by a comma.

If the condition is true, the row meeting the condition is returned. All character searches are case-sensitive. I n Note: The symbols! The range that you c r a specify contains a lower limit and an upper limit. The condition defined using the c r a IN operator is also known as the membership condition. Therefore, using the IN operator has no performance r a benefits and is used only for logical simplicity.

You can select rows that match a character c r a pattern by using the LIKE operator. The character pattern—matching operation is referred to as a wildcard search. Two symbols can be used to construct the search string. This causes the Oracle server to interpret the underscore literally. A null value means that the value is unavailable, unassigned, unknown, or inapplicable.

The slide example retrieves the last names and managers of all employees who do not have a manager. Therefore, c are selected. The c r a table in the slide lists the default order of precedence. However, you can override the default order by using parentheses around the expressions that you want to calculate first.

Further, you can specify an expression, an alias, or a column position as the sort condition. To reverse the order in which the rows are displayed, specify the DESC keyword after the U hired employee. The slide example sorts the result by the most recently l e 2. The slide example sorts the data by c annual salary.

You can sort query results by more than one column. The sort limit is the number of columns in the given table. If you want to reverse the order of a column, specify DESC after its name. I want to query different values. You can edit the WHERE clause to provide a different value each time O ly you run the command, but there is also an easier way. You can embed substitution variables in a command file or in a single SQL statement.

A variable can be thought of as a container in which values are I n temporarily stored. When the statement is run, the stored value is substituted. If used in scripts that are deployed to users, substitution variables can be subverted for SQL injection attacks. However, you do not need to define the value of each variable.

When the statement is executed, SQL Developer prompts the user for an employee number and then e l displays the employee number, last name, salary, and department number for that employee. The c r a same rule applies to the substitution variables. Enclose the variable with single quotation marks within the SQL statement itself. The user sees the prompt for the value only once.

If you run the query again, you will not be prompted for the value of the variable. You should also have learned how to implement various operators and O ly By using the substitution variables, you can add flexibility to your SQL statements. Run your query. Create a report that displays the last name and department number for employee number Run the query. The HR department needs to find high-salary and low-salary employees. Create a report to display the last name, job ID, and hire date for employees with the last names of Matos and Taylor.

Order the query in ascending order by the hire date. Display the last name and department ID of all employees in departments 20 or 50 in ascending alphabetical order by name. Label the columns Employee and m y Monthly Salary, respectively. The HR department needs a report that displays the last name and hire date for all employees who were hired in Create a report to display the last name and job title of all employees who do not have a manager.

Create a report to display the last name, salary, and commission of all employees who earn commissions. Sort data in descending order of salary and commissions. Members of the HR department want to have more flexibility with the queries that you are e A writing. They would like a report that displays the last name and salary of employees who earn more than an amount that the user specifies after a prompt.

The HR department wants to run reports based on a manager. The HR department wants the ability to sort the report on a selected column. If you want an extra challenge, complete the following exercises: There are different types of single-row functions. This can be represented by a column name or expression. If n is O omitted, all characters to the end of the string are returned. Note: The functions discussed in this lesson are only some of the available functions.

LPAD column expression, n, Returns an expression left-padded to length of n 'string' characters with a character expression. RPAD column expression, n, Returns an expression right-padded to length of n 'string' characters with a character expression.

This is a feature that is available in Oracle8i and later versions. Because both names are now lowercase, a match is found and one row is selected. This section describes some of c the number functions. TRUNC column expression, n Truncates the column, expression, or value to n decimal MOD m,n t e r s places or, if n is omitted, n defaults to zero U I n Returns the remainder of m divided by n c l e Note: This list contains only some of the available number functions.

If the second c r a argument is 0 or is missing, the value is rounded to zero decimal places. If the second argument is 2, the value is rounded to two decimal places. Conversely, if the second argument is —2, the value is O ly rounded to two decimal places to the left rounded to the nearest unit of You will see examples later in this lesson.

The DUAL table is useful when you want to return a value only once for example, the value of a constant, pseudocolumn, or expression that is not derived from I n a table with user data.

If the second argument is 0 or is missing, the value is truncated to zero decimal places. If the second argument is 2, O ly the value is truncated to two decimal places. Conversely, if the second argument is —2, the value is decimal place to the left. Valid Oracle dates are between O ly January 1, B.

However, dates are not stored in the database in this format. All the components of the a e date and time are stored. U s and year, there is also time and century information associated with the date.

Use c r a the RR date format element instead of YY so that the century of the return value varies according to the specified two-digit year and the last two digits of the current year. The table in the slide O ly summarizes the behavior of the RR element. However, when the date column is displayed on the screen, the century component is not displayed by default. The DATE data type uses 2 bytes for the year information, one for century and one for year. The century value is always included, whether or not it is specified or displayed.

Therefore, if you are in a place in Australia and connected to a remote database in a location a e in the United States US , sysdate function will return the US date and time.

It subtracts the date on which the employee was hired from the current date SYSDATE and divides the result by 7 to calculate the number of weeks that a worker has been employed. Your results may differ depending on the date and time set for the operating system of your local database when you run the SQL query.

The result can be positive or negative. If date1 is later than date2, the result is positive; if date1 is earlier than date2, the result is negative. The value of n must be an integer and can be negative. The value of char may be a number representing a day or a character string. If the format model fmt is omitted, date is rounded to the nearest day. If the format model fmt is omitted, date is truncated to the nearest day.

When used with dates, c r a these functions round or truncate to the specified format model. Therefore, you can round dates to the nearest year or month. If the format model is month, dates result in the first day of the current O ly month. Dates result in the first day of the next month.

Months result in January 1 of the next year. Manipulate data items 2. Accept arguments and return one value per argument 3. Act on each row that is returned 4. Return one result per set of rows 5. May not modify the data type 6. Can be nested 7. Write a query to display the system date.

Label the column as Date. Note: If your database is remotely located in a different time zone, the output will be the date for the operating system on which the database resides. The HR department needs a report to display the employee number, last name, salary, and salary increased by Label the column New Salary. Post on Jan 1. Category: Documents 26 download. Tags: oracle training course oracle parkway oracle university exclusive property of sole discretion of oracle course labs disclaimerthis course proprietary information.

All rights reserved. Disclaimer This course provides an overview of features and enhancements planned in release 11g. Restricted Rights Notice If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United States Government, the following notice is applicable: U. You learn how r a to use SQL Developer for your database development tasks. With just a few clicks, you can easily create and debug stored procedures, test SQL statements, and view optimizer plans.

Therefore, it is a cross-platform tool. SQL Developer does not require an installer t e r U s and you need to simply unzip the downloaded file. To install SQL Developer, you need an unzip tool. Unzip the downloaded SQL Developer kit into the folder created in step 1.

The installation kit for l e SQL Developer 1. You may use either version of SQL c Developer in this course. Instructions for installing SQL Developer version 1. You can customize many aspects of the appearance and behavior of SQL Developer by setting preferences. To use SQL Developer, you must have at least one database connection, which may be existing, created, or imported. O ly You can create and test connections for multiple databases and for multiple schemas.

You can export connections to an XML file so that you can reuse it later. Enter the O ly username and password of the schema that you want to connect to. You can select the connection type as: n - t e r U s Basic: In this type, enter hostname and SID for the database you want to connect to.

Port is already set to Or you can also choose to enter the Service - I n name directly if you use a remote database connection. TNS: You can select any one of the database aliases imported from the c l - e tnsnames. Click Test to ensure that the connection has been set correctly. So, after you close the SQL Developer connection and open it again, you are not prompted for the password. The connection gets added in the Connections Navigator. You can expand the connection to view the database objects and view object definitions, for example, dependencies, details, statistics, and so on.

However, these connections are read-only connections that enable you to browse objects and data in that data source.

You can customize many aspects of the appearance of SQL Developer by setting preferences. For example, if you select a table in the Navigator, the details about columns, t U constraints, grants, statistics, triggers, and so on are displayed on an easy-to-read tabbed page.

Expand the Connections node in the Connections Navigator. Expand Tables. By default, the Columns tab is selected. It shows the column O description of the table. Using the Data tab, you can view the table data and also enter new rows, update data, and commit these changes to the database. Alternatively, you can create objects using the context menus. When created, you can edit the objects using an edit dialog or one of the many context-sensitive menus.

O ly As new objects are created or existing objects are edited, the DDL for those adjustments is l one or more objects in the schema. To open a dialog box for creating e r s a new table, right-click Tables and select New Table. The dialog boxes to create and edit t U database objects have multiple tabs, each reflecting a logical grouping of properties for that type of object. If you select the Advanced check box, the Create Table dialog box changes to one with multiple O ly options, in which you can specify an extended set of features while you create the table.

In the Connections Navigator, right-click Tables. In the Create Table dialog box, select Advanced. Specify column information. Click OK. Sometimes, you may want to edit the table that you have created; to do so, right-click the table in the Connections Navigator and select Edit.

You can use bind variables in the SQL statements, but not substitution a e 2. Commit: Writes any changes to the database and ends the transaction I n 4.

Rollback: Discards any changes to the database, without writing them to the database, and ends the transaction l e 5. Cancel: Stops the execution of any statements currently being executed c 6. Execute Explain Plan: Generates the execution plan, which you can see by clicking the Explain tab 8.

Enter SQL statements. Results are shown here. Commands not n a e supported by the SQL Worksheet are ignored and are not sent to the Oracle database. Alternatively, e r s In the example in the slide, because there are multiple SQL statements, the first statement is t U I n terminated with a semicolon. The cursor is in the first statement, and therefore, when the statement is executed, results corresponding to the first statement are displayed in the Results box.

You can have multiple files open at the same time. Each file displays as a Script Pathing I n l e You can select a default path to look for scripts and to save scripts. The Open O ly 2. Use the command, followed by the location, and name of the file you want to run, in the 2. After formatting, the SQL code is beautified with the l a e keywords capitalized and the statement properly indented.

When you place your cursor here, it shows the Snippets window. From the drop-down list, you can select the functions category you want. SQL Developer has the feature called Snippets. You can drag snippets into the Editor window. You can use the drop-down list to select a group. A Snippets button is placed in the right window margin, so that you can display the e r s Snippets window if it becomes hidden. Then you can edit the syntax so that the SQL function is valid in the current context.

To see a brief description O ly of a SQL function in a tool tip, place the cursor over the function name. Provide the location of the sqlplus. You cannot resume execution from this point; instead, to start running or debugging from the beginning of the function or procedure, l e click the Run or Debug icon in the Source tab toolbar.

O These options are also available as icons in the debugging toolbar. Individual reports are r a displayed in tabbed panes at the right side of the window; and for each report, you can select O using a drop-down list the database connection for which to display the report. For reports about objects, the objects shown are only those visible to the database user associated with the selected database connection, and the rows are usually ordered by Owner. You can also create your own user-defined reports.

Organize reports in folders. To create a user-defined report, perform the following steps: r a 1. Then, click Apply.

You can also include an optional tool tip to be displayed I n when the cursor stays briefly over the report name in the Reports navigator display. To create a folder for user-defined reports, right-click the User Defined Reports node r a or any folder name under that node and select Add Folder. Information about user-defined reports, including any folders for these reports, is stored in a file named UserReports.

Also, you have shortcut icons to some of the frequently used tools such as Notepad, Microsoft Word, and Dreamweaver, available to you. To do so, perform the following: n a e 1. From the Tools menu, select External Tools. In the External Tools dialog box, select New to add new tools. Therefore, users will no longer be able to connect to an Oracle 8. Create a folder. Note: As with version 1.

These are the same options that are found in the Debug menu in version 1. Using SQL r a Developer, you can browse, create, and edit database objects.

SQL Developer enables you to create and save your own special set of reports for repeated use. Version 1. Oracle SQL contains many extensions. It contains its own command language. To log in from a Windows environment: r a O ly 1. Enter the username, password, and database name. Log on to your machine. Enter the sqlplus command shown in the slide.

In the syntax: I n username Your database username c l e password Your database password Your password is visible if you enter it here. O Instead, enter only your username.

Enter your password at the password prompt. The result c must contain data. In the result: r a Null? The SQL prompt then appears. The new current line is displayed. The newly edited line is a e displayed. Verify the new contents of the buffer by using the LIST command. In this case, replace the employees table with the departments table. The default extension is. GET filename [. The default extension for the file name is. OFF closes the spool file. OUT closes the spool file and sends the file results to the printer.

In this way, you can store frequently used scripts for use in the future. You can also, alternatively, use the symbol to run a script. This opens an editor with the script file in it.

The delimiter must be the first character of a l a e new line immediately following the statement. You can now append to, or replace an existing file, where previously you could only use SPOOL to create and replace a file. O ly To spool output generated by commands in a script without displaying the output on the screen, run interactively.

It supports every stage of the software development life cycle SDLC from modeling to deploying. This innovative approach makes J2EE development simple and efficient. A connection serves several O ly purposes from browsing the database and building applications, all the way through to deployment. The Applications - Navigator provides an infrastructure that the different extensions can plug into and use to organize their data and menus in a consistent, abstract manner. The raw files that make a e up these abstract nodes appear in the Structure window.

O ly In the Structure window, you can view the document data in a variety of ways. When the current selection is a node in the navigator, the default editor is assumed. The tabs at the top of the editor window are the document tabs. Selecting a document tab gives O ly that file focus, bringing it to the foreground of the window in the current editor.

Selecting an l a e editor tab opens the file in that editor. Create a database connection. Create a deployment profile. Deploy the objects. Expand Database and select a database connection. In the connection, expand a schema.

Right-click a folder corresponding to the object type Procedures, Packages, Functions. Enter a valid name for the function, package, or procedure and click OK.

A skeleton definition is created and opened in the Code Editor. You can then edit the I n subprogram to suit your need. You may need to change the NULL values with reasonable values that are passed into the program unit.

After you change the values, click OK. The output is displayed in the Message-Log window. The Drop Confirmation dialog a box appears; click Yes. The object is dropped from the database. A local debugging session is started by r a setting breakpoints in source files, and then starting the debugger.

Remote debugging requires two JDeveloper processes: a debugger and a debuggee, which may reside on a different platform. This option can be enabled using various ways.

For example, you can specify parameters being passed or t e r details about what was tested. U s return values from a function giving you more control over what is run and providing you output I n Note: The procedures or functions in the Oracle database can be either stand-alone or within a package.

Create a database connection using the Database Wizard. In the Navigator, expand the Database node to display the specific database username and schema name. Expand the Schema node. Expand the appropriate node depending on what you are debugging: procedure, function, or package body. Optional for debugging only Select the function, procedure, or package that you want to debug and double-click to open it in the Code Editor.

Note: The breakpoint must be set on an executable line of code. If the debugger does not stop, the breakpoint may have not been set on an executable line of code verify that the breakpoint was set correctly. Make sure that either the Code Editor or the procedure in the Navigator is currently selected. Click the Debug toolbar button, or, if you want to run without debugging, click the Run toolbar button.

In some cases, you may need to write additional code to initialize values to be passed as arguments. Click OK to execute or debug the target. Analyze the output information displayed in the Log window. U displayed. I n In the case of functions, the return value is displayed. It is a trigger in r a a program that, when reached, pauses program execution allowing you to examine the values of some or all of the program variables.

By setting breakpoints in potential problem areas of your O ly source code, you can run your program until its execution reaches a location you want to debug. You can then use the debugger to a e view the state of your program.

Breakpoints are flexible in that they can be set before you begin n t e r U s a program execution or at any time while you are debugging. To set a breakpoint in the Code Editor, click the left margin next to a line of executable code. I n Breakpoints set on comment lines, blank lines, declaration, and any other non-executable lines of code are not verified by the debugger and are treated as invalid. The debugger pauses r a the program execution at the point where the breakpoint is set. At this point, you can check the values of the variables.

You can continue with the program execution by clicking the Resume O ly icon. The debugger will then move on to the next breakpoint. After executing all the Debugging — Log area. You can modify program data values during a debugging session as a way to test hypothetical bug fixes during a program run. You use the Data window to display information about variables in your program. The Data n a e window displays the arguments, local variables, and static fields for the current context, which is t e r U s controlled by the selection in the Stack window.

If you move to a new context, the Data window is updated to show the data for the new context. If the current program was compiled without I n debug information, you will not be able to see the local variables. After you enter a watch expression, the Watch window displays the current value of the expression. As your program runs, the value of the watch changes as your program updates the O ly values of the variables in the watch expression.

It displays the call stack r a for the current thread. When you select a line in the Stack window, the Data window, Watch window, and all other windows are updated to show data for the selected class.

Thus, declaring a cursor variable creates a pointer, not an item. However, cursors differ from cursor variables the way constants differ from variables. A cursor n a e is static, but a cursor variable is dynamic because it is not tied to a specific query.

You can open t e r U s a cursor variable for any type-compatible query. This gives you more flexibility. You can pass cursor variables back and forth between an application and server through remote procedure calls O RPCs. Therefore, you can pass the value of a cursor variable freely from one scope to another.

For example, you can declare a cursor variable on the client side, open and fetch c l e from it on the server side, then continue to fetch from it back on the client side. A cursor variable holds a reference to the cursor work area in the PGA instead of addressing it O with a static name.

Because you address this area by a reference, you gain the flexibility of a variable. Unlike packaged variables, cursor variables do not have persistent states. Remember, declaring a cursor variable creates a pointer, not an item. Cursor variables cannot be saved in the database; they follow the usual scoping and instantiation rules. END; Any bind arguments in the query are evaluated only when the cursor variable is opened.

Thus, to fetch rows from the cursor using different bind values, you must reopen the cursor variable with the bind arguments set to their new values. You can use a different l e INTO clause on separate fetches with the same cursor variable. Each fetch retrieves another row c from the same result set. After that, the associated result set is undefined. In these practices, you apply the concepts that you learned in the course.

These additional practices provide supplemental practice in declaring variables, writing executable statements, interacting with the Oracle server, writing control structures, and working with composite data types, cursors, and handle exceptions. Evaluate each of the following declarations. Determine which of them are not legal and explain why. In each of the following assignments, determine the data type of the resulting expression.

For the exercises below, you must create a temporary table to store the results. Store a department number in a substitution variable. In the executable part of the program, do the following: a.

Store an employee name in a substitution variable. Update the department ID of the employee with the new department number, and e c l update the salary with the new salary. Use the emp table for the updates. Process each row from the cursor, and if the salary is greater than 15, and the hire date is later than FEB, display the employee name, salary, and hire date in the window in the format shown in the sample output below: Pass a parameter of the DATE data type to the cursor and print the details of all the employees who have joined after that date.

Use the EMP table for this practice. Verify the results by querying the emp table. For the exercise below, you will require a table to store the results. Query the employees table to find out whether the number of years that the employee has been with the organization is greater than five; and if the salary is less than 3,, raise an exception.

Handle the exception with an appropriate exception handler that inserts the following values into the analysis table: employee last name, number of years of service, and the current salary. Otherwise display Not due for a raise in the window. Verify the results by querying the analysis table. A Boolean data type cannot be assigned a date value. The data type should be date.

For the following exercises, you will require a temporary table to store the results. Verify your results by querying the TEMP table. In the executable part of the program, do the following: d e 7. Store his or her salary in the sal variable c. Update the department ID of the employee with the new department number, and update the salary with the new salary. Process each row from the cursor, and the employee name, salary, and hire date in the window.

Use the emp table for this practice. The DATE data type always stores year information as a four-digit number internally: two digits for the century and two digits for the year. For example, the Oracle database stores the year as or , and not just as 87 or Hence, if you are in a place in Australia and connected to a remote database in a location in the United States US , sysdate function will return the US date and time.

Arithmetic with Dates Because the database stores dates as numbers, you can perform calculations using arithmetic operators such as addition and subtraction. You can add and subtract number constants as well as dates. Using Arithmetic Operators with Dates The example in the slide displays the last name and the number of weeks employed for all employees in department It subtracts the date on which the employee was hired from the current date SYSDATE and divides the result by 7 to calculate the number of weeks that a worker has been employed.

Your results may differ depending on the date and time set for the operating system of your local database when you run the SQL query. If a more current date is subtracted from an older date, the difference is a negative number. Date-Manipulation Functions Date functions operate on Oracle dates.

The result can be positive or negative. If date1 is later than date2, the result is positive; if date1 is earlier than date2, the result is negative. The noninteger part of the result represents a portion of the month.

The value of n must be an integer and can be negative. The value of char may be a number representing a day or a character string. If the format model fmt is omitted, date is rounded to the nearest day. If the format model fmt is omitted, date is truncated to the nearest day. When used with dates, these functions round or truncate to the specified format model. Therefore, you can round dates to the nearest year or month. If the format model is month, dates result in the first day of the current month.

Dates result in the first day of the next month. If the format model is year, months result in January 1 of the current year. Months result in January 1 of the next year. Example: Compare the hire dates for all employees who started in Summary Single-row functions can be nested to any level.

Practice 3: Overview This practice provides a variety of exercises using different functions that are available for character, number, and date data types. Write a query to display the system date. Label the column as Date. Note: If your database is remotely located in a different time zone, the output will be the date for the operating system on which the database resides.

The HR department needs a report to display the employee number, last name, salary, and salary increased by Label the column New Salary.

Label the column Increase. Run the revised query. Rewrite the query so that the user is prompted to enter a letter that the last name starts with. The HR department wants to find the duration of employment for each employee. For each employee, display the last name and calculate the number of months between today and the date on which the employee was hired. Order your results by the number of months employed.

Round the number of months up to the closest whole number. Create a query to display the last name and salary for all employees. Each asterisk signifies a thousand dollars. Sort the data in descending order of salary. Create a query to display the last name and the number of weeks employed for all employees in department Truncate the number of weeks value to 0 decimal places.

Objectives This lesson focuses on functions that convert data from one type to another for example, conversion from character data to numeric data and discusses the conditional expressions in SQL SELECT statements. However, the Oracle server internally converts such data types to Oracle data types. In some cases, the Oracle server receives data of one data type where it expects data of a different data type.

When this happens, the Oracle server can automatically convert the data to the expected data type. This data type conversion can be done implicitly by the Oracle server or explicitly by the user.

Implicit data type conversions work according to the rules explained in the next two slides. Explicit data type conversions are done by using the conversion functions. Conversion functions convert a value from one data type to another. Generally, the form of the function names follows the convention data type TO data type. The first data type is the input data type and the second data type is the output. Note: Although implicit data type conversion is available, it is recommended that you do the explicit data type conversion to ensure the reliability of your SQL statements.

Implicit Data Type Conversion Oracle server can automatically perform data type conversion in an expression. Implicit Data Type Conversion continued In general, the Oracle server uses the rule for expressions when a data type conversion is needed.

If this parameter is omitted, this function uses the default date languages for the session. A format model is a character literal that describes the format of datetime stored in a character string.

But be sure to separate the date value from the format model with a comma. Indicates B. Elements of the Date Format Model Use the formats that are listed in the following tables to display time information and literals, and to change numerals to spelled numbers.

The hire date appears as 17 June This technique is especially useful with concatenation. The default is a period. Decimal point in position specified You can specify multiple group separators in a number format model.

The format model that you select is based on the previously demonstrated format elements. Without fx, the Oracle server ignores extra blanks. Without fx, the numbers in the character argument can omit leading zeros. There are two spaces after the month May and the number 24 in the following example.

Because the current year is greater than , the RR format interprets the year portion of the date from to The following command, on the other hand, results in no rows being selected because the YY format interprets the year portion of the date in the current century Nesting Functions Single-row functions can be nested to any depth. Nested functions are evaluated from the innermost level to the outermost level.

Some examples follow to show you the flexibility of these functions. Nesting Functions continued The slide example displays the last names of employees in department The evaluation of the SQL statement involves three steps: 1.

The inner function retrieves the first eight characters of the last name. The outermost function converts the results to uppercase. The entire expression becomes the column heading because no column alias was given. Example: Display the date of the next Friday that is six months from the hire date. The resulting date should appear as Friday, August 13th, Order the results by hire date. General Functions These functions work with any data type and pertain to the use of null values in the expression list.

If expr1 is null, NVL2 returns expr3. The argum ent expr1 can have any data type. If any column value in an expression is null, the result is null. To calculate values for all employees, you must convert the null value to a number before applying the arithmetic operator.

In the example in the slide, the NVL function is used to convert null values to zero. If the first expression is not null, then the NVL2 function returns the second expression.

If the first expression is null, then the third expression is returned. The argument expr1 can have any data type. The arguments expr2 and expr3 can have any data types except LONG. If the data types of expr2 and expr3 are different, the Oracle server converts expr3 to the data type of expr2 before comparing them, unless expr3 is a null constant.

In the latter case, a data type conversion is not necessary. If they are equal, the function returns a null. If they are not equal, the function returns the first expression. However, you cannot specify the literal NULL for the first expression. If they are equal, then the function returns null. If they are not, then the function returns expr1. However, you cannot specify the literal NULL for expr1. When the lengths of the names are equal, a null value is displayed.

When the lengths of the names are not equal, the length of the first name is displayed. If none of the WHEN Otherwise, the Oracle server returns a null. For all other job roles, there is no increase in salary. This is an example of a searched CASE expression. In a searched CASE expression, the search occurs from left to right until an occurrence of the listed condition is found, and then it returns the return expression.

If the expression is the same as search, result is returned. If the default value is omitted, a null value is returned where a search value does not match any of the result values. In this example, you determine the tax rate for each employee in department 80 based on the monthly salary. Remember that for nested functions, the results are evaluated from the innermost function to the outermost function.

Label the column Dream Salaries. Display the last name, hire date, and day of the week on which the employee started. Label the column DAY. Order the results by the day of the week, starting with Monday. Rewrite the statement in the preceding exercise using the CASE syntax. Objectives This lesson further addresses functions. It focuses on obtaining summary information such as averages for groups of rows. It discusses how to group rows in a table into smaller sets and how to specify search criteria for groups of rows.

Group functions operate on sets of rows to give one result per group. What Are Group Functions? Unlike single-row functions, group functions operate on sets of rows to give one result per group. These sets may comprise the entire table or the table split into groups.

Types of Group Functions Each of the functions accepts an argument. You may have multiple group functions separated by commas. The default is ALL and therefore does not need to be specified. The example in the slide displays the average, highest, lowest, and sum of monthly salaries for all sales representatives.

The example in the slide displays the most junior and most senior employees. In contrast, COUNT expr returns the number of non-null values that are in the column identified by expr. The example in the slide displays the number of employees in department The example in the slide displays the number of employees in department 80 who can earn a commission.

Group Functions and Null Values All group functions ignore null values in the column. However, the NVL function forces group functions to include null values. The average is calculated as the total commission that is paid to all employees divided by the number of employees receiving a commission four. The average is calculated as the total commission that is paid to all employees divided by the total number of employees in the company Creating Groups of Data Until this point in our discussion, all group functions have treated the table as one large group of information.

At times, however, you need to divide the table of information into smaller groups. You can then use the group functions to return summary information for each group. The example in the slide displays the department number and the average salary for each department. The rows are grouped by department number, so the AVG function that is applied to the salary column calculates the average salary for each department.

For example, the SELECT statement in the slide displays the average salaries for each department without displaying the respective department numbers. Without the department numbers, however, the results do not look meaningful. Grouping by More than One Column Sometimes you need to see results for groups within groups.

The slide shows a report that displays the total salary that is paid to each job title in each department. For example, the four stock clerks in department 50 are grouped together, and a single result total salary is produced for all stock clerks in the group.

Find the average salary for each department by grouping by department number. Rows are grouped. The group function is applied. The group function is applied to the group. The example excludes sales representatives and sorts the list by the total monthly salary. Nesting Group Functions Group functions can be nested to a depth of two functions. The Oracle server evaluates the clauses in the following order: 1.

Practice 5: Overview At the end of this practice, you should be familiar with using group functions and selecting groups of data. Circle either True or False.

Group functions work across many rows to produce one result per group. Group functions include nulls in calculations. Find the highest, lowest, sum, and average salary of all employees. Label the columns as Maximum, Minimum, Sum, and Average, respectively.

Round your results to the nearest whole number. Write a query to display the number of people with the same job. Generalize the query so that the user in the HR department is prompted for a job title. Determine the number of managers without listing them. Label the column as Number of Managers. Find the difference between the highest and lowest salaries. Create a report to display the manager number and the salary of the lowest-paid employee for that manager.

Exclude anyone whose manager is not known. Sort the output in descending order of salary. Create a query to display the total number of employees and, of that total, the number of employees hired in , , , and



0コメント

  • 1000 / 1000