Sie sind auf Seite 1von 22

Tamil

Page 1 of 22
SQL Notes INTRODUCTION

sql notes.doc

Oracle 9i Features: Oracle offers a comprehensive high-performance infrastructure for e-business. It is called oracle9i. Oracle9i everything needed to develop, deploy, and manager internet applications. Benefits -Scalability, Robust, Reliable, Available, Secure Architecture. -One development model, easy deployment options, One management interface for all applications, Industry standard technologies. Oracle9i products -Oracle 9i Application server -Oracle9i Database. Oracle9i Apps. Server: The Oracle9i application server runs all your applications. The oracle9i Database stores all your data. -Oracle9i AS can run your Portals or websites, Java transactional applications, Business intelligence applications. Oracle 9i Database: It manages all your data. Relational and object relational database management system: -Relational model and object relational model -User defined data types and objects -Fully compatible with relational database -support of multimedia and large objects -High quality database server features. Oracle internet platform: -It built on three core pieces. -Browser based clients to process presentation -Application servers to execute business logic and serve presentation logic to browser based clients. -Databases to execute database intensive business logic and serve data. System development life cycle: Strategy and analysis: Study and analyze the business requirement. Identify the information requirements. Build models of the system. Transfer the business narrative into a graphical representation. Confirm and refine model with the analysts and experts. Design: Design the database. Build and document: Build the prototype system. -Write and execute the commands to create the tables and supporting objects for the database. -develop user documentation. Transition: Refine the prototype. Move the application into production with user acceptance testing, Make any modification required. Production: Roll out the system to users. Operate the production system. Monitor its performance, and enhance and refine the system. Storing Information: -Organizations can store data on various media and in different formats. Such as a hard copy document in a filing cabinet or data stored in electronic spreadsheets or in databases. Database : It is an organized collection of information. -To manager databases, you need database management system. It is a program that stores, retrieves and modifies data in the database on request. Four main types of databases: Hierarchical, network, relational and more recently object relational. Relational database concept: Dr.E.F.Codd Proposed the relational model for database systems in 1970. -It is bases for the RDBMS. -It consists - Collection of objects or relations - Set of operators to act on the relations - Data integrity for accuracy and consistency. Definition of a Relational database: It is a collection of relations or two dimensional tables to store information.

Tamil

Page 2 of 22

sql notes.doc

Data models: Models are a cornerstone of design. It helps communicate the concepts in peoples minds. They used for communicate, categorize, Describe, Specify, Investigate, Evolve, Analyze, Imitate. Entity relationship model: Create an ER diagram from business specifications or narratives. It built during the analysis phase of the SDLC. -Documents information for the organization in a clear, precise format. -Provide a clear picture of the scope of the information requirement. -Provide an easily understood pictorial map for the database design. -Offers an effective framework for integrating multiple applications. Key components: -Entity: A thing of significance about which information needs to be known. -soft box, Singular, Unique name, Uppercase, Synonym in parentheses. -Attribute: Something that describes or qualifies an entity. -Singular name in lowercase, Mandatory marked with *, Optional marked with o - Unique identifier : Primary key marked with #, Secondary marked with #. -Relationships: A named association between entities showing optionality and degree. Symbol Description Dashed line - May be Solid line - Must be Crows foot One or more Single line - One and only one. Relating multiple tables: With an RDBMS you can relate the data in one table to the data in another by using the foreign keys. Primary key: Each row of data in a table is uniquely identified by a primary key. Foreign Key: It is a column or a set of columns that refer to a primary key in the same table or another table. -Purely logical, not physical, pointers. -It is values in existing primary key value or unique key value or null. -It reference either PK or UK column. Relational database terminology: It can contain one or many tables. Table is the basic storage structure of an RDBMS. Properties: -Can be accessed and modified by executing SQL statements. -Contains a collection of tables with no physical pointers. -Uses a set of operators. SQL (Structured query language): Using SQL you can communicate with the oracle server. -Efficient, Easy to learn and use, functionally complete (You can define, retrieve, and manipulate data in the tables). Relational Database Management System: -Oracle provides a flexible RDBMS called oracle9i. -Using its features, you can store and manage data with all the advantages of a relational structure plus PL/SQL, an engine that provides you with the ability to store and execute program units. -Oracle server supports retrieving data based on optimization techniques. -Consistency and protection of data through locking mechanisms. -It provides an open, comprehensive, and integrated approach to information management. - It consists of an oracle database and an oracle server instance. - Every time a database is started, a system global area(SGA) is allocated, and oracle background processes are started. -The combination of the background processes and memory buffers is called an oracle instance. SELECT Data retrieval. INSERT, UPDATE, DELETE, MERGE DML CREATE, ALTER, DROP, RENAME, TRUNCATE DDL COMMIT, ROLLBACK, SAVEPOINT TCL GRANT, REVOKE DCL. -Both ANSI (American national standard institute) and ISO (International standard organization) have accepted SQL as the standard language for relational databases

Tamil
Capabilities of SQL SELECT Statements

Page 3 of 22
1. Writing Basic SQL SELECT Statements

sql notes.doc

Projection : To choose the columns in a table that you want returned by your query. Selection : To choose the rows in a table that you want returned by a query. Joining : To bring together data that is stored in different tables by creating a link between them. Basic Select Statement Select * |{[DISTINCT] column | expression [alias],} From table; Select Which specifies column to be displayed. From Which specifies the table containing the columns listed in the selected clause. * - Select all columns Distinct Suppresses duplicates Column/expression select the named column or expression Alias gives selected columns different headings A keyword refers to an individual SQL element.(SELECT). A clause is a part of a SQL statement.(select empid)

-A statement is a combination of two or more clauses. (Select * from employees is a SQL statement.) Selecting all columns of all rows : You can display all columns of data in table by following the SELECT keyword with an asterisk(*). SELECT * FROM DEPARTMENTS; Select specific columns of all rows: You can use the select statement to display specific columns of the table by specifying the column names, separated by commas. SELECT DEP_ID,LOC_ID FROM DEPARTMENTS;

Writing SQL Statements: -Are not case sensitive, can be on one or more lines. -Keywords cannot be abbreviated or split across lines. -Clauses are usually placed on separate lines. -Indents are used to enhance readability. Column heading defaults: Default heading in center and uppercase. Character and date column are left justified. Number column are right justified. Arithmetic Expressions: -Create expressions with number and date data by using arithmetic operators. - *,/,+,-It can contain column names, constant numeric values, and the arithmetic operators. -You can use arithmetic operators in any clause or a SQL statement except in the from clause. - Operator precedence : Operators of the same priority are evaluated from left to right. Parentheses are used to force prioritized evaluation and to clarify statements. Defining a null value: A null is a value that is unavailable, unassigned, unknown, or inapplicable. It is not the same as zero or a blank space. Arithmetic expressions containing a null value evaluate to null.

Tamil

Page 4 of 22

sql notes.doc

Defining a column alias: Renames a column heading, Is useful with calculations, Output display by default uppercase. Immediately follows the column name there can also be the optional as keyword between the column name and alias. Requires double quotation marks ( ) if it contains spaces or special characters or is case sensitive. Concatenation operator: Concatenates columns or character strings to other columns. Is represented by two vertical bars(||). Create a resultant column that is a character expression. Literal Character Strings: A literal is a character, a number, or a date included in the select list. Date and character literal values must be enclosed within single quotation marks. Each character string is output once for each row returned. Duplicate and Eliminate duplicate rows: -The default display queries is all rows, including duplicate rows. -Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause. SQL: A language. ANSI standard. Keyword cannot be abbreviated. Statements manipulate data and table definitions in the database. Use functions to perform some formatting. Do not have a continuation character. ISQL * PLUS: - An environment. - Oracle Proprietary. - Keywords can be abbreviated. - Commands do not allow manipulation of values in the database. - Runs of a browser. -Centrally loaded, does not have to be implemented on each machine. - Use commands to format data. - Has a dash (-) as a continuation character if the command is longer than one line. After you log on I SQL * PLUS: Describe the table structure. Edit your SQL Statement Execute SQL from iSQL*plus Save SQL statements to files and append SQL statements to files. Execute statements stored in saved files into the ISQL*PLUS edit window. 2. Restricting and sorting data Where clause: Restrict the rows returned by using the where clause. The where clause follows the from clause. A WHERE clause contains a condition that must be met. Condition is composed of column names, expressions, constants, and a comparison operator. Character strings and Dates: These two are enclosed in single quotation marks. Character values are case sensitive, and date values are format sensitive. The default date format is DD-MON-RR. Oracle databases store dates in an internal numeric format, resenting the century, month, day, hours, minutes, and seconds. Comparison Conditions: The comparison conditions are =,>,>=,<,<=,<>.

Tamil

Page 5 of 22

sql notes.doc

Comparison conditions are used in conditions that compare one expression to another value or expression. The are used in where clause in the following format: WHERE expr operator value. An alias cannot be used in the where clause. Other comparison conditions : Between and . Between two values (inclusive), Use the BETWEEN condition to display rows based on a range of values. In condition: Use the IN membership condition to test for values in a list. The in condition can be used with any data type. Like Condition: It used to perform wildcard searches of valid search string values. Search conditions can contain either literal characters or numbers. % - Denotes zero or many characters. _ -denotes one character. You can combine pattern-matching characters. You can use the ESCAPE Identifier to search for the actual % and _ symbols. Null condition: Test for nulls with the IS NULL operator.

LOGICAL CONDITION: (Three) -AND: Returns true if both component conditions are true. -OR: Returns true if either component condition is true. -NOT: Returns true if the following condition is false. -You can use several conditions in one where clause using the AND and OR operators. - The NOT operator can also used with other SQL operators, such as BETWEEN, LIKE and NULL. Rules of precedence: Arithmetic, Concatenation, comparison, IS [NOT] NULL, LIKE, [NOT] IN, [NOT] BETWEEN, NOT, AND, OR. Override rules of precedence by using the parentheses. ORDER BY CLAUSE: - Sort rows with the ORDER BY clause.1. ASC: Ascending order, default. 2. DESC Order. -The ORDER BY clause comes last in the SELECT statement. - You can specify an expression, or an alias, or column position as the sort condition. -If the ORDER BY clause is not used, the sort order is undefined. - Numeric values are displayed with the lowest values first. Date values are displayed with the earliest value first. Character values are displayed in alphabetical order. Null values are displayed last for ascending sequences and first for descending sequences. -The sort limit is the number of columns in the given table. -You can also order by columns that are not included in the SELECT clause. 3. Single-Row Functions SQL Functions: Perform calculations on data. Manipulate output for groups of rows. SQL functions sometimes take arguments and always return a value. Two types of functions. Single row functions : These functions operate on single rows only and return one result per row. Character, number, date, conversion are types of single row functions Multiple row functions: These functions can manipulate groups of rows to give one result per group of rows. SRF: Manipulate data items. Accept arguments and return one value. Act on each row returned. Return one result per row. May modify the data type. Can be nested. Accept arguments which can be a column or an expression. The argument can be User supplied constant, variable value, column name, expression. Can be used in SELECT,WHERE and ORDER BY Clauses; Character functions: Accept character input and can return both character and number values. It classified into two types. Case-manipulation functions : Lower (column/expression) : Converts alpha character values to lowercase. UPPER (column/expression): Converts alpha character values to uppercase. INITCAP (column/expression): Converts alpha character values to uppercase for the first letter of each word, all other letters in lowercase. Character-manipulation functions: CONCAT( column1|expression1,column2 |expressin2) Join a value together.Concatenates the first character value to the second character value. Equivalent to concatenation operator(||).

Tamil

Page 6 of 22

sql notes.doc

SUBSTR (column | expression,m[,n]) Extracts a string of determined length. Return specified characters from character value starting at character position m, n characters long. If m is negative, the count starts from the end of the character value. If n is omitted, all characters to the end of the string are returned. LENGTH ( column|expression) Shows the length of a string as as numeric value. Returns the number of characters in the expression. INSTR( column| expression, string,[,m], [n]) Finds numeric position of a named character. Returns the numeric position of a named string. Optionally, you can provide a position m to start searching, and the occurrence n of the string. M and n default to 1, meaning start the search at the beginning of the search and report the first occurrence. LPAD| RPAD (column | expression, n , string) : Pads the character value right_justified(LPAD) OR left_justified(RPAD) to a total width of n character positions. TRIM(leading|trailing|both ,trim_character FROM trim_source) : Enables you to trim heading or trailing character(or both) from a character string. If trim_character or trim_source is a character literal, you must enclose it in single quotes.(after 8i) REPLACE (text, search_string, replacement_string) Searches a text expression for a character string and, If found, replaces it with a specified replacement string.

NUMBER FUNCTIONS: Number functions accept numeric input and return numeric values. -ROUND (column|expression,n) Rounds the column, or value to n decimal places, or ,if n is omitted, no decimal places.(If n is negative, numbers to left of the decimal point are rounded.) -TRUNC (column|expression,n) Truncates the column, expression, or value to n decimal places, or, if n is omitted, then n defaults to zero. -MOD (m,n)- Returns the remainder of m divided by n. The mode function is often used to determine if a value is odd or even. DUAL Table : The dual table is owned by the user SYS and can be accessed by all users. It contains one column, DUMMY, and one row with the value X. Working With dates : Oracle database stores dates in an internal numeric format: century, year, month, day, hours, minutes, seconds. The default date display format is DD-MON-RR. Allows you to store 21st century dates in the 20th century by specifying only the last two digits of the year. Allows you to store 20th century dates in the 21st century in the same way. Valid oracle dates are between January 1,4712 B.C. and December 31,9999 A.D. SYSDATE is function that returns the current database server date and time. Arithmetic with dates: -Add or subtract a number to or from a date for a resultant date value. -Subtract two dates to find the number of days between those dates. -Add hours to a date by dividing the number of hours by 24. -Date + number, Date number, Date Date , Date + number/24. DATE FUNCTIONS: DATE function operate on oracle dates. All date functions return a value of DATE data type except MONTH_BETWEEN, Which returns a numeric value. MONTHS_BETWEEN (date1,date2) : Finds the number of months between date1 and date2. The result can be positive or negative. ADD_MONTHS (date, n) : Adds n number of calendar months to date. The value of n must be an integer and can be negative. NEXT_DAY (date,char) : Finds the date of the next specified day of the week(char) following date. The value of char may be a number representing a day or a character string. LAST_DAY (date) : Finds the date of the last day of the month that contains date. ROUND(date[,fmt]): Returns the date rounded. If the format model is omitted, date is rounded to the nearest day. TRUNC(date[,fmt]): Returns the day with the time portion of the day. If the fmt model is omitted, date is truncated to the nearest day. The round and Trunc functions can be used fro number and date values. In the format model we can use MONTH and YEAR. Conversion Functions: In addition to oracle data types, columns of tables in an oracle9i database can be defined using ANSI,DB2 and SQL/DS data types. However, the oracle server internally converts such data types to oracle data types. Two types of data types. Implicit data type Explicit data type In some cases, Oracle server uses data of one data type where it expects data of a different data type. When this happens, oracle server can automatically convert the data to the expected data type. This data type conversion can be done implicitly by oracle server, or explicitly by the user. Explicit data type conversions are done by using the conversion functions. Conversion functions convert from one data type to another. Generally, the form of the function names follows the conversion data type to data type. The first data type is the input data type; the last data type is the output.

Tamil

Page 7 of 22

sql notes.doc

Implicit Data type conversion: For assignments, the oracle server can automatically convert the following. The assignment succeeds if the oracle server can convert the data type of the value used in the assignment to that of the assignment to that of the assignment target. FROM TO Varchar2 or Char Number Varchar2 or Char Date Number Varchar2 Date Varchar2 For expression evaluation, the oracle server can automatically convert the following.Varchar2 or char to number,date. Explicit Data Type Conversion: 1.Number, date to character 2.Char to Number 3.Char to Date. TO_CHAR Conversion Function: TO_CHAR (date,format_model). All oracle date values were displayed in the DD-MON-YY format. You can use the TO_CHAR function to convert a date from this default format to one specified by you. The format model. It must be enclosed in single quotation marks and is case sensitive. Can include any valid date format element Has an fm element to remove padded blanks or suppress leading zeros Is separated from the date value by a comma. Elements of the date format model: YYYY Full year in numbers, YEAR Year spelled out, MM Two digit value for month, MONTH Full name of the month, MON Three letter abbreviation of the month, DY Three letter abbreviation of the day of the week, DAY- Full name of the day of the week, DD- Numeric day of the month, TH Ordinal number, SP- Spelled out number, AM OR PM, A.M. OR P.M., HH OR HH12 OR HH24, MI, SS, SSSSS Seconds past midnight(0-86399),/ . , - Punctuation is reproduced in the result. -Add character string by enclosing them in double quotation marks. Elements of the number format model:9 Represents a number,0 - Forces a zero to be displayed, $ - Places a floating dollar sign, L Uses the floating local currency symbol, . Print a decimal point, , - Prints a thousand indicator, MI Minus signs to right(negative values), PR Parenthesize negative numbers, V- Multiply by 10 n times, B- Display zero values as blank, not 0. The oracle server displays a string of hash signs (#) in place of a whole number whose digits exceed the number of digits provided in the format model. The oracle server rounds the stored decimal value to the number of decimal spaces provided in the format model. TO_NUMBER: Convert a character string to a number format using the TO_NUMBER function. TO_NUMBER (char[,format_model]) TO_DATE: Convert a character string to a date format using the TO_DATE function. TO_DATE(char[,format_model]). These functions have an fx modifier. This modifier specifies the exact matching for the character argument and date format model of a TO_DATE funcition. You may want to convert a character string to either a number or a date. To accomplish this task, use the TO_NUMBER OR TO_DATE functions. RR Date format: -If two digits of the current year in 0-49 and if the specified two-digit year in 0-49 the result date is in the current century. --If two digits of the current year in 0-49 and if the specified two-digit year in 50-99 the result date is in the century before the current one. -If two digits of the current year in 50-99 and if the specified two-digit year in 0-49 the result date is in the after the current one. -If two digits of the current year in 50-99 and if the specified two-digit year in 50-99 the result date is in the current century. Nesting functions: Single row functions can be nested to any level. Nested functions are evaluated from deepest level to the least deep level. General Functions: These functions work with any data type and pertain to using nulls. -NVL (expr1, expr2) Converts a null value to an actual value. Data types that can be used are date, character and number. Data types must match. -NVL2 (expr1, expr2, expr3) If expr2 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3. The argument expr1 can have any data type. The 2 and 3 can have any data type except LONG type. -NULLIF (expr1, expr2) Compares two expressions and returns null if they are equal, or the first expression if they are not equal. The NULLIF is logically equivalent to the case expression. -COALESCE (expr1, expr2, , exprn) Returns the first non-null expression in the expression list. It can take multiple alternate values. Conditional Expressions: Provide the use of IF-THEN-ELSE logic within a SQL statement. The following two methods used to implement conditional processing. Use two methods: Case expressions: The CASE expression is new in the oracle 9i server release. The case expressions let you use IF-THEN-ELSE logic in SQL statements without having to invoke procedures.

Tamil

Page 8 of 22

sql notes.doc

CASE expr WHEN comparison_expr1 THEN return_expr1 ELSE else_expr END. -You cannot specify the literal null. All of the expressions should be in same data type. Decode function: The decode function decodes expression after comparing it to each search value, If the expression is the same as search, result is returned. DECODE (col|expression, search1, result1 [,search2, result2,.,] [,default]) 4. DISPLAYING DATA FROM MULTIPLE TABLE Join : Use a join to query data from more than one table. Write the join condition in the WHERE clause. -Prefix the column name with the table name when the same column name appears in more than one table. -To join N tables together, you need a minimum of n-1 join conditions required. Ex. To join four tables, a minimum of three joins is required. This rule may not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row. SELECT table1.column,table2.column FROM table1, table2 WHERE table1.column1=table2.column2; Cartesian Product: A Cartesian product is formed when a join condition is omitted. A join condition is invalid. All rows in the first table are joined to all rows in the second table. To avoid a Cartesian product, always include a valid join condition in a WHERE clause. Oracle Proprietary Joins (8i and prior) : - Equijoin : The relationship between the two or more tables is called equijoin. The common column from the both tables values must be equal. Frequently, This type of join involves primary and foreign key complements. Equijoins are also called simple joins or inner joins. Qualifying Ambiguous column names : Use table prefixes t qualify column names that are in multiple tables. Improve performance by using table prefixes. Distinguish columns that have identical names but reside in different tables by using column aliases. Table aliases : Simplify queries by using table aliases. Improve performance by using table prefixes. Just as a column alias gives a column another name, a table alias gives a table another name. It keep SQL code smaller, use less memory. The table alias is valid only for the current SELECT statement. Non-Euqijoins: A non-equijoin is a join condition containing something other than an equality operator. Operator like Between and, In, <, > and so on. Outer Join: If a row does not satisfy a join condition, the row will not appear in the query result. You use an outer join to also see rows that do not meet the join condition. The outer join operator is the plus sign(+). - Place the outer join symbol following the name of the column in the table without the matching rows. - The outer join operator can appear on only one side of the expression. - A condition involving an outer join cannot use the IN operator or be linked to another condition by the or operator. Self Join: Joining a table to itself it is called self join. SELECT w.last_name || works for || m.last_name FROM employees w, employees m WHERE w.manager_id = m.employee_id; JOINING TABLES USING SQL COMPLAINT JOIN: 1999 SELECT table1.column, table2.column FROM table1 [CROSS JOIN table2] | [NATURAL JOIN table2] | [JOIN table2 USING(column_name)] | [JOIN table2 ON(table1.column_name = table2.column_name)] | [LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column = table2.column_name)];

Tamil

Page 9 of 22

sql notes.doc

Cross join: The cross join clause produces the cross product of two tables. Natural Joins : The natural join clause is based on all columns in the two tables that have the same name. It selects rows from the two tables that have equal values in all matched columns. If the columns having the same names have different data types, an error is returned. The join can happen only on columns having the same names and data types in both the tables. Creating joins with the USING Clause: Use the Using clause to match only one column when more than one column matches. Do not use a table name or alias in the referenced columns. Therefore columns that have the same name in both tables have to be used without any qualifiers. Creating joins with the on clause: To specify arbitrary conditions or specify columns to join, the on clause is used. The ON clause makes code easy to understand. INNER VERSUS OUTER JOINS: In SQL 1999 the join of two tables returning only matched rows is an inner join. A join between two tables that returns the results of the inner join as well as unmatched rows left or right tables is a left or right outer join. A join between two tables that returns the results of the inner join as well as results of a unmatched rows left and right join is a full outer join. You can apply additional conditions in the WHERE clause. 5.Group Functions Group functions: Group functions operate on sets of rows to give one result per group. It accepts argument. Types are -Avg, Count, Max, Min, Stddev, Sum, Variance. -All the group functions ignore null values except count. To substitute a value for null values, use the NVL,NVL2, or COLLESCE functions. -When we using the group function the result set by default in ascending order. To override this we can use descending order(DESC) in the order by clause. -The AVG, SUM, STDDEV and VARIANCE functions against columns that can store only numeric data. The MIN and MAX we can use for any data type. COUNT(*), COUNT(expr), COUNT(DISTINCT expr) : Returns the number of rows in a table. It has three formats. COUNT(*) Returns number of rows in a table including duplicate rows and rows containing null values. COUNT(expr) Returns the number of non-null values in the column identified by expr. COUNT(DISTINCT expr) - Returns the number of unique and non-null values in the column identified by expr. Group by Clause : Divide rows in a table into smaller groups by using the group by clause. -All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. - Using a WHERE clause, you can exclude rows before dividing them into groups - You must include the columns in the GROUP BY clause. - You cannot use a column alias. - When we using the group function the result set by default in ascending order. To override this we can use descending order(DESC) in the order by clause. -The GROUP BY column does not have to be in the SELECT list. We can use more than one column in the GROUP BY clause. -We cannot use the WHERE clause to restrict groups and we cannot use group functions in the WHERE clause. -We can use the HAVING clause to restrict groups - When we using the group function the result set by default in ascending order. To override this we can use descending order(DESC) in the order by clause. -HAVING clause : When we using the group functions in select clause we can use the HAVING clause to restrict the groups. The oracle server performs the following steps: -Rows are grouped. -The group function is applied to the group. -The groups that match the criteria in the having clause are displayed. -Nesting group functions: Group functions can be nested to a depth of two.

Tamil

Page 10 of 22
6. SUBQURIES

sql notes.doc

Subquery : A subquery is a SELECT statement that is embedded in a clause of another select statement. Subqueries can be use in WHERE, HAVING and FROM. - The subquery is often referred to as a nested SELECT, sub- SELECT, or INNER SELECT statement. - The subquery(inner query) executes one before the main query. The result of the subquery is used by the main query (outer query). - Enclose subqueries in parentheses. Place subqueries on the right side of the comparison condition. - The ORDER BY clause is used in subquery ORACLE 8I and later. - Types of subquries: Single row and Multi row. Single row sub query : A single-row subquery is one that returns one row from the inner SELECT statement. This type of subquery uses a single-row operator. (=, >, >= , < , <=, <>) - The outer and inner queries can get data from different tables. - The oracle server executes sub queries first. - If the sub query returns one of the values returned by the inner query is a null value, hence the entire query returns no rows. Multiple-Row subquries: Sub queries that return more than one row are called multiple-row sub queries. - IN : Equal to any member in the list - ANY: Compare value to each value returned by the sub query. <ANY : Less than the maximum. >ANY : More than the minimum. =ANY : Is equivalent to IN. - ALL: Compare value to every value returned by the sub query. <ALL : Less than the minimum. >ALL : More than the maximum. -The NOT operator can be used in IN, ANY and ALL operators.

7. PRODUCING READABLE OUTPUT WITH ISQL*PLUS Substitution Variables: In Isql*plus, you can use single ampersand (&) substitution variables to temporarily store values. - Specifying character and date values with substitution variables. - Use substitution variables in WHERE conditions, ORDER BY clauses, Column expressions, Table names and Entire SELECT statements. DEFINE and UNDEFINE: You can predefine variables by using the DEFINE command. - You need to predefine a variable that includes spaces, you must enclose the value within single quotation marks. - A defined variable is available for the session. - Use the UNDEFINE command to clear it. && SUBSTITUTION VARIABLE: It use the double ampersand(&&) if you want to reuse the variable value without prompting the user each time. VERIFY command: It used to toggle the display of the substitution variable, before and after replaces substitution variables with values. Customizing the isql*plus environment: SET: You can control the environment in which isql*plus is currently operating by using the SET commands. SHOW: You can verify what you have set by using the SHOW command. Set command Variables: ARRAY [SIZE] {20|n} Sets the database data fetch size. FEED [BACK] { 6|n|OFF|ON} Displays the number of records returned by a query when the query selects at least n records. HEA [DING] {OFF|ON} Determines whether column headings are displayed in reports. LONG {80 |n} Sets the maximum width for displaying LONG values.

Isql*plus Format commands: All format commands remain in effect until the end of the isql*plus session or until the format setting is overwritten or cleared.

Tamil
The -

Page 11 of 22

sql notes.doc

COL [UMN] [column option] Control column formats. TTI[TLE] [text|OFF|ON] Specifies a header to appear at the top of each page of the report. BTI[TLE] [text|OFF|ON] Specifies a footer to appear at the bottom of each page of the report. BRE[AK] [ON report_element] Suppresses duplicate values and divides rows of data into sections by using line breaks. COLUMN Command: The column command options CLE [AR]: Clears any column formats. HEA [DING] text: Sets the column heading. FOR [MAT] format: Changes the display of the column using a format model. NOPRINT: Hides the column. PRINT: Shows the column NUL [L] text: Specifies text to be displayed for null values. Column Command: To show or clear the current COLUMN command settings, use the following commands: [UMN] column: Displays the current settings for the specified column. [UMN]: Displays the current settings for all columns. [UMN] column CLE [AR]: Clears the settings for the specified column. [AR] COL [UMN]: Clears the settings for all columns. 8. Manipulating Data

Using the - COL - COL - COL - CLE

DML: Data manipulation language is a core part of SQL. When we want to add, update, or delete data in the database, we execute a DML statement. - A collection of DML statements that form a logical unit of work is called a transaction. - Types of DML statements are: Insert, Update, Delete and Merge. Insert: Add new rows to a table by using the insert statement. When we insert a now into a table we have to list values in the default order of the columns in the table. Enclose character and date values within single quotation marks. Inserting rows with null values: Implicit method is Omit the column from the column list. Explicit method is specify the NULL keyword in the VALUES clause. Common errors during a row insert: - Mandatory value missing for a NOT NULL column. - Duplicate value violates uniqueness constraint - Foreign key constraint violated - CHECK constraint violated - Data type mismatch - Value too wide to fit in column. -We can use functions to enter special values in your table. EX.SYSDATE. - Creating a Script: Use & Substitution in a SQL statement to prompt for values. & is a placeholder for the variable value. - We can use a subquery in place of the table name in the INTO clause of the insert statement. UPDATE: Modifying existing rows with the UPDATE statement. If we use the where clause specific rows are updated. If not use WHERE clause all rows in the table updated. -Updating two columns with a subquery. -We can updating rows based on another table values. Delete Statement: We can remove existing rows from a table by using the DELETE statement. If we use the where clause specific rows are updated. If not use WHERE clause all rows in the table updated. -Use subqueries in DELETE statements to remove rows from a table based on values from another table. - We cannot delete a row that contains a primary key that is used as a foreign key in another table. Using WITH CHECK OPTION keyword: A subquery is used to identify the table and columns of the DML statement.

Tamil
-

Page 12 of 22

sql notes.doc

The WITH CHECK OPTION keyword prohibits you from changing rows that are not in the subquery.

Explicit Default: When we creating a table we can specify a default value for a column. We can use the DEFAULT keyword as a column value where the column default is desired. It can be used in INSERT and UPDATE statements. If no default value exists, a null value is used. The MERGE statement: It provides the ability to conditionally update or insert data into a database table. -Performs an UPDATE if the row exists, and an INSERT if it is a new row. Database Transaction: - DML statements which constitute one consistent change to the data. Consists of any number of DML statements that the oracle server treats as a single entity or a logical unit of work. - One DDL statement and one DCL statement. - A transaction end with one of the following : Commit or Rollback statement is issued. A DDL or DCL statement executes. The user exits iSQL*plus. The system crashes. Explicit TCL( Commit or Rollback): Ensure data consistency. Preview data changes before making changes permanent. Group logically related operations. - Explicit Transaction Control statements are COMMIT, SAVEPOINT and ROLLBACK. - COMMIT: Ends the current transaction by making all pending data changes permanent. - SAVEPOINT: Making a savepoint within the current transaction. - ROLLBACK: Rollback ends the current transaction by discarding all pending changes. - ROLLBACK TO SAVEPOINT name: It rollback the current transaction to the specified savepoint. Implicit TCL: An automatic commit occurs under the following circumstances. - DDL and DCL Statement is issued - Normal exit from iSQL*plus. - An automatic rollback occurs under an abnormal termination of iSQL*plus or system crashes. - We can use AUTOCOMMIT command to commit the transaction automatically to set on or off explicitly. State of the DATA before COMMIT or ROLLBACK: -The previous state of the data can be recovered. - The current user can review the results of the DML operations by using the select statement. -Other users cannot view the results of the DML statements by the current user. -The affected rows are locked; other user cannot change the data within the affected rows. State of the Data after COMMIT: - Data changes are made permanent in the database. - The previous state of the data is permanently lost. - All users can view the results - Locks on the affected rows are released. Those rows are available for other users to manipulate. - All savepoints are erased. State of the Data after Rollback: - Discard all pending changes by using the rollback statement. - Data changes are undone. - Previous state of the data is restored. - Locks on the affected rows are released. Statement level Rollback: - If a single DML statement fails during execution, only that statement is rolled back. - The oracle server implements an implicit savepoint. - All other changes are retained.

Tamil
Read Consistency: - Readers do not wait for writers. - Writers do not wait for readers.

Page 13 of 22

sql notes.doc

Locking: Explicit and implicit. - Locks are mechanisms that prevent destructive interaction between concurrent transactions. - Implicit : Implicit locking occurs for all SQL statements except SELECT. - Explicit : The users can also lock data manually, which is called explicit locking. 9. CREAETING AND MANAGEING TABLES Database Objects: Table, view, sequence, index and synonym. Data definition statements are: Create, Alter, Drop, Rename and Truncate. Table: Basic unit of storage, composed of rows and columns. - Tables can be created at any time, even while users using the database. - You do not need to specify the size of any table. Naming rules: - Must begin with a letter. - Must be 1-30 characters long. - Must contain only A-Z, a-z, 0-9,_,$ and # - Must not duplicate the name of another object owned by the same user. - Must not be an oracle server reserved word. Create table statement: - Create table to store data. - Create a table you must have a create table privilege. - You specify table name, column name, column data type, Default expr and column size. Reference another users tables: - Tables belonging to other users are not in the users schema. - You should use the owners name as a prefix to access those tables. - Schema : A schema is a collection of objects. The default option: Specify a default value for a column during an table creation. - Literal values, expressions, or SQL functions are legal values. Tables in the oracle database: -User tables: Are a collection of a tables crated and maintained by the user. It contains user information. -Data dictionary: Is a collection of tables created and maintained by the oracle server. It contains database information. These table owned by the SYS user. Four categories of data dictionary views: USER_ - These views contain information about objects owned by the user. ALL_ - These views contain information about all of the tables. DBA_ - These views are restricted views, which can be accessed only by people who have been assigned the DBA role. V$ - These views are dynamic performance views, database server performance, memory and locking. Querying the data dictionary: - User_tables: See the names of tables owned by the user. - User_objects: View distinct object types owned by the user. - User_catalog: View tables, views, synonyms and sequences owned by the user. It has synonym named CAT.

Tamil
Data types:

Page 14 of 22

sql notes.doc

Varchar2(size) Variable length character data. Char(size) - Fixed length character data. Number(p,s) - Variable length numeric data. Date - Date and times values. Long - Variable length character data up to 2 gigabytes. CLOB - Character data up to 4 gigabytes. RAW and LONG RAW Raw binary data. BLOB - Binary data up to 4 gigabytes. BFILE - Binary data stored in an external file. Up to 4 gigabytes. ROWID - A 64 base number system representing the unique Address of a row in its table. - A long column in not copied when a table is created using a subquery. - A long column cannot be included a GROUP BY or an ORDER BY clause. - Only one LONG column can be used per table. - No constraints can be defined on a LONG column. Date Time Data types: Datetime enhancements with oracle9i are: - TIMESTAMP : Date with fractional seconds -TIMESTAMP WITH TIME ZONE Data type: -TIMESTAMP WITH LOCAL TIME Data type: Data stored in the database in normalized to the database time zone. - INTERVAL YEAR TO MONTH : Stores a period of time using the YEAR and MONTH datetime fields. INTERVAL DAY TO SECOND: It stores a period of time in terms of days, hours, minutes and seconds. Create a table by using a subquery: Create a table and insert rows by combining the create table statement and the AS subquery option. - Match the number of specified columns to the number of subquery columns. - The integrity rules are not passed onto the new table, only the column data type definitions. - Be sure to give column alias when selecting an expression in subquery. ALTER TABLE statement: - Add a new column Modify an existing column - Define a default value for the new column. - Drop a column. - Rename a column. - After you create a table, you may need to change the table structure because: you omitted a column, your column definition needs to be changed, or you need to remove columns. You can do this by using the alter table statement. - When we add a new column to the table that will be added as a last column. Add : You can add or modify columns. - You cannot specify where the column is to appear. The new column becomes the last column. Modify : You can change a columns data type ,size and default value. - A change to the default value affects only subsequent inserations to the table. Drop: Use the drop column clause to drop columns you no longer need from the table. - Only one column can be dropped at a time. The SET UNUSED OPTION: It marks one or more columns as unused so that they can be dropped when the demand on system resources is lower. - Use the SET UNUSED option to mark one or more columns as unused. - Use the DROP UNUSED COLUMNS option to remove the columns that are marked as unused. Use this when we need extra disk space. - SET UNUSED information is stored in the USER_UNUSED_COL_TABS dictionary view. Droping a table: Removes the definition of an oracle table. - All data and structure in the table is deleted.

Tamil
Any pending transactions are committed. All indexes are dropped. Any views and synonyms remain but are invalid.

Page 15 of 22

sql notes.doc

RENAME : To change the name of a table, view, sequence, or synonym, you execute the RENAME Statement. - We must be the owner of the object. Truncating a table: - Removes all rows from a table. - Releases the storage space used by that table. - You cannot roll back row removal when using TRUNCATE. - You must have a DELETE TABLE system privilege. Adding comments to a table: You can add comments to a table or column by using the COMMENT statement. -Comments can be viewed through the data dictionary views: ALL_COL_COMMENTS, USER_COL_COMMENTS, ALL_TAB_COMMENTS, USER_TAB_COMMENTS. - You can add a comment of up to 2000 bytes. 10. CONSTRAINTS Constraints: - Constraints enforce rules at the table level. - Constraints prevent the deletion of a table if there are dependencies. - Name a constraint or the oracle server generates a name by using the SYS_Cn format. - Create a constraint either: -At the same time as the table is creted. -After the table has been created. - Define a constraint at the column or table level. -Column level: Reference a single column and is defined within a specification for the owing column. -Table level: References one or more columns and is defined separately from the definitions columns in the table. We Can define any constraints except NOT NULL. - We can we the constraint by using the dictionary view USER_CONSTRIANTS. NOT NULL: specifies that the column cannot a null value. It can specify at column level only. UNIQUE: Specifies a column or combination of columns whose values must be unique for all rows in the table. The group of columns named as unique key is called composite unique key. It allows null values. It can be created column and table level. When we creating a unique key at the time implicitly creating a unique index. A composite unique key must be created by using the table level definition Primary key: Each row of data in a table is uniquely identified by a primary key. It should be not null and unique column or combination of column in the table. - Only one primary key can be created for each table. - The group of columns or combination of columns created as primary key is called composite primary key. - It can be defined at table and column level. - A UNIQUE index is automatically created for a PRIMARY KEY column. - A composite primary key must be created by using the table level definition Foreign Key: Specify a column or a set of columns that refer to a primary key in the same table or another table. -Purely logical, not physical. -It is values in existing primary key value or unique key value or null. -It reference either PK or UK column. -Defined at either the table level or the column level. - A composite foreign key must be created by using the table level definition

Tamil

Page 16 of 22

sql notes.doc

FOREIGN KEY: Defines the column in the child table at the table constraint level. REFERENCES: Identifies the table and column in the parent table. ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent table is deleted. ON DELETE SET NULL: Converts dependent foreign key values to null. - With out the on delete cascade or the on delete set null options, the row in the parent table cannot be deleted if it is referenced in the child table. Check: Defines a condition that each row must satisfy. The single column can have multiple check constraints. It can be defined at the column or table level. Use the ALTER TABLE statement: We can add a constraint for existing tables by using the alter table statement with the ADD clause. Add or drop a constraint, but not modify its structure. Enable or disable constraints. Add a NOT NULL constraint by using the MODIFY clause. You can define a NOT NULL column only if the table is empty or if the column has a value for every now.

Dropping a Constraint: Drop a constraint by using the drop clause. We can identify the constraint name from the USER_CONSTRAINTS and USER_CONS_COLUMNS. Then use the ALTER TABLE statement with the drop clause. -The CASCADE option of the drop clause causes any dependent constraints also to be dropped. Disabling Constraints: Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint. Apply the CASCADE option to disable dependent integrity constraints. - We can use DISABLE clause both CREATE TABLE statement and the ATLER TABLE statement. - Disable a unique or primary key constraint removes the unique index. Enabling constraints: Activate an integrity constraint currently disabled in the table definition by using the enable clause. - A UNIQUE OR PRIMARY KEY index is automatically created which were removed disable the constraint. Cascading Constraints: It is used along with the DROP COLUMN clause. It drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns. USER_CONSTRIANTS: Query the user_constraints table to view all constraint definitions and names. USER _CONS_COLUMNS: View the columns associated with the constraint names in the USER_CONS_COLUMNS view. This view is especially useful for constraints that use system assigned names. 11. VIEWS What is a view: You can present logical or combinations of data by creating views of tables. A view is a logical table based on table or another view. - The view is stored as a SELECT statement in the data dictionary. Why use views: To restrict data access To make complex queries easy To provide data independence To present different views of the same data

Simple view: - Derives data from only one table. - Contains no functions or groups of data - Can perform DML operations through the view Complex view: - Derives data from many tables - Contains functions or group of data

Tamil
-

Page 17 of 22

sql notes.doc

Does not always allow DML operations through the view Create a view by embedding a subquery within the CREATE VIEW statement. Once your view has been created, you can query the data dictionary view call USER_VIEWS to see the name of the view definition. The text of the SELECT statement that constitutes your view is stored in a LONG column. Modifying a view by using CREATE OR REPLACE VIEW clause. You cannot modify data in a view if it contains Group functions, A GROUP BY clause, The DISTINCT keyword, The pseudocolumn ROWNUM keyword, column defined by expressions, Not null columns in the base tables that are not select by the view.

Using WITH CHECK OPTION clause: You can ensure that DML operations performed on the view stay within the domain of the view. Using WITH READ ONLY Clause: You can ensure that no DML operations occur by adding this clause. - You use the DROP VIEW statement to remove a view. Inline views: A inline view is a subquery with an alias that you can use FROM clause of the main query. - The subquery defines a data source that can be referenced in the main query. Top-N Analysis: Top-N Analysis use a consistent nested query structure. - A subquery or a inline view to generate the sorted list of data. The subquery or the inline view includes the ORDER BY clause that the ranking is in the desired order. - For results retrieving the largest values, a DESC parameter is need. - An outer query to limit the number of rows in the final result set. - The ROWNUM column, which assigns a sequential value starting with 1 to each of the rows returned from the subquery. - A WHERE clause, which specifies the n rows to be returned. The outer where clause must use a < or <= operator. 12. Sequence, Index and Synonym What is a sequence: A sequence is a user created database object that can be shared by multiple users to generate unique integers. - Is a sharable object. - Is typically used to create a primary key value. - Verify your sequence values in the USER_SEQUENCES data dictionary table. - NEXTVAL return the next available sequence value. CURRVAL obtains the current sequence value. Gaps in sequence values can occur when: - A rollback occurs. - The system crashes. - A sequence is used in another table. - When we modify the sequence with alter sequence clause the future sequence numbers are affected. - Remove a sequence from the data dictionary by using the DROP SEQUENCE statement. What is an Index: An index is a schema object is used by the oracle server to speed up the retrieval of rows by using a pointer. - Automatically (unique index): A unique index is created automatically when you define a primary key or unique constraint in a table definition. - Manually: Users can create nonunique indexes on columns to speed up access to the rows. - Index can be created on one or more columns. When to Create an Index: - A column contains a wide range of values, large number of null values. One or more columns are frequently used together in a where clause or a join condition. - The table is large and most queries are expected to retrieve less than 2 to 4 percent of the rows. When not to create an index: - The table is small and One or more columns are not frequently used together in a where clause or a join condition. - The table updated frequently and queries retrieve more than 2 to 4 percent of the rows in the table. - The indexed columns are referenced as part of an expression. - Confirming indexes by using USER_INDEXES and USER_IND_COLUMNS views in the data dictionary. - Function based index is an index based on expression.

Tamil
-

Page 18 of 22

sql notes.doc

Drop the index from the data dictionary by using the DROP INDEX command. You cannot modify indexes.

What is Synonym: Simplify access to objects by creating a synonym. - Another name for an object. - Ease referring to a table owned by another user. - Shorten lengthy object names. - Public synonym accessible to all users. - To drop a synonym, use the DROP SYNONYM statement. 13. Controlling User Access Controlling User Access: Database security can be classified into two categories: System Security: It covers access and use of the database at the system level, such as username and password. Database Security: It covers access and use of the database objects and the actions that those users can have on the objects. Privileges: Privileges are the right to execute particular SQL statement. System Privileges: Gaining access to the database. - More than 100 privileges are available. - The database administrator has high-level system privileges. - Create user, drop user, drop any table, backup any table, select any table and create any table. - Once a user is created, the DBA can grant specific system privileges to a user. - The application developer may have following privileges. - CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE VIEW AND CREATE PROCEDURE. - Current system privileges can be found in the dictionary view of SESSION_PRIVS. What is role: A role is a named group of related privileges that can be granted to the user. This method makes it easier to revoke and maintain privileges. Object Privilege: An object privilege is a privilege or right to perform a particular action on a specific table, view, sequence or procedure. - Each object has a particular set of grantable privileges. - Object privileges vary from object to object. - An owner has all the privileges on the object and an owner can give specific privileges on that owners object. - If the grant includes WITH GRANT OPTION, then the grantee can further grant the object privilege to other users. - PUBLIC: Grants object privileges to all users. How to Revoke Object privileges: You use REVOKE statement to revoke privileges granted to other users. Privileges granted to others through the WITH GRANT OPTION clause are also revoked. CASCADE CONSTRAINTS: Is required to remove any referential integrity constraints made to the object by means of the REFERENCE privilege.

Database Links: A database link connection allows local users to access data on a remote database. 15. SET OPERATORS Set operators: The set operators combine the results of two or more component queries into one result. Queries containing SET operators are called compound queries. - All set operators have equal precedence. - Set operators evaluates from left to right

Tamil
The Set -

Page 19 of 22

sql notes.doc

Oracle Server and Set Operators: Duplicate rows are automatically eliminated except in UNION ALL. Column names from the first query appear in the result. The out is sorted in ascending order by default except in UNION ALL. Operator Guidelines: The expressions in the select lists must match in number and data type. Parentheses can be used to alter the sequence of execution. The ORDER BY clause can appear only at the very end of the statement. It can accept the column name, aliases from the first select statement, or the positional notation.

UNION Operator: The union operator returns all rows selected by either query and eliminate any duplicate rows. - The number of columns and the data types of the columns being selected must be identical in all the select statements used in the query. - The result is sorted in ascending order of the first column of the first select statement. UNION ALL Operator: It returns all rows from multiple queries and including all duplications. The result also not sorted. INTERSECT Operator: Use the intersect operator to return all rows common to multiple queries. -It does not ignore null values. MINUS Operator: Use the minus operator to return rows returned by the first query that are not present in the second query. - All of the columns in the WHERE clause must be in the select clause for the MINUS operator to work. 16. Oracle9i: Datatime Functions TZ_OFFSET: Function returns the time zone offset corresponding to the value entered. The return value is dependent on the date when the statement is executed. Ex: SELECT TZ_OFFSET (US/Eastern) FROM DUAL; Output: -04:00 CURRENT_DATE: Function returns the current date in the sessions time zone. The return value is a date in the Gregorian calendar. CURRENT_TIMESTAMP: Function returns the current date and time in the session time zone, as a value of the data type TIMESTAMP WITH TIME ZONE. LOCALTIMESTAMP: Function returns the current date and time in the session time zone in a value of data type TIMESTAMP. DBTIMEZONE: The default database time zone is the same as the operating systems time zone. You set the databases default time zone by specifying the SET TIME_ZONE clause of the CREATE DATABASE statement. SESSIONTIMEZONE: Function returns the value of the current sessions time zone. EXTRACT: The extract expression extracts and returns the value of a specified datetime field from a datetime or interval value expression. FROM_TZ: The FROM_TZ function converts a TIMESTAMP value to a TIMESTAMP WITH TIME ZONE value. TO_TIMESTAMP: Function converts a string of CHAR, VARCHAR2, NCHAR or NVARCHAR2 data type to a value of TIMESTAMP data type. TO_TIMESTAMP_TZ: Function converts a string of CHAR, VARCHAR2, NCHAR or NVARCHAR2 data type to a value of TIMESTAMP WITH TIME ZONE data type. TO_YMINTERVAL: Function converts a character string of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type to an INTERVAL YEAR TO MONTH data type. The INTERVAL YEAR TO MONTH data type stores a period of time using the YEAR and MONTH datetime fields.

Tamil

Page 20 of 22
17. ENHANCEMENTS TO THE GROUP BY CLAUSE

sql notes.doc

Group by with ROLLUP and CUBE Operators: Use rollup or cube with group by to produce superaggregate rows by cross referencing columns. Rolluup: It is extension to the group by clause. Rollup grouping produces a result set containing the regular grouped rows and the subtotal values. - The rollup operator is useful if there are many columns involved in producing the subtotals. - Given n expressions in the ROLLUP operator of the GROUP BY clause, the operation results in n+1groupings. Cube: It is extension to the group by clause. Cube grouping produces a result set containing the rows from rollup and cross tabulation rows. - If you have n columns or expressions in the GROUP BY clause, there will be 2 power n(2^n) possible superaggregate combinations. Grouping function: The grouping function can be used with either the CUBE or ROLLUP operator to help you understand how a summary value has been obtained. - The grouping function uses a single column as its argument. - The expr in the grouping function must match one of the expressions in the GROUP BY clause. - Using the grouping function, you can differentiate stored null values from null values created by ROLLUP or CUBE. - The function returns 1 for column has null value, 0 returns for column has value. Grouping Sets: Grouping sets are a further extension of the GROUP BY clause. - You can use grouping sets to define multiple groupings in the same query. Grouping set efficiency: - Only one pass over the base table is required. Ex: GROUP BY GROUPING SETS ((department_id, job_id), (job_id, manager_id)); Composite Columns: To specify composite columns, use the GROUP BY clause to group columns within parentheses so that oracle server treats them as a unit while computing ROLLUP or CUBE operations. Ex: GROUP BY ROLLUP(department_id, (job_id, manager_id)); Concatenated Groupings: - Concatenated groupings offer a concise way to generate useful combinations of groupings. - The concatenated groupings are specified simply by listing multiple grouping sets, cubes, and rollups, and separating them with commas so that the oracle server combines them into a single GROUP BY clause. Ex: GROUP BY department_id, ROLLUP(job_id), CUBE(manager_id); 18. Advanced Subqueries Subqueries can be used for the following purposes: - To provide values for conditions in WHERE, HAVING and START WITH clauses of SELECT statements. - To define the set of rows to be inserted into the target table of an INSERT or CRATE TABLE statement. - To define the set of rows to be included in a view or snapshot in a CRAATE VIEW statement. - To define one or more values to be assigned to existing rows in an UPDATE statement. Multiple Column Subqueries: Each row of the main query is compared to values from a multiple row and multiple column subquery. Multiple column subquery can be two types: Pairwise comparisons subquery: The columns in the where clause retrieves values based on the columns in the inner query (subquery). The values of the columns are match values of the main query (outerquery) if match found the matched rows are executed. Nonpairwise comparison subquery: The columns in the where clause are separated we using the subquery for each column in the where clause, retrieves values based on the columns in the inner query (subquery), The values of the columns are match values of the main query (outerquery), if match found the matched rows are executed. Scalar Subquey Expressions: It is a subquery that returns exactly one column value from one row.

Tamil
-

Page 21 of 22

sql notes.doc

It were supported in oracle8i only in a limited set of cases, those are Select statement (FROM and WHERE clauses). VALUES list of an INSERT statement. In oracle9i, it can be used in: Condition and expression part of DECODE and CASE. All clauses of SELECT except GROUP BY.

Correlated Subqueries: Correlated subqueries are used for row by row processing. Each subquery is executed once for every row of the outer query. - The subquery references a column from a table in the parent query. Execution of Correlated subquries: - Geta a candidate row (fetched by the outer query). - Execute the inner query using the value of the candidate row. - Use the values resulting from the inner query to qualify or disqualify the candidate. - Repeat until no candidate row remains. Using the EXISTS Operator: This operator is frequently used with correlated subqueries to test whether a value retrived by the outer query exists in the results set of the values retrieved by the inner query. - If a subquery row value is found the condition is flagged TRUE and the search does not continue in the inner query. - If a subquery row value is not found the condition is flagged FALSE and the search continues in the inner query. Correlated UPDATE and DELETE: Use a correlated subquery to update and delete rows in one table based on rows from another table. The WITH clause: - The WITH clause enables you to reuse the same query block in SELECT statement when it occurs more than once within a complex query. It improves performance. - It is used only with SELECT statements. 19. Hierarchical Retrieval Tree walking: Where a hierarchical relationship exists between the rows of a single table, a process called tree walking enable the hierarchical to be constructed. The parent child relationship of a tree structure enables you to control: - The direction in which the hierarchy is walked. - The starting point inside the hierarchy. Hierarchical queries can be identified by the presence of the CONNECT BY and START WITH clauses. LEVEL: You can explicitly show the rank or level of a row in the hierarchy by using the LEVEL, the LEVEL pseudocolumn returns 1 for a root row, 2 for a child of a root, 3 for child of child and 4 for leaf node is any node without children. START WITH: Specifies the root rows of the hierarchy(where to start). This clause is required for a true hierarchical query. - Specifies the condition that must be met. - Accepts any valid condition. Ex: START WITH column1= value CONNECT BY PRIOR: Specifies the columns in which the relationship between parent and child rows exist. This clause is required for a hierarchical query. - The direction of the query, whether it is from parent to child or from child to parent, is determined by the CONNECT BY PRIOR column placement. - The PRIOR operator refers to parent row. - CONNECT BY PRIOR column1 = column2 - Top down column1 = parent key, column2 = child key. - Bottom up column1=child key, column2= parent key.

Tamil
It cannot contain a subquery.

Page 22 of 22

sql notes.doc

The SELECT statement cannot contain a join or query from a view that contains a join.

Pruning Branches: You can use the WHERE and CONNET BY clauses to prune the tree. That is, to control which nodes or rows are displayed. Use the WHERE clause to eliminate a node. Use the CONNECT BY clause to eliminate a branch. 20. Extensions to DML and DDL statement Multitable INSERT: The INSERTSELECT statement can be used to insert rows into multiple tables as part of a single DML statement. Syntax:

INSERT [ALL] [conditional_insert_clause] [insert_into_clause values_clause] (subquery) Conditional_insert_clause [ALL] [FIRST] [WHEN condition THEN] [insert_into_clause values_clause] [ELSE] [insert_into_clause values_clause]
Unconditional INSERT [ ALL into_clause]: Specify ALL followed by multiple insert_into_clauses to perform an unconditional multiple insert. The oracle server executes each insert_into_clause once for each row returned by the subquery. Conditional INSERT [conditional_insert_clause]: Specify the conditional_insert_clause to perform a conditional multitable insert. The oracle server filters each insert_into_clause through the corresponding WHEN condition, which determines whether that insert_into_clause is executed. - A single multitable insert statement can contain up to 127 WHEN clauses. Conditional INSERT [ALL]: If you specify ALL, the oracle server evaluates each WHEN clause regardless of the results of the evaluation of any other WHEN clause. For each WHEN clause whose condition evaluates to true, the oracle server executes the corresponding INTO clause list. Conditional FIRST: [INSERT]: If you specify FIRST, the oracle server evaluates each WHEN clause in the order in which it appears in the statement. If the first WHEN clause evaluates to true, the oracle server executes the corresponding INTO clause and skips subsequent WHEN clauses for the given row. Conditional INSERT: [ELSE clause]:If no WHEN clause evaluates to true, If you have specified an ELSE, clause the oracle server executes the INTO clause list associated with the ELSE clause. Restriction on Multitable INSERT Statements: - You can perform multitable inserts on tables, not on views or materialized views. - You cannot perform a multitable insert a remore table. - In a multitable insert, all of the insert_into_clauses cannot combine to specify more than 999 target columns. Pivoting INSERT: Pivoting is an operation in which you need to build a transformation such that each record from any input stream, such as, a nonrelational database table, must be converted into multiple records for a more relational database table environment. External tables: - External tables are read only tables in which the data is stored outside the database in flat files. - The metadata for an external table is created using a CREATE TABLE statement. - With the help of external tables, oracle data can be stored or unloaded as flat files. - The data can be queried using SQL, but you cannot use DML and no indexes can be created. Create index with CREATE TABLE statement: CREATE TABLE NEW_EMP( emp_id number(6) PRIMARY KEY USING INDEX (CREATE INDEX e_id_idx ON NEW_EMP(emp_id));

Das könnte Ihnen auch gefallen