Rdbms 3
Rdbms 3
ROUNDING BY INSERT:
               If we insert values 543.876 in a NUMBER(6,2) column, the precision is 4, and the
       scale is 2. the resulting values will be 543.88 rounded to 2 decimal places, or a scale of 2.
SUBSTITUTION VARIABLES:
                The SQL language does have substitution variables, which enable us to create
                 an interactive SQL script.
                When we execute the script, Oracle prompts us to enter a value for the
                 substitution variable.
                The ampersand (&) character is used before the substitution variable in the
                 query.
Example
CUSTOMIZED PROMPTS:
               The SQL *Plus command ACCEPT is used for customized prompts. The
                ACCEPT command does not use an ampersand in front of the variable name.
               we might to use the ACCEPT statement for a variable to be used later more
                than 1 INSERT statement. The syntaxis as follows
                ACCEPT variable name PROMPT >prompt message?
Example
DISTINCT FUNCTION:
                 This function is used to suppress duplicate values. The word DISTINCT is used right
         after the keyword SELECT and before the column name.
                        Sql > SELECT NAME FROM S1;
                                SUMI
                                SUMI
                                VINO
                                MATHU
                                MATHU
                                FANSI
                        Sql > SELECT DISTINCT name FROM S1;
                                SUMI
                                MATHU
Column alias:
     The syntax is SELECT column name [AS] alias……
    Column aliases are useful, because we change the column?s heading.
    When a calculated value is displayed, the mathematical expression is not displayed as the
     column heading, but the column alias is displayed.
    The column alias is written right after the column name with the optional keyword. If an alias
     includes spaces or special characters or if we want to preserve its case, we must enclose it in
     double quotes (< <).
COLUMN COMMAND:
                  Sql*Plus COLUMN command allows us to specify format column for columns. The
          syntax is
                         COLUMN column name FORMAT format type
          For
          example,       COLUMN state FORMAT AS
                         COLUMN salary FORMAT $999.999
CONCATENATION:
   The word concatenation is a common word. Concatenation means joining or linking. In SQL,
    concatenation joins a column or a character string to another column.
   The result is a column that is a string or a sequence of characters. 2 vertical bars or pipe
    symbols (||) are used as the concatenation operator. the 2 columns values are joined without any
    spaceseparating them.
                       SQL > SELECT lname || fname
                       2       FROM
                       EMP; LNAME | |
                       FNAME
                       MATHU
                       VINO
                       FANSI
                       VIANY
                               2      rows selected.
                       SQL >
ARITHMETIC OPERATIONS:
            It is used to display mathematically calculated data. These expressions use columns,
      numeric values and arithmetic operators.
          Operator         Use
          *                Multiplication
          /                Division
          +                Addition
          -                Subtraction
ORDER OF OPERATION:
            The order is
                               Whatever is in parentheses is done first.
                               Multiplication and division have higher precedence than addition and
                                subtraction.
                               If more than 1 operator of the same precedence is present, the
                                operators are performed from left to right.
              We are familiar with relational and logical operators. The logical operators AND and
       OR work with 2 conditions, whereas NOT works with only1 condition. All 3 return a TRUE
       or FALSE result.
       Logical operator                             Meaning
       AND                                          Returns TRUE only if both conditions are
                                                    True
       OR                                           Returns TRUE if 1 or both conditions are
                                                    True
       NOT                                          Returns TRUE if the condition is false
       Operator                                          Meaning
       IS NULL                                           Is a null value
       BETWEEN…..AND                                     Is between a range of values (both
                                                         included)
       IN                                                Match any value from a list (an alternate
                                                         way to write OR)
       LIKE                                              Match a value using wild cards
       When the relational and logical operators are used together, the order of precedence is as
       follows if all operators exist.
              Whatever is in parentheses is performed first
              Relational operators are performed second
              The NOT operator is performed first
              The AND operator is performed 4th.
              The OR operator is performed last.
WILD CARDS:
              We can select rows that match a pattern of characters. Such a search is known as a
       wild card search. There are 2 wild cards for a pattern search.
       For example
              SQL > SELECT name, phone from faculty where name like >C%?;
              Name       pho
              sumi        435
              sunil       445
       For example,
              SQL > SELECT lname from emp where hd like >
              %6_?; Lname              hd
              Sunil                    15-apr-90
Sonia 19-apr-98
SORTING:
                  The ORDER BY clause is used with the SELECT query to sort rows in atable. The
           rows can be sorted in ascending or descending order. The rows can be sorted based on 1 or
           more columns. The syntax for that is
                  SELECT column list
                  FROM table name
                  [WHERE condition(s)]
                  [ORDER BY column expression [ASC\DESC]];
           ASC stands for ascending order.
           DESC stands for descending order.
           Type of value                               Ascending sort order
           Numeric                                     Lowest to highest value
           Character                                   Alphabetical order
           Date                                        Earliest date to latest date
                  The substitution variables can be used in statements other than the INSERT statement.
           They can substitute for column names, table names, expressions or text. Their use is to
           generate queries by inserting them as follows.
                  In the SELECT statement in place of a column
                  name In the FROM clause in place of a table name
                  In the WHERE clause as a column expression or
                  text As an entire SELECT statement
DEFINE COMMAND:
A variable can be defined at the SQL> prompt. The variable is assigned a value that isheld until the user
exits from SQL*Plus or undefines it. The syntax is
                          DEFINE variable [=value]
           For example,
                          DEFINE Last = Sunil
The DEFINE Last command will return the value of the variable if it already has a value.
         Otherwise oracle will display an <UNDEFINED= message.
               The variable?s value can be erased with the UNDEFINE command. For example,
                       UNDEFINE last
CASE STRUCTURE:
BUILT-IN FUNCTIONS
Single-Row Functions
                  The single-row functions take different types of arguments, work on data item from
          each row, and return one value for each row. The arguments are in the form of a constant
          value, variable name, column, and/or expression. The value returned by a function may be of
          a different type than the argument(s) supplied. The general syntax is
          Function (column/expression [, argument1, argument2,…])
          Where function is the name of the function, column is a column from a table, expression is a
          character string or a mathematical expression, and argument is any argument used by the
          function
                 There are various types of single-row functions:
                 Character functions take a character string or character-type column as an argument and
                 return a character or numeric value.
                 Number functions take a number or number-type column as an argument and return a
                 numeric value.
                 Date functions take a date value or date-type column as an argument and return date-type
                 data.(Exception: The MONTHS_BETWEEN functions returns a numeric value)
                 Conversion functions convert value from one data type to another.
                 General functions perform different tasks.
Character Functions. The character function perform case conversion or character manipulation .The
case conversion character functions change a string or character-type column data?s case. For
example
                UPPER(>Oracle?)                                ->?ORACLE?
                LOWER(>DaTaBaSe SyStEmS?)                   ->?Database systems?
                INITCAP       (>DaTaBaSe SyStEmS?)                ->?Database systems?
         Character Function                                Use
         UPPER(Column/expr)                                Converts each letter to uppercase
         LOWER(Column/expr)                                Converts each letter to lowercase
case
Numeric Functions .The numeric functions take numeric value(s) and return a numeric
value.The ROUNDfunction rounds the value,expression,or column to n decimal places.If n is
omitted ,zero decimal place is assumed.If n is negative,rounding takes place to the left side of
the decimal place,forexample
                       ROUND(25.465,2)=25.47
                       ROUND(25.465,0)=25
                       Round(25.465,-1)=30
         The TRUNC function truncates the value,expression,or column to n decimal places.If
n is not supplied ,zero decimal place is assumed.If n is negative,truncation takes place to the
left side of the decimal place.for example,
                       TRUNC(25.465,2)=25.46
                       TRUNC (25.465,0)=25
                       TRUNC 25.465,-1)=20
POWER(2,4)=16
POWER(5,3)=125
                        Prepared by K.Gokul HOD of BCA(Dr.R.A.N.M
                                                      lOMoARcPSD|341 746 99
The ABS function returns the absolute value of a column,expression or value for example
       The SIGN function returns -1 for a negative number,1 for a positive number. And 0 for a
       zero.for example,
                     SIGN(-50)=-1
                     SIGN(+43)=1
                     SIGN(0)=0
       The FLOOR function is similar to the TRUNC function,and theCEILL function is similar to
       the ROUND function.However,both take one argument instead of two,for example
       FLOOR(54.7)=54
       CEIL(54.3)=55
SQL>SELECT ROUND(5.55,1),TRUNC(5.5),SIGN(−5.5),MOD(5,2),
5.6 5 −1 1 5 81 5 6
SQL>
                              Figure 1-Using Numeric Functions
DUMMY VARCHAR2(1)
−−
  This Query will display the current date.You can get more information about day,date and
  time by using a format mask with SYSDATE function
  OTHER FUNCTIONS: The NVL function converts a null value to an actual value supplied
  as an argument. The second argument is enclosed with in the single quotation marks for
  columns with DATE,CHAR, or VARCHAR2 data types.The general syntax is
                                      NVL(column,value)
NVL(PreReg.9None9)
CONVERSION FUNCTION: The conversion function convert data from one data type to
another .The oracle server follows some rules to convert data type implicit. For example, if
you enter a character string that includes a valid number, the oracle server can successfully
covert CHAR data to NUMBER data.if you enter a date as a string and use the default date
format DD-MON-YY, the Oracle server can perform CHAR-to-DATE conversion
successfully. Its advisable to use explicit data conversion functions for successful and reliable
queries. The three conversion functions shown below are used for explicit data type
conversion in queries
GROUPING DATA
                       The rows in a table can be divided into different groups to treat each
group separately.The group function can be applied to individual groups in the same fashion
they are applied to all rows.the GROUP BY clause is used for grouping data. The general
syntax is
                      SELECT column,groupfunction(column)
                      FROM table name [WHERE condition(s)]
                      [GROUP BY column/expression]
                       [ORDER BY column/expression [ASC/DESC0];
      when you include a group function and the GROUP BY clause in your query , the individual
      column(s) appearing the SELECT must also appear in GROUP BY
      The WHERE clause can still be used to restrict data before grouping
      The WHERE clause can?t be used to restrict groups
      A column alias can?t be used in a GROUP BY clause
      The GROUP BY column does not have to appear in a SELECT query
      When a column is used in the GROUP BY clause,the result is sorted in ascending order by
      that column by default . In other words ,GROUP BY has an implied OREDER BY clause
      explicitly to change the implied sort order
      In oracle 9i the order of the WHERE and GROUP BY clauses in the SELECT query does not
      matter,but traditionally ,the WHERE clause is written before the GROUP BY clause
HAVING clause
location
2 WHERE UPPER(building)<>’KENNEDY’
3 GROUP BY building
4 HAVING COUNT(*)>=4;
*HAVING Clause
*GROUP BY sort order changed with ORDER BY
     SQL>SELECT Building ,COUNT(*) FROM
3 HAVING COUNT(*)>2
BUILDING COUNT(*)
JOIN
               When the required data are in more than one table, related tables are joined using a
       join condition. The join condition combines a row in one table with a row in another table
       based on the same values in the common columns. In most cases (but not always), the
       common columns are primary key in one table and a foreign key in another table. In this
       section, you will be introduces to different types of joins based on the join condition used.
CARTESIAN PRODUCT
               A Cartesian product results a multitable query that does not have a WHERE clause.
       The product operation joins each row in first table with each row in second table. The product
       normally results in an output with a large number of rows and is not very useful. Whenever
       retrieving data from more than one table, you must use one or more valid join conditions to
       avoid a Cartesian product! You would perform a Cartesian product operation only if you a
       looking to find all possible combinations of rows from two tables.
               In figure 7-1, you will see an example of a product in which all students and faculty
       members are matched unconditionally. All resulting rows are not shown in the figure. The
       last and first names are selected from the STUDENT table and a name is selected from the
       FACULTY table. There is no join condition issued. The result is 48 rows, because the
       product of two table with m and n rows, respectively, returns m * n rows. The STUDENT
       table has 6 rows and the FACULTY table has 8 rows, hence the result (6 * 8 rows). If you are
       looking for each student?s last name and his or her faculty adviser?s name, you would use a
       join condition using the STUDENT table?s foreign key FacultyId and the FACULTY table?s
       primary key FacultyId to find matching rows.
               The Cartesian product is covered in this section, but it is not a join operation. There is
       no join without a join condition. In oracle, you will perform a Cartesian product by not
       providing enough join conditions in the SELECT query. Remember that the number of join
       conditions is one less than the number of table names used in the FROM clause. There are
       four types of joins in Oracle:
           1. Equijoin
           2. Nonequijoin
           3. Outer join
           4. Self-join
EQUIJOIN
               The equijoin is a join with a join condition involving common columns from two
       tables. If you need to get information about a student from STUDENT table and
                                               lOMoARcPSD|341 746 99
corresponding information about the faculty adviser from the FACULTY table, you would
use the following syntax:
                       SELECT columnnames
FROM tablenames
        The column names include columns from both tables separated by commas, table
names are all tables used separated by commas, and join condition is a condition that includes
common columns from each table. The join condition normally (but not always) includes a
foreign key column from one table and referenced primary key column from the other table.
Suppose you want to get a student?s last name, the student?s first name, the faculty adviser?s
name and the faculty adviser?s phone number. You would get them from the STUDENT and
FACULTY tables. The common column in both tables is FacultyId, which is the foreign key
in the child STUDENT table and the primary key the parent FACULTY table. The join
condition will return the requested information from rows in two tables where the FacultyId
value is same. The rows without a match are not selected by the query.
        In figure 7-2 you see that all students are picked from STUDENT table, but faculty
members are picked based on the FacultyId in the student rows. The faculty member Collins
(FacultyId = 33) is not selected because there is no match for it in the STUDENT table. On
the other hand, Chang (FacultyId = 555) is picked twice because it appears twice as a value in
the foreign key column of the STUDENT table.
        The Cartesian product, as mentioned earlier, is rarely useful, equijoin is a very
important operation in database querying. Another thing to be notes is the use of
tablename.columnname. When columns are retrieved from more than one table, the use of
table name qualifier in front of the column name tells Oracle to retrieve that column from the
specified table. Oracle is pretty smart about it. If a column name exists in only one of the two
tables involved in the query, it is not necessary to use a table name as a qualifier. If a column
exists in both tables, you must use the table name qualifier. Because the join condition
usually has the same column names from two tables, the column names become ambiguous
without a qualifier. The qualifier actually improves performance because you are telling the
Oracle server where to go to find that column. Remember that the two join columns need not
have the same name.
        Sometimes, the required information is in more than two tables. In this case, the
FROM clause will include all needed tables, and the WHERE clause will have more than one
join condition. If you need to join n tables, you would need n – 1 join conditions. In our
NamanNavan (N2) Corporation database, an employee?s demographic information is in the
EMPLOYEE table. The EMPLOYEE table has three foreign keys: PositionId, referencing the
POSITION table; QualId, referencing the QUALIFICATION table; and DeptId, referencing
the DEPT table. You would need to join four tables to retrieve information from all those
tables. This means the query will have 4 – 1 = 3 join conditions.
        The query will look like the one shown in figure 7 -3. For simplicity, we will join
three tables using two join conditions. There is no limit on the number of join conditions
within a query.
                                              lOMoARcPSD|341 746 99
       The multiple-join example selects information from three tables using a query with
two join conditions. If you look at the query, the table qualifiers are used quite a few times.
There is a way to shorten and simplify this query.
TABLE ALIASES
        In chapter 5, you learned about column aliases, which are used for renaming column
headings in a query. Table aliases are used to avoid using lengthy table names over and over
again in a query. A table alias can be from 1 to 30 characters long. Normally very short alias
names are used to shorten the query and save some keystrokes. The table aliases appears in
the FROM clause of the SELECT query. A table name is written, followed by a space, and
then a table alias is supplied. Though they appear after the SELECT clause, alias names can
also be used as qualifiers for column names in the SELECT clause. All table aliases are valid
only in the SELECT query, where they are named and used.
        In figure 7-4, you will see the query from figure 7-3 with table aliases. The results
obtained from the queries in figure 7-3 and 7-4 are similar, but the query in figure 7-4 is
shortened by the use of table aliases. In this example, we joined the EMPLOYEE table with
the QUALIFICATION tables instead of the POSITION table. The result contains seven rows
in figure 7-4 instead of eight rows, as in figure 7-3, because one of the employees does not
have a QualId.
ADDITIONAL CONDITIONS
        In addition to join conditions, you may use additional conditions using the AND
operator to restrict information. Suppose you want to see the information of figure 7-4 for
employees belonging to department number 10 only. Figure 7-5 shows the use of additional
condition with the AND operator where the information is displayed for DeptId = 10 only.
The three tables are joined for employees in Department 10, which results in three rows
instead of all eight employee rows.
NONEQUIJOIN
        There is no matching column in the EMPLEVEL table for the Salary column in the
EMPLOYEE table. The only possible relationship between the two tables is between the
Salary column of the EMPLOYEE table and the LowSalary and HighSalary columns in the
EMPLEVEL table. The join condition for these tables can be written using any operator other
than the = operator. That is why it is called nonequijoin.
The nonequijoin condition of figure 7-6 could have been written as:
        If you look at the EMPLEVEL table, none of the salaries appears in more than one
level. In other word, there is no overlapping. None of the employees makes a salary that is
not included in the range of salaries. For these two reasons, each employee appears once in
                                               lOMoARcPSD|341 746 99
result. Note that none of the columns are ambiguous, so table aliases are not necessary
(though they are used here in this example).
OUTER JOIN
        You saw in the equijoin that the rows from two tables are selected only if common
column values are the same in both tables. If a row in one table does not have a matching
value in the other table, it is not joined. Figure 7-2 displayed all students from the STUDENT
table and their advisers from the FACULTY table. Some of the faculty members are not any
student?s adviser, so they did not get selected. Suppose you also want to see all those faculty
adviser names. Then, you would change your query?s join condition and create a join known
as outer join.
        The table that does not contain the matching values is known as the deficient table. In
our case, the deficient table is the STUDENT table, because it does not contains all the
FacultyIDs. The outer join uses the (+) operator in the join condition on the deficient side
(You will see it soon in figure 7-8, which compares equijoin and outer join on these tables.).
The (+) operator can be used on any side of the join condition, but it cannot be used on both
sides in one condition.
      The join condition will look different if the (+) operator is used on the right side. For
example,
        Figure 7-7 shows an outer join using the EMPLOYEE and QUALIFICATION tables.
The outer join operator (+) is used on the QUALIFICATION side. Because it is the deficient
table or it generates a null value for the row(s) in the EMPLOYEE table without any
qualification value. The equijoin would have returned seven employees, but the outer join
also includes one extra employee without any qualification.
        Figure 7-8 compares outputs from outer join and equijoin on the same tables. The
equijoin returns six students with their faculty advisers? names, whereas the outer join returns
three extra rows with faculty names. The outer join operator (+) is used on the STUDENT
table?s side, because it generates null values for faculty members with no match in the
STUDENT table.
SELF-JOIN
        A self-join is joining a table to itself. It sounds meaningless, but think about using it
the following scenario: In the EMPLOYEE table, EmployeeId is the primary key column that
                                              lOMoARcPSD|341 746 99
describes each entity. For example, EmployeeId 200 represents employee Shaw, Jinku. The
table also has another column called Supervisor, which contains ID?s of employee
supervisors. How can you find name of the supervisor for an employee? You can look up the
supervisor ID, go to EmployeeId column to find its match, and then read the name. This is
easier said than done, however. A self-join is one join that is not so easy to understand.
        When a table is joined to itself, two copies of same table are loaded or used. They are
treated like any two different tables, and a join is produced from those two copies. Let us
explain that by using the EMPLOYEE table. The following operations are performed in the
performed in the self-join figure 7-9:
  Two copies of the EMPLOYEE table are created with aliases e and s.
Set operator        Use
UNION                   It returns all rows from both queries,but duplicate rows are not repeated .
UNION ALL               It returns all rows from both queries,but displays all duplicate rows.
INTERSECT               It returns all rows that appears both queries? result.
MINUS                   It returns rows that are returned by the first query minus rows that are
    An employee?s last name is picked from the e table, and the corresponding Supervisor
     ID is retrieved.
    The matching EmployeeId id found from the s table. The first employee in the e table
     does not have a supervisor and so is not picked.
    The last name from the s table is retrieved based on the EmployeeId.
     In short, the table is looked at twice, once for the employee and once for the supervisor.
The Indo-US (IU) College database also contains a table, which can be used in self-join.
Table COURSE contains a PreReq column that references its own primary key, CourseId.
SET OPERATORS:
                               SELECT-Query1
                               Set operator
                               SELECT-Query2;
Where the Set operator is one of the four set operators described below:
The set operators UNION,INTERSECTION and MINUS are shown below using venn
diagrams. The left circle represents the first table,and the right circle represents the second
table.The shaded area is the area selected by each operation.The UNION operator selects all
rows from the first table as well as the second table,so both circles are entirely shaded.The
INTERSECTION operator selects rows present in both tables,so the common area is shaded.
                                          lOMoARcPSD|341 746 99
For example, we are using a table called WORKER which contains staff members of the
college and also student workers.
WORKER Table
Union:
   The UNION operator takes output from two queries and returns all rows from both
results.The duplicate rows are displayed only once. If you perform union on two very large
tables,use a where clause to filter rows .All six students rows are selected from the first
query,and four rows are selected from the second query.Two rows from the second query are
duplicate rows(ID 00103 and ID 00105), and they are not repeated.
Union
All:           The UNION ALL operation is similar to the UNION operation. The only
difference is that UNION ALL operation also displays duplicate rows. If you find UNION
ALL of the STUDENT and WORKER tables, you will get six rows from the first query and
six rows from the second query (see fig-2).
ID LAST FIRST
 10 rows
 selected.
ID LAST FIRST
ID LAST FIRST
 12 rows
 selected.
ID LAST FIRST
SQL>
Minus:
           The MINUS operation is same as the DIFFERENCE operation. When MINUS is
performed on outputs from two queries, the result is the rows in the first query?s result that
are not in the second query?s result.
    Remember that the STUDENT table minus the WORKER table is not the same as the
WORKER table minus the STUDENT table.
          Fig-4 is an example of a minus operation in which the result includes students who
are not workers. Fig-5 shows workers who are not students.
ID LAST FIRST
 4 rows
 selected.
ID LAST FIRST
4 rows selected.
SQL>
Union All
The UNION ALL operation is similar to the UNION operation. The only difference is
that UNION ALL operation also displays duplicate rows. If you find UNION ALL of the STUDENT
and WORKER tables, you will get six rows from the first query and six rows from the second query
(see fig-2).
ID LAST FIRST
 10 rows
 selected.
  2 UNION ALL
  3 SELECT Workerid, Last, First FROM worker4 /
ID LAST FIRST
ID LAST FIRST
12 rows selected.
SQL>
Intersect
            The INTERSECT operation works on output from two separate queries and
            returns rows
that appear in both outputs. In the student and worker example, INTERSECT
will return students whoare also workers at the college.
           In fig-3, you see only two student rows, which are the only
students appearing in the WORKER table.
ID LAST FIRST
SQL>
                                     lOMoARcPSD|341 746 99
   2 MINUS
   3 SELECT Workerid, Last, First FROM worker4 /
ID LAST FIRST
00102
 4 rows
 selected.
ID LAST FIRST
4 rows selected.
SQL>