This action might not be possible to undo. Are you sure you want to continue?
Part 2. Data Definition Language, Views, SET operations, Formatting the output,
DATABASE MANAGEMENT SYSTEMS
The Data Manipulation Language
This is the section of SQL which handles data manipulation, i.e. inserting, updating and deleting rows in tables. It consists of three basic statements INSERT UPDATE DELETE allows insertion of records into a table updates existing rows in a table removes unwanted rows from a table
These statements are incorporated into what is known as a transaction
INSERTing rows into a table
The INSERT INTO statement has a number of forms, as the following examples show INSERT INTO <tablename> VALUES(value1, value2, value3,.....); This form allows insertion of ONE complete row into the table. The values in the list must be in the same order as the columns in the table and there must be a value for each column. So to insert a new row into the EMP table INSERT INTO emp VALUES (7999, ‘cox’, ‘CLERK’, 7369, ‘01-APR92’, 2000,250,20); If you do not have values for all the columns, a list of columns may be specified and values provided in the same order as the specified columns. INSERT INTO emp(empno, ename, hiredate, deptno) VALUES (7888, ‘PITT’, ‘29-FEB-92’, 30); All unspecified columns will be set to NULL. N.B. Only one row at a time may be inserted using the above forms of the INSERT statement.
DATABASE MANAGEMENT SYSTEMS
Multiple rows may be inserted by using a SELECT statement to bring in rows from another table. (Obivously this form can not be used for raw data input - only data which already exists in an Oracle table) INSERT INTO bonus (empno, manager, highsal) SELECT empno,ename,sal*1.1 FROM emp WHERE job = ‘MANAGER’ This takes data about managers from the emp table and copies it into the bonus table.
DATABASE MANAGEMENT SYSTEMS
25.. or more generally UPDATE <tablename> SET (col_1. WHERE <condition> Values supplied may be derived from expressions e. The SELECT statement may be used to provide the new values for the update (as shown above). every row in the table will be updated to your specified value. Remember if a WHERE clause isn’t used to limit the number of rows updated..1. hence the following is illegal.. UPDATE emp SET comm = (SELECT avg(comm)/2 FROM emp). DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .. UPDATE <tablename> SET column = value..UPDATEing existing rows The UPDATE statement allows you to change the values of existing rows in an Oracle table.comm) = (sal * 1. But only one column may be specified if you are using such expressions.) = val_1. UPDATE emp SET (sal. UPDATE emp SET sal = sal*1. val_2.. comm/2).g. col_2. It may also be used to decide which of the rows in a table should suffer the update UPDATE emp SET comm = (SELECT MIN(comm) FROM emp WHERE deptno = 10) WHERE job = ‘SALESMAN’.
DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . Like INSERT. no space is freed up in the Oracle database for use by other tables. The following statement does not contain a WHERE clause DELETE FROM emp. This will delete every row from the emp table .DELETEing unwanted rows The DELETE statement allows you to remove one or more unwanted rows from a table. Care must be taken with the DELETE statement. The space used by a table does not dynamically shrink when data is deleted from the table. This will delete JONES’s record from the emp table.and it does not even ask for confirmation! Always make sure you use a WHERE clause in any DELETE statement (unless you really want to wipe a table). it functions on whole rows of data DELETE FROM emp WHERE ename = ‘JONES’. Incidentally. when a table is wiped.
If you wish to make your changes permanent (which means they will not be able to be rolled back) you should issue the command. you may roll them back out of the database by replacing them with the original values. the user logs off Oracle in normal fashion 2.COMMITting the changes Normally. This can be done by issuing the command SQL>ROLLBACK. These units consist of a number of DML statements which all should succeed in order to keep the database consistent. a COMMIT statement should only be issued after the second update statement and not after the first. This will rollback all your changes since the last commit was performed. Sometimes Oracle will perform its own implicit commit (no message is given when this happens). it would be possible for a department to have a new value in the dept table. Hence. A user process terminates abnormally Oracle can now perform statement level rollback .all succeed or all fail (no halfway measures). immediately after it executes a DDL command Oracle will automatically perform an implicit rollback whenever 1. but employees to be left ‘dangling’ with an old defunct department number in the emp table.see the SQL*Plus Reference Guide The Data Definition Language DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . if you decide that your changes are an error. If a COMMIT is issued after the first statement. The use of these two commands enables you to design logical units of work (known as transactions). This change should occur in both the department table and the employee table in order to keep the database consistent. immediately before it executes a DDL command 3. SQL>COMMIT. This is also known as transaction atomicity . A typical scenario could be one in which you might wish to change a department number. or all should be rolled back. Oracle performs an implicit commit whenever 1.
. col_2 datatype [NULL NOT NULL]. where col_x may be any alphanumeric name starting with an alphabetic character.DDL statements change the structure of the database.. ..........d) numeric data of total width W and d decimal places DATE LONG dates (including a time element down to seconds) up to 64K of free format text (limited to one LONG per table) LONGs may not be used in functions or WHERE clauses optionally use NULL or NOT NULL to specify whether the column can accept NULL values. The CREATE TABLE is progressively becoming more complex .. NULL values are allowed.. The default is NULL i..particularly so in Oracle 7.). The name may also contact ‘$’ ‘_’ ‘#’ ‘@’ (maximum 30 characters) datatype may be one of the following CHAR VARCHAR NUMBER allows variable length alphanumeric data up to 255 characters in length (will change in Oracle 7 to fixed length!) allows variable length alphanumeric data up to 255 characters in length numeric data .. This treatment merely covers the basic statement.... There are three basic commands CREATE ALTER DROP any used to create new objects (tables... CREATEing a table CREATE TABLE emp DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .. etc) in the database used to change the structure of an existing object used to expunge the object from the database (all its data plus reference to it in the data dictionary) To create a new table use the CREATE TABLE statement CREATE TABLE <tablename> ( col_1 datatype [NULL NOT NULL].e. views.maximum of 38 digits (will also accept scientific notation) NUMBER (W.......
CHAR(12). NUMBER(4) NOT NULL. SQL*Plus will use the current defaults. NUMBER(7. Note that NOT NULL is specified for the empno column.2).not recommended reserved word in SQL Names which are already given to existing objects owned by the user. CHAR(12.2).( empno ename job mgr hiredate sal comm deptno NUMBER(4) NOT NULL. are also prohibited ALTERing the table structure To modify the definition or structure of a table. When a table is created you may specify criteria for its storage (such as initial space allocation). See the SQL Language Reference Manual or the DBA Guide t V6. Valid table names emp2 EMP2 2emp PROJ-ASST PROJ_ASST PROJ ASST “PROJ ASST” UPDATE OK NO NO OK NO OK NO OK starts with a letter table names are not case-sensitive starts with a number the ‘-’ is not a valid character use of underscore is recommended to link words spaces are not allowed spaces allowed within double quotes . NUMBER(4) DATE. use the ALTER TABLE command To add a new column DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . NUMBER(7. This column will be used as the primary key. If the storage clause is not used.
ALTER TABLE emp ADD (GENDER CHAR(1)). e. you may add extra NULL or NOT NULL columns change the datatype of an existing column alter an existing column to be NULL or NOT NULL make the width of the column smaller or larger If the table contains rows.g. e. ALTER TABLE emp MODIFY (deptno NUMBER(6)). You may not ‘drop’ or ‘delete’ a column using ALTER. There is no direct support in SQL for removing columns from a table! You may not rename a column using ALTER.g. but there are no values in the column in question make the column width smaller or larger change the datatype If the column already has data values make the column width larger (not smaller) force the column to be NOT NULL if there are no NULLs already present in the column 2. Again there is no direct support in SQL for this. The use of the ALTER TABLE statement to change column definitions is restricted as follows 1.ALTER TABEL <tablename> ADD (column_name datatype). To modify an existing column ALTER TABLE <tablename> MODIFY (deptno NUMBER(6)). 3. DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . If the table does not contain any data.
indexes. DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . Good back up and recovery procedures need to be in place if this type of statement could possibly be used in error. It will also remove any indexes which are based on that table. dname FROM dept. One method which may be used is as follows:To delete the column LOC from the dept table 1. 3. This means you cannot even roll it back. Column headings will default to those in the dept table. (Only the creator of the table may DROP it) DROP TABLE <tablename>. The DROP statement may be used to drop tables.. Create a new table which is an angle of the dept table excluding the LOC column CREATE TABLE newdept AS SELECT deptno. but it may not be used to drop columns. views. this produces a table containing all the data for deptno and dname which already exists in the dept table. Rename the new table to the old table name RENAME newdept TO dept. Deleting columns from tables can not be done directly. It frees up any space they were occupying and removes all references to them from the data dictionary. Now drop the old table DROP TABLE dept. 2.DROPping objects from the database The DROP statement may be used to remove entire unwanted objects from the database. synonyms etc. will remove the specified table (with its contents) from the database. Remember that this statement is very severe and should be used with extreme caution No confirmation is requested by Oracle in order to perform this operation Oracle issues an implicit commit both before and after it processes the DROP command.
VIEWS Views can be regarded as windows through which users may see data stored in database tables. They have a number of attractive features:(i) they do not own any data of their own hence they take up virtually no space in the database (in fact the only space consumed is that required for their definition in the relevant data dictionary tables) (ii) they are automatically activated when the user references them in an SQL statement this means they will always reflect the current state of the database (iii) they may be simple or arbitrarily complex views may be based on single or multiple tables and may also reference other views views may be tailored to suit user requirements and make the users task easier (e.g. avoid specification of complex joins) simple views are based on a single table and only contain columns which are directly stored in the table in question (iv) views are merely stored SQL statements hence they can be defined using familiar SQL constructs (v) may be treated as tables in SQL queries almost 100% compatible with table usage (vi) can be used to implement row level security within SQL *Plus the GRANT statement does not provide this functionality (vii) may be used to implement integrity (including referential) checks Oracle7 will use constraints to perform this function (viii) useful in providing a level of data independence for application programs their use allows the structure of the database to change with minimal effect on users and application programs DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .
so there is a probable increase in disk I/O when views are used. mainly in increased parse times. you merely drop the view and run your amended view definition file.they are essentially stored SQL statements. it may be advisable to save their definitions in a command file in case they subsequently need to be changed. With this. The use of views can present a performance overhead.VIEW MANAGEMENT View definitions may be observed using the following dictionary views USER_VIEWS ALL_VIEWS DBA_VIEWS these show the viewnames along with the full view definitions Views may be created using the CREATE VIEW <viewname> command. (Remember no storage definition will be required.DML should never be performed on the dictionary tables. Remember also that Verson 6 does not possess a view cache. any views built on that table will remain in existance but will become invalid. DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . So for complex views.) They may be dropped using the DROP VIEW <viewname> command. Note that when a table is dropped or becomes inaccessable. It is important to realise that views may not be altered . When using a DBA account do not be tempted to update view definitons as stored in the data dictionary .
sal*12 + NVL(comm. annual_sal.this must be specified outside of the view in the normal SELECT statement e. In the above example. Views cannot contain an ORDER BY clause . annual_sal respresents sal*12 from the base table. sal.. total AS SELECT ename.0) FROM emp. job.col_2. job.)] AS SELECT ename. At this point Oracle will reply with ‘View created.0). sal*12. DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . sal FROM dept30 WHERE comm IS NOT NULL. Complex views can be used to make life easier for the user and also to present virtual columns (columns which do not exist in the database) CREATE VIEW total_comp (employee..g. NVL(comm. salary.CREATEing Views The CREATE VIEW command allows you to create a view by specifying a standard SQL query: CREATE VIEW <viewname> [(col_1. SELECT * FROM dept30 ORDER BY sal.. comm FROM emp WHERE deptno = 30. Views which contain virtual columns MUST have their own column headings specified.’ The view can be used and referenced as you would a normal Oracle table SELECT ename.. sal. commission.
This can only be performed on what are known as simple views. Remember that they can be treated as base tables (queries will work just as effectively against views as they will against base tables almost 100% of the time). sal. one will encounter some very serious problems when attempting to manipulate data through views. However.-------- ---------. comm. dname. loc FROM emp. The ability to perform DML operations on views in an Oracle database is currently severely restricted. Often there are good reasons for this. Views on more than one table suffer similar restrictions: CREATE VIEW deptemp AS SELECT empno. DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . The output from such a view would look like EMPNO ENAME HIREDATE SAL 2000 COMM 500 DEPTNO 30 DNAME SALES LOC --------7777 CHICAGO --------COX -----------11-APR-92 ----. It is tempting to make heavy use of views. This view contains an aggregate function which renders all the data seen through the view non-updatable.deptno = dept. Obviously Oracle has a problem because this would probably translate into two separate deletes on the two tables.--------- ---------- What if the user wishes to delete COX’s details from the view? They would probably attempt the following operation DELETE FROM deptemp WHERE ename = ‘COX’. views have a number of attractive features.deptno. dept WHERE emp. ename.Data Manipulation As already seen. If this were allowed to go ahead we could easily find the remaining employees in COX’s department having no correspondence department record in the department table. hiredate.Views . Consider the following view definition: CREATE VIEW summary AS SELECT deptno. deptno. avg(sal) FROM emp GROUP BY deptno.
DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . a simple salary change.In fact all DML operations on views based on more than one table are disabled. theoretically. This is somewhat over protective as. many of the possible update operations should be allowed .g.e.
sal + comm): updates allowed on all but the virtual columns delete operations are unrestricted inserts are allowed if . Views based on the join of one or more tables (or views): no DML is allowed on any column in the view 3. 1111. comm. Simple views which do not possess ALL of the NOT NULL columns: no INSERTion of rows is possible (only updates and deletes) 5. Views containing GROUPed set of data: no DML is allowed on any column in the view 2. 4. Views containing virtual columns (e. ‘CoX’. 9999). ename. INSERT INTO virtualcols VALUES (7777. The following statements are legal UPDATE virtualcols SET sal = 9999 WHERE empno = 7934. 8888. 1111) The following statements are illegal UPDATE virtualcols SET total = 9999 WHERE empno = 7934. sal. INSERT INTO virtualcols VALUE (7777. 8888. Views containing the WITH CHECK OPTION DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .all not null columns are specified and no attempt is made to insert a value in any of the virtual column(s) Hence given the view CREATE VIEW virtualcols AS SELECT empno.UPDATEing Views The Rules 1. ‘COX’. sal + comm total FROM emp.g.
see table constraints in Oracle7 DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .Updates are restricted to those which result in data which still compiles with the check (data migration is prevented) .
projno = p. This view is designed to display information on employees and their projects as shown below and can obviously be referenced in application programs Pers Ename --------smith allen Sal ----2000 1800 Pname --------alpha beta DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . Project Employee The tables built to handle this situation would probably look like: PROJECT Projno --------101 102 103 Pname --------alpha beta psi Budget --------9. sal.VIEWS . project p WHERE e. where each project may have a number of employees but each employee may only be assigned to one project.000 EMPLOYEE Empno --------7369 7499 7782 7932 7654 7788 Ename --------smith ford allen ward james scott Sal ------2000 3000 1800 1500 1600 5000 Projno -------101 101 102 101 103 102 For convenience we could create a view based on these tables: CREATE VIEW pers AS SELECT ename.Logical Data Independence Suppose we have this data model. pname FROM employee e.100 54.projno.600 10.
Project Projno -------101 102 103 Pname -------alpha beta psi Budget --------9. This small change in the requirements will result in a massive change in the database design. Project Employee This relationship must be resolved by the introduction of a new entity (intersecting entity) to hold details of who is working on which project. Project Employee Assignments The following tables now have to be constructed .Now suppose the rules change such that employees may be assigned to more than one project.100 54.600 10.000 Employee Empno --------7369 7499 7782 7932 7654 7788 Ename -------smith ford allen ward james scott Sal ---2000 3000 1800 1500 1600 5000 DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .a significant design change. If we take a look at the new entity model we will see that there is now a ‘many to many’ relationship between employees and their projects.
Assignment Projno -------101 101 102 Empno --------7369 7499 7369 Start_Date ------------03-apr-90 01-apr-90 25-dec-89 End_Date -----------04-apr-90 31-apr-90 31-dec-89 View Maintenance DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .
First drop the old view (views may not be altered) DROP VIEW pers. assignment a WHERE e. As columns may not be dropped from tables. CREATE VIEW pers AS SELECT ename.projno = a. If applications have referenced the view called pers they will now still work without modification. sal. However in terms of using the pers view.projno. SET operations Oracle possesses a number of functions which can be used to perform set (as in mathematics) operations DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . a new image of the employee table may be created which excludes the projno column. Obviously if applications reference the underlying base tables. these values must be set to NULL.empno = a. pname FROM employee e. they would need to undergo significant changes. At this stage it is worth remembering that the employee table will still contain values for projno.This change could cause a hiatus with our application programs. A new view must now be created which will display the same data as the old view but handles the change in table structure.empno AND p. project p. we can cope with the new table structure as follows. Alternatively.
These are UNION INTERSECT MINUS They are normally applied across two or more SELECT statements e.. The UNION operator. SELECT ...... UNION This operator presents rows which are returned by any of the SELECT statements involved in the query (if effectively ‘Ors’ the results of the SELECT statements) SELECT ename. sal FROM consultants WHERE contract_date> ‘01-MAY-92’.. sal FROM emp WHERE job = ‘MANAGER’ UNION SELECT ename.g... The columns must also be of the same datatype and in the same order they do not have to have the same name. Employees names and salaries are returned for both managers and all people in department 10 Obviously the above statement could have been performed using an OR e..... sal FROM emp WHERE job = ‘MANAGER’ UNION SELECT ename. UNION SELECT ... SELECT ename.... The final presented column will have the same heading as the one specified in the first selected statement.g. So DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .. FROM .e. sal FROM emp WHERE job = ‘MANAGER’ OR deptno = 10. however. SELECT ename.......... UNION operations The same number of columns must be selected by all query blocks in the ‘UNION’ statement.. is more general than the OR operator in that it can work ‘ ‘across’ tables .g.. FROM ... sal FROM emp WHERE deptno = 10.
comm. Incidentally ‘DISTINCT’ can not be used in direct association with the UNION keyword. sal. will produce as follows ENAME ---------SMITH FORD : SAL ----2000 230 : DEPTNO -----------10 30 : notice sal and comm values are mixed under the heading SAL Beware that when using UNIONs. deptno FROM emp WHERE deptno = 10 UNION SELECT ename. duplicate rows are automatically eliminated! This is NOT the case when using OR . deptno FROM emp WHERE deptno = 30.the DISTINCT keyword is required. [ Oracle at present has no support for OUTER UNIONs ] DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .SELECT ename.
SELECT ename. sal FROM emp WHERE job = ‘MANAGER’ INTERSECT SELECT ename. In practice. the INTERSECT operator is not nearly as useful aas UNION. DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . Of course more than one intersect may be used where numerous select statements are involved. sal FROM emp WHERE deptno = 10.INTERSECT operator The INTERSECT operator effectively performs an AND across two select statements in order to present only those rows returned by both select statements. This query will show only those employees who are both managers and work in department 10.
MINUS operator The MINUS operator is used to present rows which are returned by one select statement but NOT by the second select statement. It is important to be clear about the order of the select statements . this gives the value ‘PRESIDENT’ whereas if the selects are placed in a different order SELECT job FROM emp WHERE deptno = 20 MINUS SELECT job FROM emp WHERE deptno = 10.viz: SELECT job FROM emp WHERE deptno = 10 MINUS SELECT job FROM emp WHERE deptno = 20. gives the value ‘ANALYST’ DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .
A further example SELECT * FROM emp x WHERE NOT EXISTS (SELECT 1 FROM emp WHERE x. A data item can never ‘not be equal to a NULL’ and hence the subquery returns no rows. If the NULL is updated to some spurious value such as 9999.empno. dname. x. is passed down from the outer query block to the inner query block for each row in the emp table.empno = mgr) Shows employees who do not manage anyone else. the NOT IN subquery will produce the expected result.The EXISTS operator This operator returns only true and false and is used in connection with the subquery construct. Not only does it give unexpected results . Unlike other subqueries. A typical example SELECT deptno. (In all other examples the subquery is executed only once in order to return a value to the outer query) Incidentally this could perhaps have been atttempted using a NOT IN construct. loc FROM dept WHERE EXISTS (SELECT deptno FROM emp WHERE job = ‘CLERK’). SELECT * FROM emp WHERE empno NOT IN (SELECT mgr FROM emp). [The NOT IN subquery construct is to be avoided. it is re-executed for each row in the table referenced by the outer query.but it also has a performance penalty in index usage is disabled] Formatting the query output DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . Note the use of a table alias in order to distinguish between values from the two images of the emp table. (There are six of them). this returns details of departments which employ clerks. This type of statement is known as a correlated subquery. this returns no rows! The cause of this is the existence of a NULL value in the mgr column. A value. Unfortunately.
SQL file is a user.SQL*Plus commands can be used to perform rudimentary formatting of SQL output for reporting purposes and controlling the SQL environment. or in a LOGIN. Turning feedback ON puts the number of records at 1. The maximum value of n is 500 but obviously other restrictions may prevail. Unlike SQL reserved words. They cannot simply be RUN with SQL statements because the SQL processor is only able to process SQL statements. The default value for the option is shown by an underscore and the available options are separated by a vertical bar ‘l’. If 6 or more receords are retrieved. Examples SET PAUSE ON this command causes a pause to occur after each new page of output . Obviously OFF suppresses the display. In the examples which follow the part of the command which may be abbreviated is enclosed in square brackets. page numbers.SQL file which means they will be active (in the sense of setting default values) on a global scale for all user sessions. It gives the user the ability to set various features to a value. SQL*Plus commands are treated as separate statements from normal SQL statements. governs the printing of column headings in SQL output sets the total characters shown on each line of Oracle output.the user must press <RETURN> in order to progress to the next page governs the display of commands as they are executed from a command file. Normally they are executed as part of a command file and are specified in advance of an SQL query statement. SET ECHO OFF/ON SET FEED[BACK] 6/N/OFF/ON SET HEA[DING] OFF/ON SET LIN[ESIZE] 80IN setting feedback to a value governs when Oracle displays the ’number of records retrieved’ message after each query. all SQL*Plus commands may be abbreviated. the message is shown by default. new column headings and formats.SQL file. but they can be executed singly at the SQL prompt. The SET command This command allows control of the SQL*Plus environment.owned file which can be used to set defaults for a user. DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . or turn them on or off. SQL*Plus commands like these may be specified in a GLOGIN. This can be overriden by specifying your own value or turning feedback OFF altogether. The LOGIN. Typically one can give SQL output a title. summary values.
SET NUMF[ORMAT] <format> SET NUMW[IDTH] 10IN SET PAGES[IZE] 14IN SET PAUSE ON/OFF prompt SET SPA[CE] 1 /N SET TIM[ING] ON/OFF SET TERM[OUT] ON/OFF SET WRA[P] ON/OFF There is also a SHOW command which may be used to show the current setting of any of the above environment variables . sets the number of spaces between columns in any output. Message governs the printed on the screen when Oracle waits for input. controls the truncation of a data item if it is too long for the current line width. when set to ON. The maximum value is 10. If n is set Oracle will force a formfeed between pages. (The information shown is O/S dependent). SHOW LINESIZE DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . OFF truncates the data.e. ON allows it to wrap to the next line.SET NEW[PAGE] 1 IN to zero. governs whether SQL output will actually be shown on the terminal screen.g. specifies number of blank lines to be printed between bottom title of one page and the top title of the next page. sets a default value for the format for the display of numeric columns governs the default width for the display of numeric values sets the number of lines per page message governs whether Oracle will wait for user input (a press of the <RETURN> key) or not. this will display timing statistics for each SQL statement which is subsequently executed. Obviously useful if output is meant to be directed to a file.
see the SQL*Plus User’s Guide) COLUMN sal FORMAT $99. sal*12 + NVL (comm. will give the following formatted output ENAME ---------MILLER EMPNO ---------7788 HIREDATE --------------12-MAR-92 SAL*12 + NVL ------------------2850 DEPTNO -----------10 Note that column names are in upper case and are all underlined by’-’.999. Remember that any column formatting will remain in place for the whole of the SQL*Plus session unless explicitly turned off or changed.99 COLUMN HIREDATE A35 COLUMN lotsofchars FORMAT A25 WORDWRAP 2300 ---.00 column width is increased from 9 to 35 characters wide column is wrapped around at the end of the last word to fit on one line Staffordshire UNIVERSITY DATABASE MANAGEMENT SYSTEMS .g. Date columns are 9 character columns wide. hiredate. each column heading will be the same as the column name in the database or the expression which is used in the SELECT statement. empno. SQL*Plus can be used to change all of these default settings. Character columns default to the actual column width specification in the database. Changing column names SQL> COLUMN ename HEADING Employee Column names may also be changed withing the SQL statement but this only takes effect within that particular select command . SELECT ename Employee FROM emp. By default all SQL output is displayed in columnar format. The following query: SELECT ename.> $2.Column Formatting SQL*Plus commands may be used to specify individual formatting of columns.0). Numeric columns are 10 character columns wide and right justified. COLUMN empno HEADING ‘Employee 1 number’ (note the use of ‘l’ to force a new line) Changing column formats (for full details.e. deptno FROM emp. (ename renamed to Employee) Column names may be forced over more than one line (useful for narrow columns of data as it allows a full display of the column name).300.
If the data value is too big for the column formatting. Each job’s data will then be printed on one page containing the value of job in its title. SQL*Plus displays % The LIKE command allows specification of a column to be the same as a previously specified column COLUMN sal FORMAT $9999 COLUMN comm LIKE sal The NEW_VALUE facility allows you to extract a value in a column for use in the top title of a report page COLUMN job NEW_VALUE jobpage TTITLE RIGHT jobpage This puts the current value of job on the top of each page. The keywork NULL can be used to specify what should be output if a NULL value is encountered in the database for a particular column COLUMN comm FORMAT $999. Obviously this would be used for data which is grouped around the job column (normally by use of the BREAK statement). SQL*Plus displays #### If the data is of the wrong type for the specified format.99 HEADING ‘Commission’ NULL ‘NotApp’ DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .
RIGHT or CENTRE. Titles which are cleared.Page Titles Page titles are specified using: TTITLE BTITLE top of page before the displayed SQL output bottom of page after the SQL output The commands allow text to be shown as titles and positioned LEFT.USER any user variable (usually a column NEW_VALUE) Some examples showing the use of TTITLE TTITLE LEFT ‘Company Annual Report’ TTITLE SKIP 2 COL 10 ‘Departmental Accounts’ DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . page number and date are not shown. a value of 0 for n will cause a skip back to the start of the current line). until they are cleared or turned off using TTITLE OFF BTITLE OFF CLEAR TITLE Titles which are turned off may be turned on again (use TTITLE ON).SKIP PAGE. This command can also be used to skip to a new page . The SKip command Lines may be skipped using SKIP n (N. Once set. Text may also be tabbed (moved forward n spaces by using TAB n) or positioned to a specific character column (COL n).B. titles remain active for all reports generated within a session. Displaying values within titles SQL. If SKIP is used. can not be brought back.PNO SQL.LNO SQL.
‘Departmental Report’ TTITLE CENTER ‘Company Report’ SKIP 2CENTER ‘Chemicals Division’ TTITLE LEFT today CENTER ‘Sales Statistics’ [ today would be defined by the NEW_VALUE facility from SYSDATE COLUMN SYSDATE NEW_VALUE today ] With some releases you could also reformat ‘today’ to show the new time on each page of the report. TTITLE RIGHT today FORMAT Ddth Mon YY HH:MM:SS DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .FORMAT may also be used to format the data items in the title TTITLE LEFT FORMAT 099 ‘Page:’ SQL.PNO CENTER.
skipping lines. printing (or not) of duplicate values. Some examples BREAK ON REPORT BREAK ON ROW SKIP 2 BREAK ON PAGE BREAK ON deptno SKIP 2 BREAK ON job SKIP PAGE BREAK ON deptno ON job BREAK ON dname SKIP 1 ON job SKIP PAGE To view your breaks. An action should always be specified in this statement.usually via an ORDER BY clause. A break may be specified to occur at any (or all) of the following levels. start a new page or skip lines. ON REPORT ON column name 1 expression useful for producing grand totals at the end of a report or skipping pages before the next report useful for producing summary values and formatting whenever a value of the specified column or expression changes.. simply type BREAK To clear breaks. The BREAK command is used to specify where in a report certain actions should occur. These actions may be calculations of summary values.B. causes break processing to occur after each row in the output. A separate COMPUTE statement is required to produce summary values.BREAK processing BREAK ON level [action [action]]. type CLEAR BREAKS DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY .... breaks on each page throw ON ROW ON PAGE The actions may be to suppress duplicate values... N. This command should only be used with an SQL statement which produces sorted data ...
A typical command file to generate a report. For example: COMPUTE SUM OF sal ON deptno will produce salary totals each time the value of deptno changes if i) ii) iii) BREAK is specified on deptno and it is the most recently specified BREAK the column (or expression) referenced in the ON clause is in the select list of the SQL statement all expressions.PNO CENTER ‘Departmental Records SKIP 2 BREAK ON REPORT ON dname SKIP 2 COMPUTE SUM OF sal comm total ON dname COMPUTE SUM OF total ON REPORT SELECT dname. columns.999. job.deptno = dept. empno. nvl(sal. or column aliases in the OF clause must also occur in the select list of the SQL statement besides SUM you may calculate and display COUNT count of non-null values AVG MAX MIN STD NUM[BER] count of number of rows If a column is renamed inside the SQL query. An obvious use is in producing subtotals and grand totals.99 TTITLE LEFT FORMAT 099 ‘Page:’ SQL. comm.deptno ORDER BY dname. sal.0) total FROM emp. SET PAGESIZE 66 COLUMN sysdate NEW_VALUE today COLUMN comm NULL’ N/A’ COLUMN total FORMAT $99. sal. CLEAR BREAKS TTITLE OFF Interactive Queries DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . dept WHERE emp.The COMPUTE statement This statement is used in conjunction with the BREAK statement in order to produce summary values on groups of rows.0) + nvl(comm. its alias must be used in BREAK and COMPUTE statements.
SELECT empno.Substitution variables which allow the user to specify values to be used at runtime. When this statement is executed. expressions. may be specified in a command file or SELECT statement. the following SQL statement will allow the user to specify which employee records should be displayed based on the value of the sal column. A stored command may use up to 9 parameters. This may be done by prefixing the variable with an ampersand (&).viz. For example. deptno FROM emp WHERE sal = &salary_value.: DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . AVG(&your_second_column) FROM emp WHERE deptno = &department_number If the required substitution is a string. Enter value for your_job: ‘ANALYST’ this can be avoided by putting the subscription variable in quotes withing the SQL statement SELECT * FROM emp WHERE jon = ‘&yourjob’. SQL*Plus will prompt for the value of salary_value as follows Enter value for salary_value: EMPNO ---------3333 4444 ENAME ----------COX WILKINS 3000 JOB -----MANAGER CLERK DEPTNO -----------10 20 Substitution variables may be used to represent any reference to columns. AVG(&your_first_column). or tables. the user must enclose the input with single quotes. SELECT deptno. ename. Interactive Queries Often the substitution variable will need to be referenced more than once in a statement . job.
When this is run. deptno FROM emp WHERE job = &&your_job AND sal > (SELECT AVG(sal) FROM emp WHERE job = &&your_job. For further details on interactive control see ACCEPT. DEFINE. This query is designed to find all those employees who earn more than the average salary for their occupation. the user will be prompted twice for the same data! This can be prevented by prefixing the substitution variable with a double ampersand. SQL*Plus will continue to use the supplied value in subsequent queries and will not prompt for your_job until it is explicitly UNDEFINEd. deptno FROM emp WHERE job = &your_job AND sal > (SELECT AVG(sal) FROM emp WHERE job = &your_job. sal. DATABASE MANAGEMENT SYSTEMS Staffordshire UNIVERSITY . sal.SELECT ename. SELECT ename. UNDEFINE and VERIFY in the SQL*Plus reference manual.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue listening from where you left off, or restart the preview.