SQL_SAS NOTES.pdf

Embed Size (px)

Citation preview

  • 7/25/2019 SQL_SAS NOTES.pdf

    1/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    What is DBMS?A database management system (DBMS) is a software package with computerprograms that control the creation, maintenance, and the use of a database.

    What is a RDBMS?A relational database management system (RDBMS) is a database managementsystem (DBMS) that is based on the relational model as introduced by E. F. Codd.

    A short def in it ion of an RDBMS is: a DBMS in which data is stored in tables and therelationships among the data are also stored in tables. The data can be accessed orreassembled in many different ways without having to change the table forms.

    Example: Oracle, MS SQL Server, NCR Teradata, IBM DB2, MySQL,MS Access, SyBase etc.

    Most popular databases currently in use are based on the relational database model.

    What is a Database?

    Databases are designed to offer an organized mechanism for storing, managing andretrieving data/information. They do so through the use of tables. Database

    What are the di fferent databases and their versions available?

    Oracle 11g/ 10g/ 9i/ 8iTeradata V2R6.0/ V2R5.0MSSQL 2008/ 2005/ 2000IBM DB2 9.7/ 9.5/ 9.1/8

    MySQL6.0/ 5.5/ 5.4/ 5.1/ 5.0MS Access2010/ 2007/ 2005SyBase12/11 etc.

    www.irctc.co

    m

    End

    End

    Front-

  • 7/25/2019 SQL_SAS NOTES.pdf

    2/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    What is a database schema?Pronounce skee-ma, the structure of a database system, described in a formallanguage supported by the database management system (DBMS). In a relationaldatabase, the schema defines the tables, the fields in each table, and the relationships

    between fields and tables.

    Example: Sales Schema

  • 7/25/2019 SQL_SAS NOTES.pdf

    3/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    What is a table?

  • 7/25/2019 SQL_SAS NOTES.pdf

    4/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    The foundation of every RDBMS is a database object called table.

    Every database consists of one or more tables, which store the data/information.

    Each table has its own unique name and consists of columns and rows.

    The database table columns (also called table fields) have their own unique namesand have a pre-defined data types.

    The table rows contain the actual data for the columns.

    Here is an example of a simple database table, containing employee data.

    The first row, listed in bold, contains the names of the table columns:

    Table: Employees

    Column Column Column Column

    First_Name Last_Name Email DOB

    John Smith [email protected] 2/4/1968

    Steven Goldfish [email protected] 4/4/1974

    Paula Brown [email protected] 5/24/1978

    James Smith [email protected] 20/10/1980

    What is SQL?

    SQL (pronounced "ess-que-el") stands forStructured Query Language.

    The standard SQL commands such as "Select", "Insert", "Update", "Delete","Create", " Alter" and "Drop" can be used to accomplish almost everything that oneneeds to do with a database.

    DDL Data Definition LanguageUsed to CREATE or ALTER Tables, Views, Indexes etc.

    DML Data Manipulation LanguageUsed to SELECT, INSERT, UPDATE, DELETE data from tables

  • 7/25/2019 SQL_SAS NOTES.pdf

    5/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Selecting Data from a tableThe select statement is used to query the database and retrieve selected data thatmatch the criteria that you specify.

    Here is the format of a simple select statement:select "column1" ,"column2"etc from "tablename" [where "condition"]; [] = optional

    To select all columns, use * e.g. select * from employees.

    Where clause is used to filter data.E.g: select * from employees where last_name = 'Smith '

    Creating a DB table

    The create table statement is used to create a new table.

    Here is the format of a simple create table statement:

    create table "tablename" ("column1" "data type", "column2""data type", "column3" "data type");There are different types of data typee.g.NUMBERVARCHAR2BINARYFLOATDATE

    Eg: create table EMP_SAMPLE(EMP_ID number,EMP_NAME Varchar2(30),EMP_START_DATE DATE)

    Note: If you any of the insert, update or delete statements, you must commit (meanssave) or rollback (means revert).

    INSERT Statement

    The insert statement is used to insert or add a row of data into the table.To insert records into a table, enter the key words insert into followed by the tablename, followed by an open parenthesis(, followed by a list of column names separated

  • 7/25/2019 SQL_SAS NOTES.pdf

    6/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    by commas, followed by a closing parenthesis), followed by the keyword values,followed by the list of values enclosed in parenthesis.

    Rules: The order of values should match up with the column names order that you specify.

    Strings should be enclosed in single quotes Numbers and dates should not.

    insert into "tablename" (first_column,...last_column) values (first_value,...last_value);

    Eg: insert into EMP_SAMPLE (E_ID,EMP_NAME) values (101,MyName); commit;

    * If you want to enter values in all the columns of a table , then you dont have tospecify column names.Eg: insert into EMP_TARGET values (102,MyName, sysdate)

    UPDATE StatementThe update statement is used to update or change records that match a specifiedcriteria. This is accomplished by carefully constructing a where clause.

    update "tablename" set "columnname" = "newvalue" [,"nextcolumn" ="newvalue2"...] where "columnname" OPERATOR "value" [and|or"column" OPERATOR "value"];e.g.update EMP_SAMPLEset EMP_NAME = 'Smith',where EMP_ID = 101;

    commit;

    * if you dont specify where cluase in the update statement, the value will be updated forall the rows of that column.

    e.g.update EMP_SAMPLEset EMP_NAME = 'Smith',

    rollback;

    Delete StatementThe delete statement is used to delete records or rows fromthe table.

  • 7/25/2019 SQL_SAS NOTES.pdf

    7/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    delete from "tablename"where "columnname" OPERATOR "value" [and|or "column"OPERATOR "value"];e.g : delete from EMP_SAMPLE where EMP_NAME = 'Smith'; commit;

    Commit and Rollback

    When DML statements l ike DELETE, UPDATE, INSERT are executed on a table,data is not truly saved (i.e. commit ted) to the table until COMMIT is executed.Remember to commit your data changes using COMMIT command.

    If you accidentally changed data in a table using DMLs likeINSERT/UPDATE/DELETE and i f you have not committed the changes yet, then

    you can use ROLLBACK command to get the old data back into the table.

    Never leave un-commit ted data in a table either COMMIT or ROLLBACK.(Reason: Un-committed transactions create table locks!)

    FROM Keyword:

    This keyword is used to determines the data source at the time of retrieving data.

    Eg : Select employee_id, first_name FROM employee;

    WHERE statement:

    This is used to filter the records from an sql statements

    Syntax: Select column1, column2 , column3 .. FROM employee Where ;

    Example: Select EMP _NAME, EMP_ID, from EMP _SAMPLE Where EMP _NAME=smith;

    Delete EMP _NAME, EMP_ID from EMP _SAMPLEWhere EMP _ID=102;

    Here only one record will be deleted

    IF we omit the where condi tion all the records will be deleted

  • 7/25/2019 SQL_SAS NOTES.pdf

    8/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Example: Update EMPLOYEE set EMP _ID=111 where EMP _ID=102;

    Commit;

    *If we dont use where condition all the records wil l be updated.

    NOTE : we can not use group function in where clause.

    Eg: Select EMP_ID,EMP_NAME, count(EMP_ID) from employee Group by EMP_ID,EMP_NAME where count(EMP_ID)>3;*It wil l give errorGroup by Clause:

    Group By clause is used to divide the output of a query into groups.

    Syntax: Select column1, column2, group _function ( column name ) from

    Table name [Where ] [Group by column1, column2];

    Example: Select job from employee group by job;

    Example: Select EMP_NAME,EMP_ID from EMP_SAMPLE Group by EMP_NAME , EMP _ID;

    Example: Select TO _CHAR ( HIRE_DATE , YYYY ) YEAR GROUP fromEMPLOYEES Group by TO _CHAR( HIRE_DATE, YYYY );

    Rules:

    Columns present in select statement must be there in group by clause. All group by clause column list may or may not used in select clause. Column aliases cannot be used in select statements. Extra non group function is used in a select clause , we should not use individual

    result columns.

    ORDER BY CLAUSE:

    Order by clause can be used to sort the rows.

    Syntax: Select column1, column2. From table name[Where conditions]

    Order by columns ASC/DESC;

  • 7/25/2019 SQL_SAS NOTES.pdf

    9/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    ASC: Ascending order, it displays the output in ascending order

    DESC: Descending order, this command will display the output in descending oder.

    Example: Select EMP _NAME, EMP _ID from EMP _SAMPLE ORDER BY EMP _ID;

    Example: Select FIRST_NAME, EMPLOYEE_ID, PHONE from EMPLOYEE ORDER BY EMPLOYEE_ID DESC;

    Example: Select emp _id, emp _name from emp _sample Order by 2;*It will sort based on emp _name because emp _name posit ion is 2.Rules:

    The ORDER BY clause must be the last clause of the sql statement.

    An expression, an alias, column position can be used as the sort Condition, but the position value must be existing in the select list. The default order is ascending order.

    HAVING CLAUSE:

    The having clause is used to filter data is associated with group function.

    Syntax: Select [column], group _function (column)

    From table name[Where condition][Group by group _by _expression][Having having _expression][Order by column/alias];

    Example: Select EMP _NAME, EMP _ID, count (EMP_ID) from EMP_SAMPLE Group by EMP_ID having count (EMP_ID)>3;

    NOTE: We can use count/group funct ion in having clause, but group functionCannot be used in where clause.

    Example: select EMP_NAME, EMP _ID, count (EMP_ID) from EMP_SAMPLEGroup by EMP_ID where count (EMP_ID)>3;

  • 7/25/2019 SQL_SAS NOTES.pdf

    10/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    *It gives Error, we need to use having clause in place of where clause to avoiderrors.

    Rules:

    The column which is used in having clause must be used in group by clause.

    when having clause condition false it returns no rows selected, when where Condition returns zero.

    DISTINCT keyword:

    The DISTINCT keyword is used to eliminate the duplicate rows in the result.We can specify multiple columns after the distinct keyword , it effects all the selectedcolumns.

    Syntax : Select DISTINCT column1,column2. From table name.

    Eg : select FIRST_NAME from EMPLOYEES;CONSTRAINTS:

    Constraints are used to impose business rules to DBs. It allows to enter only valid data.

    There are six types of constraints in OraclE.

    1) NOT NULL Constraint2) UNIQUE Constraint

    3) PRIMARY KEY Constraint4) FOREIGN KEY Constraint 5) CHECH Constraint 6) DEFAULT Constraint

    The Constraint clause can appear in CREATE Table ALTER Table CREAT View

    Level of Constraints:

    1. Column Level : Used to define constraints next in column name

    Define with each column Composite key cannot be defined

  • 7/25/2019 SQL_SAS NOTES.pdf

    11/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Syntax: CREATE table table name (column1 data _type () ConstraintConstraint _name Constraint _type,

    Column2 data _type (), column3 data _type ());

    2. Table Level: Defining Constraints after defining all columns Not Null cannot be defined

    Syntax: CREATE table table name (column1 data _type(), Column2 data _type (), column3 data type (),

    Constraint Constraint _name Constraint _type (column1, column2...));

    NOT NULL Constraint:

    Used to avoid NULL values into columns.Data must be entered.Duplication values allowed.NOT NULL should be defined at column level Only.

    Syntax: Create table table name (column1 data _type(),column2 data _type()Constraint constraint _name NOT NULL,

    Column3 data _type () NOT NULL);

    Example: CREATE table student(Sid number(4) Constraint sid_nn NOT NULL,

    Name varchar2 (20), Gender char);

    *Here constraint keyword and constraint name are optional but recommended.

    UNIQUE Constraint :

    Used to avoid DUPLICATE values into columns. Accepts NULL values. A table can have any number of UNIQUE keys Which is not possible in PRIMARY KEY

    Composite UNIQUE key is possible and always defined at table levelonly. A table can have more than one composite UNIQUE key. An index will be created automatically. A composite UNIQUE key cannot have more than 32 columns.

  • 7/25/2019 SQL_SAS NOTES.pdf

    12/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    The same combination of columns should not make both Unique and primary key.

    UNIQUE key defined at column level:

    Syntax: CREATE table table name (column1 data _type() constraint Constraint _name .UNIQUE,column2 data _type(), Column3 data _type() UNIQUE);

    Example: CREATE table product _master (product _no varchar2 (6), Product _name varchar2 (20) constraint pn_nn NOT NULL,

    Description varchar2 (20), quantity number (8) constraint qty _un UNIQUE);

    At table level:

    Syntax: CREATE table table name (column1 Data _type (), Column2 Data _type (), Column3 Data _type (),

    Constraint Constraint _name UNIQUE (column1, column2);

    Example: CREATE table customer (c_id number number (4) NOT NULL, c_name

    varchar2 (30) ,email varchar2(20),Constraint name_email_un UNIQUE ( c_name, email));

    PRIMARY KEY Constraint:

    Used to define key columns of a table. It will not accept Null values and Duplicate values, When we need both NOT NULL and UNIQUE for a single column

    we will go for PRIMARY KEY. It is provided with an automatic index.

    Rules:

    Only one primary key or composite primary key is allowed per table. A composite PRIMARY KEY cannot have more than 32 columns.

    PRIMARY KEY cannot support in Nested objects. Composite PRIMARY KEY cannot be defined at column level. You cannot designate the same column or combination of columns

    as both a primary key and a unique key.

  • 7/25/2019 SQL_SAS NOTES.pdf

    13/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    PRIMARY KEY constraint Defined at Column Level:

    Syntax: CREATE table table name (column1 data _type() constraintConstrain _name PRIMARY KEY,

    Column2 data _type (), column3 data _type (). );

    Example: CREATE table S _market (item _id number constraint id_pk PRIMARY KEY, Item_name varchar2 (20) constraint name_nn NOT NULL,

    item_rate number(8,2) NOT NULL, p_date date constraint dt_un UNIQUE);

    At table Level:

    Syntax: CREATE table table name(column1 data_type(), column2 data_type(), Column3 data_type(),

    Constraint constraint_name PRIMARY KEY(column1,column2);

    *compos ite primary key is defined at table level only as shown in example.

    Example: CREATE table product( prod _id number(4),prod _name varchar2(20),prod_rate number(6,2),

    mf_date date NOT NULL,Constraint p_pk PRIMARY KEY(prod_id,prod_name));

    FOREIGN KEY(or) REFERENTIAL INTEGRITY Constraint :

    This FOREIGN KEY represents relationships between tables.A FOREIGN KEY column values can be derived from

    PRIMARY KEY or UNIQUEA FOREIGN KEY is column that references a column of same table or another table.The table or view containing the foreign is called the Child object.The foreign key can be defined at column level or table level.A composite FOREIGN KEY can be declared at table level only.The referenced unique or primary key constraint on the parent table or view must already be definedYou cannot define a foreign key in a CREATE table statement that

    contains anAS Sub query clause. Instead, you must create the

    table without the constraint and then add it later with an ALTER table statement .When you specify a foreign key at column level you need only the REFERENCES clause, but when you specify the FOREIGN KEY at table level you must specify the FOREIGN KEY keyword and one or

  • 7/25/2019 SQL_SAS NOTES.pdf

    14/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    more column names.

    Rules:Master table cannot be update if child records exist.A composite FOREIGN KEY cannot have more than 32 columns.

    A child and parent tables must be on same database.Note:FOREIGN KEY identifies the column or combination of columns in the

    Child table that makes up of the foreign key.REFERENCES identifies the parent table and the column or

    Combination of columns that make up the referenced key.CASCADE option used to remove the child table record automatically, When parent record is removed.Specify SET NULL if we want Oracle to convert dependent

    FOREIGN KEY values to NULL.FOREIGN KEY at column level:

    Syntax: CREATE table table name(column1 data _type() constraintconstraint_name FOREIGN KEY(column1)

    REFERENCES parent_table_name( column name), column2 data _type() constraint nn constraint_type,column3 data_type());

    * FOREIGN KEY(column1) is optional when defining at column level.

    FOREIGN KEY at Table Level:

    Syntax : CREATE table table name( column1 data _type(), column2 data _type(), Column3 data _type(), constraint constraint_name

    FOREIGN KEY( column1,column2) REFERENCES parent table(column));

    *When FOREIGN KEY defining at table level FOREIGN KEY keyword ismandatory.

    [When creating a table with foreign key there must be one parent table withPrimary key or unique constraint.]

    Step 1:CREATE table DEPT(DEPTNO number(2) constraint dno_pk PRIMARY KEY

    constraint deptno_chk CHECK(deptno between 10 and 99),dname varchar2(15)constraint dname_nn NOT NULL constraint dname_ck CHECK(Dname=upper(dname)),Loc varchar2(15) default NEW YORK constraint loc_chk CHECK (loc in(NEWYORK,DALLAS, BOSTON, CHICAGO)));

  • 7/25/2019 SQL_SAS NOTES.pdf

    15/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Step 2:CREATE TABLE EMP(empno number(4) constraint empno_pk PRIMARY KEY,

    ename varchar2(20) constraint ename_nn NOT NULLCHECK(substr(ename,1,1) between A AND Z) ANDename=upper(ename)),

    job varchar2(15) constraint job_chk CHECK(job IN(ANALYST, CLERK,MANAGER, PRESIDENT, SALESMAN)),Mgr number(4) constraint mgr_fk_self REFERENCES emp(empno) ON DELETESET NULL,Hiredate date DEFAULT SYSDATE,sal number(8,2) constraint sal_nn NOT NULLconstraint CHK(sal between 1000 and 10000),comm Number(8,2),deptno number(2) constraint deptno_fkREFERENCES dept(deptno), ON DELETE CASCADE);

    CHECK:

    Used to impose a conditional rule on a table column. It defines a condition that each row must satisfy. A column can have any number of check constraints Check constraints can be defined at column level or table level

    Rules:This cannot be include are

    Queries that refer to values in other rows References to the CURRVAL,NEXTVAL,LEVEL or ROWNUM Calls to functions SYSDATE,UID,USER,USERENV.

    Syntax: Create table table name(column1 data_type(),column2 data_type()CONSTRAINT CONSTRAINT_NAME CHECK(),column4

    data type.);

    Example:

    CREATE table student(s_id number constraint sid_chkCHECK(s_id BETWEEN 1 and 60), name varchar2(20) NOT NULL,T_marks number(3) CHECK( T_marks BETWEEN 0 AND 100));

    DEFAULT:

  • 7/25/2019 SQL_SAS NOTES.pdf

    16/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    If values are not provided for the table column default value will be considered. The default value can be a literal, an expression, or a SQL function. The default expression must match the data type of column.

    Syntax:

    Create table table name(column1 data_type(), column2 data_type() DEFAULTexpression/value,column3 data_type());

    Example:

    CREATE table school(sid number PIMARY KEY, name varchar2(20) NOT NULL,Fee number(6,2) default 5000, fee_due number(6,2));

    Adding Constraints to a Exist ing Table:

    Syntax : Alter table table name ADD constraint constraint_nameConstraint type (column names);

    Example: ALTER table emp add constraint emp_pk primary key(empno);

    * NOT NULL and DEFAULT added to existing column by using the MODIFY clause Of the ALTER TABLE statement.

    Example: ALTER table emp modify hiredate date DEFAULT sysdate;

    DROPPING CONSTRAINTS:

    We can find the c onstraint name in USER_CONSTRAINTS andUSER_CONS_COLUMNS whis is to be dropped.

    Alter table statement is used with DROP clause. The CASCADE option of the DROP clause causes any dependent constraints

    also to be dropped. When constraint is dropped, the constraint is no longer available in data

    dictionary.

    Syntax: ALTER table table nameDROP PRIMARY KEY/UNIQUE (column)/CONSTRAINTconstraint _name

    Example : ALTER table emp DROP primary key;

  • 7/25/2019 SQL_SAS NOTES.pdf

    17/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Example : ALTER table dept DROP UNIQUE(Dname);

    Note: When we Drop PRIMARY KEY or UNIQUE constraints the related INDEX wil ldrop automatically.

    *We can find the index_name of table by fo llowing syntax.

    SELECT INDEX_NAME from USER_INDEXES where table_name= EMP;

    DISABLING Constraint:

    The constraint can be disabled without dropping or recreating it.

    Syntax:ALTTER table table name DISABLE constraint constraint_name

    Example : ALTER table emp DISABLE Constraint emp_pk;

    ENABLE Constraint:

    The disabled constraint can be enabled without dropping.

    Syntax :ALTER table table name ENABLE constraint clause.

    Example: ALTER table emp ENABLE constraint emp_pk.

    Enabling a constraint applied to all the data in a table.

    When an UNIQUE or PRIMARY KEY constraint is ENABLED, the UNIQUE orPRIMARY KEY index is automatically created.

    VIEWING Constraints:

    All constraints can be stored in USER_CONSTRAINTS tableThe code that they contained isP-primaryU-uniqueR-referencesC-check& not null

    Syntax: SELECT owner, constraint _name, constraint _type from user _constraints WHERE table _name= ;Example: SELECT owner, constraint _name, constraint _type from user _constraints WHERE table _name= EMP;

  • 7/25/2019 SQL_SAS NOTES.pdf

    18/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Note: When we drop the table all corresponding integrity constraints will droppedAutomatically.

    INDEXES:

    Index is a schema object, which a pointer locates the physical address of Data Index is used by Oracle server ti speed up the retrieval,manipulate the rows.

    Specification of INDEXES:

    INDEX can be created explicitly or automatically. INDEX is activated when indexed column is used in where clause. INDEX Necessity of disk I/O by using an indexed path to locate data quickly. INDEX is used and maintained automatically by the Oracle server. When you drop a table, corresponding indexes are also dropped.

    Creation Types of INDEXES:

    a. Automatic Index:

    A Unique index is created automatically when you define a PRIMARY KEYOr UNIQUE constraint in a table dropped.

    b. User created Index :

    Users can create non unique indexes on columns to speed up access to the rows

    Any number of Indexes can be created on one table. USER_INDEXES holds the details of Indexes.

    *When index is created it forms two dimensional matrix which is independent of thetable, it will hold the sorted data, extracted from table columns and address fieldidentifies the location of the record in Oracle Database(ROWID).

    Note: The records in the index are stored in the ascending order of the INDEX column.

    Rules To Create INDEX:

    The table or cluster to be indexed must be in own schema. INDEX object privilege should be available on the table to INDEXED.

  • 7/25/2019 SQL_SAS NOTES.pdf

    19/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    CREATE any index SYSTEM privilege must be available. UNLIMITED TABLESPACE system privilege or SPACE QUOTA on

    TABLESPACES must be available INDEX cannot be created on columns contain data type as LONG,LONG

    RAW,LOB,REF.

    If INDEX is locally partitioned then the table must be portioned. For Global Temporary table INDEX is also temporary with the same scope,as

    that of the table.

    Syntax: CREATE [UNIQUE] or [BITMAP] INDEX index _name ON Table _name (column name) TABLESPACE TableSpacename.

    *TableSpacenames are Stored in USER_TABLESPACES.

    CHANGING TABLESPACE QUOTQ UNLIMITED:

    ALTER tablespace TableSpacename space QUOTA UNLIMITED.

    Types of INDEXES:

    NORMAL INDEXES:

    They are default indexes

    BITMAP INDEX:

    INDEXES associated with ROWIDS called as BITMAP INDEX. Specify BITMAP to indicate that has to be create with a BITMAP for each DISTINCT KEY. BITMAP indexes should be used only when the data is infrequently updated. The Oracle OPTIMIZER can dynamically convert Bitmap Indexes to ROWIDs During the query processing.

    Syntax: CREATE BITMAP INDEX index _name ON table _name(column _name);

    Example: CREATE BITMAP INDEX si _ind ON student(sid);

    CREATE BITMAP INDEX emp_ind ON emp(deptno);Rules:

  • 7/25/2019 SQL_SAS NOTES.pdf

    20/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    BITMAP indexes should not be used for tables involved in ONLINETRANSACTION PROCESSING APPLICATIONS.

    We cannot specify both UNIQUE and BITMAP.

    COMPOSITE INDEX:

    A composite index also called a concatenated index is an index created onmultiple columns of a table.

    Columns in a composite index can appear in any order and need not be adjacentcolumns of the table.

    Example: CREATE BITMAP INDEX stud_ind ON student(sno, sname);

    UNIQUE INDEX:

    Unique indexes guarantee that no two rows of a table have duplicate values inthe columns that define the index.

    Unique index is automatically created when primary key or unique constraint iscreated.

    Example: CREATE UNIQUE INDEX stud_ind ON student(sno);

    COMPOSITE UNIQUE INDEX:

    Composite Unique Index is an Index On Multiple unique Columns.

    Example: CREATE Unique Index Eno_ename_ind ON EMP(empno,ename);NON-UNIQUE INDEX:

    Non-Unique indexes do not impose the above restriction on the column values.

    Example: CREATE INDEX stud_ind ON student(sno);

    BTREE INDEX or ASCENDING INDEX:

    The default type of index used in an oracle database is the btree index. A btree index is designed to provide both rapid access to individual rows and

    quick access to groups of rows within a range. The btree index does this by performing a succession of value comparisons.

    Each comparison eliminates many of the rows.

  • 7/25/2019 SQL_SAS NOTES.pdf

    21/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Ex: CREATE INDEX stud_ind ON student(sno);

    DESCENDING INDEX:

    The order used by B-tree indexes has been ascending order. You can categorizedata in B-tree index in descending order as well.

    This feature can be useful in applications where sorting operations are required.

    *INDEXES are Stored in USER_INDEXES.

    Global Temporary Table:

    Once Transactions are commit, table will be deleted.

    Example: CREATE Global Temporary Table g_idAS Select empno, ename, sal, d.deptno, d.dname from emp e,dept d Where e.deptno=d.deptno.

    *No data is there in this table.

    INSERT into g_id(select empno,ename,sal,d.d.deptno,d.dname from emp e,dept d Where e.deptnpo=d,deptno);

    SELECT *FROM g_id;

    Output: 14 records wil l display.

    Commit;(When we say commit the transactions will be rollback)

    SELECT *FROM g_id;

    Output: No rows selected, because the will be rollback from the table.Difference between UNIQUE and UNIQUE INDEX:

    Two data base objects are created at the time of UNIQUE (they are UNIQUE andDEFAULT INDEX) At the time of UNIQUE INDEX Only one database will be created. UNIQUE will give the REFERENCE to the other table, where as UNIQUE INDEX

    cannot give any reference.

  • 7/25/2019 SQL_SAS NOTES.pdf

    22/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    User _constraints and User _indexes will store the INDEXES. DEFAULT indexes are available in USER_INDEXES and

    USER_CONSTRAINTS. But USER INDEXES are not available in USER_CONSTRAINTS.

    To see INDEXES on a Table

    DESC USER_INDEXES;

    TYPES OF FUNCTIONS:

    1. SINGLE ROW FUNCTIONS2. GROUP FUNCTIONS

    SINGLE ROW FUNCTIONS:

    They are used to manipulate data items. They accept one or more arguments and return one value for each row returned By the query.

    The argument can be: User-supplied constant. Variable value. Column name Expression

    Syntax: FUNCTION_NAME(column/Expr,Argument1,Argument2)

    Features of Single-row Functions:

    Acting on each row returned in the query. Returning one result per row Can be used in SELECT, WHERE and ORDER BY Clause. Can be nested.

    Row Types of Single functions:

    1. String/Character functions

  • 7/25/2019 SQL_SAS NOTES.pdf

    23/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    2. Numeric functions

    3. Date functions

    4. Miscellaneous functions

    5. Conversion functions

    String/Character functions:

    Accept character input and can return both character and number values.

    UPPER:

    This will convert the string into uppercase.

    Syntax: upper (string)

    Example: Select upper('computer') from dual;

    UPPER-----------COMPUTER

    LOWER:

    This will convert the string into lowercase.

    Syntax: lower (string)

    Ex: Select lower(GOLDENGATE);Output: goldengate.

    CONCAT:

    It concatenates the first character value to the second character value. Only two parameters are accept. It returns the character data type.

    Syntax : CONCAT(COLUMN1/EXPRESSION1,COLUMN2/EXPRESSION2);

    Example: Select CONCAT(golden, gate) from Dual;

    OUTPUT: goldengate

  • 7/25/2019 SQL_SAS NOTES.pdf

    24/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Example: Select concat(concat(ename,job),sal) from EMP;

    Note: The concatenation symbol is ||. This symbol is used to concat the morethan one strings or expressions.

    Example: Select 'i' || ' am' || ' coming' from dual;

    OUTPUT: iamcoming

    LENGTH:

    We can find the LENGTH of the String or expression, we may use column namesalso in this function.

    Syntax: length (string/expression)

    Example: Select length('goldengate') from dual;

    OUTPUT: 10

    Example: Select Length(golden gate) fom dual.

    OUTPUT: 11

    * spaces in the string also treated as one character, but string should be in singleQuotes .

    Example: Select Length(ename) from EMP

    It gives the length of each employee name of EMP table.

    RPAD:

    This will allows you to pad/add the right side of a column/expression with any set ofcharacters.

    Syntax: rpad (string, length [padding _char])

    Example: Select rpad('goldengate',15,'*'), rpad('golden',15,'*#') from dual;

  • 7/25/2019 SQL_SAS NOTES.pdf

    25/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    OUTPUT: goldengate***** golden#########

    When adding the character to given string it inc ludes the no. of characterspresent in the string

    Default padding character was blank space.

    LPAD:

    This will allows you to pad/add the left side of a column with any set of characters.

    Syntax : lpad(string,length,[adding character]);

    Example: select lpad(goldengate,20, %) from dual;

    OUTPUT: %%%%%%%%%%goldengate

    Example: Select Lpad(ename,10, $) from EMP;

    OUTPUT: $$$$$smith $$$$$$john $$$$$$king

    All 14 rows will be displayed by adding $ on left side of each employee.

    Example: select lpad(sal,12,@) from emp;

    OUTPUT: @@@@@@@@@sal, here sal is taken as str ing.

    LTRIM:

    This will remove/cut off unwanted characters from the left end of string.

    Syntax: ltrim (string [,unwanted _chars]);

    Example: Select ltrim('goldengate, golden') from dual;

    OUTPUT: gateIf you havent specified any unwanted characters it will display entire string.

    RTRIM:

    It will remove all the right most characters appear in the set.

  • 7/25/2019 SQL_SAS NOTES.pdf

    26/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Syntax: RTRIM (char, set);

    Example: Select Rtrim(goldengateabab, ab) from dual;

    OUTPUT: goldengate.

    Example: Select RTrim(job,er) from EMP;

    TRIM: It removes the characters from both (left, right) sides. If we specify Leading concentrates on leading characters.

    If Trailing is specified it concentrates on trailing characters.If both or none is specified concentrates on both leading and trailing.Returns the varchar2 type

    Example: Select Trim (d from goldendd) from dual;

    Select Trim (Leading s from ssmithss) from dual;

    Select trim(Trailing s from ssmithss) from dual;

    Select trim(both s from ssmithss) from dual;

    REPLACE:

    This will replace the set of characters of a string by the given string.If the replacement string is omitted or null, all occurrences of each string are removed.

    Syntax: REPLACE (TEXT, SEARCH_STRING, [REPLACEMENT_STRING]);

    Example: Select Replace(olden, o, go) from dual;

    OUTPUT: golden, here o is Replaced with go

    Example: Select replace(g o l d e n g a t e, ) from dual;

    OUTPUT: goldengate, here we omitted the replacement st ring hence all theSpaces are removed.

    TRANSLATE:

    This will Replace the string character by character.

  • 7/25/2019 SQL_SAS NOTES.pdf

    27/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Syntax: TRANSLATE (string, old_character, new_character);

    Example: Select Translate(goldengate, ge, xy) from dual;

    OUTPUT: xoldynxaty. Here g is replaced by x, e is replaced by y .

    Example: Select translate(led, l, R) from dual;

    OUTPUT: Red.

    Example: Select translate(ledl, le, Ra) from dual;

    OUTPUT: RedR

    ASCII:

    This will return the decimal representation in the database character set of the firstcharacter of the string

    Syntax:ASCII (string)

    Example: Select ASCII(a) from dual;

    OUTPUT: 97.

    Example: Select ASCII(Ward) from dual;

    OUTPUT: 87.

    If we pass more than one character only one character is passed.

    CHR:

    This will return the character having the binary equivalent to the string in either theDatabase character set or the national character set.

    Syntax: CHR(number)

    Example: Select CHR(65) from dual;

    OUTPUT: A

  • 7/25/2019 SQL_SAS NOTES.pdf

    28/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    SOUNDEX:

    This will be used to find words that sound like other words, exclusively used inwhere clause.

    Syntax: soundex (string)Example: Select *from Emp where soundex(ename)=soundex(smith);

    SUBSTR:

    This will be used to extract substrings.

    Syntax: SUBSTR (String, starting _position(m),no_of_characters(n))

    If m is 0, it is t reated as 1.If m is posi tive, Oracle counts from beginning of character to find the firstcharacter.If n is omitted, returns all characters to the end of character.If n is less than 1 or 0, a null is returned and floating points passed automaticallyconverted to integers.

    Example: Select substr(goldengate,1,4) from dual;

    OUTPUT: gold

    Example: Select substr(goldengate,3,6) from dual;

    OUTPUT: ldenga

    Example: Select substr(goldengate,-4,3) from dual;

    OUTPUT: gat

    INSTR:

    It returns the numeric position of a named character.

    Syntax: INSTR (Column/Expression, character, [M], [N])

    It searches for a character in a string/column from its Mth character and Nthnumber of occurrence it displays the position of character.

  • 7/25/2019 SQL_SAS NOTES.pdf

    29/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    M can be positive or negative, if negative it searches backward from the end ofcolumn/expression.

    The value of N should be positive. The default value of both M and N are 1. If search is unsuccessful, the return value is zero.

    Example:

    Select instr('goldengate','g',1,2) from dual;

    INSTR ('GOLDENGATE','G', 1, 2)--------------------------- 7Select instr('goldengate','g',2,2) from dual;

    INSTR ('GOLDENGATE','G', 2,2)

    --------------------------- 0Select instr('goldengate','g',-1,2) from dual;

    INSTR ('GOLDENGATE','G',-1, 2)---------------------------- 1INITCAP:

    It returns a string with the first letter of each word in upper case, keeping all otherin lower case.

    Example:

    select initcap('golden gate') from dual;

    INITCAP('GOLDEN GATE)-----------Golden Gate

    SELECT upper('goldengate'), lower('GOLDENGATE'), initcap('golden gate') from dual;

    UPPER ('GOL LOWER('GOL INITCAP('GO---------- ---------- -----------GOLDENGATE goldengate Golden Gate

    DECODE:

  • 7/25/2019 SQL_SAS NOTES.pdf

    30/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Decode will act as value by value substitution. For every value of field, it checksfor a match in a series of if/then tests.

    Syntax: decode (value, if1, then1, if2, then2 , . else);

    If the number of parameters are odd and different then decode will displaynothing.

    If the number of parameters are even and different then decode will display lastvalue.

    If all the parameters are null then decode will display nothing.

    If all the parameters are zeros then decode will display zero

    Examples:SQL> select decode(1,1,3,2,2,5) from dual;

    DECODE (1,1,3,2,2,5)------------------- 3

    SQL> select decode(2,2,5,1,1,3) from dual;

    DECODE(2,2,5,1,1,3)------------------- 5

    SQL> select decode(2,3,5,5) from dual;

    DECODE(2,3,5,5)--------------- 5

    SQL> select decode(2,3,5) from dual;

    DECODE(2,3,5)-------------

    SQL> select decode(3,4,5,6,7,4) from dual;

    DECODE(3,4,5,6,7,4)-------------------

  • 7/25/2019 SQL_SAS NOTES.pdf

    31/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    4

    SQL> select decode(3,4,5,6,7) from dual;

    DECODE(3,4,5,6,7)

    -----------------

    SQL> select decode(1,1,2,2,3,3,3,3,5) from dual;

    DECODE(1,1,2,2,3,3,3,3,5)-------------------------

    GREATEST:

    This will give the greatest string, number from the given strings, numbers.

    Syntax: greatest (strng1number1, string2/number2, string3/number3 stringn)

    Example:

    Select greatest (10, 20, 12, 30) from dual;

    GREATEST (10, 20, 12, 30)--------------------- 30

    SQL> select greatest (12, 35, 23, 32) from dual;

    GREATEST (12, 35, 23, 32)--------------------- 35

    SQL> select greatest ('golden','hyderabad','india') from dual;

    GREAT-----india

    SQL> select greatest ('golden, gate') from dual;

    GREATE

  • 7/25/2019 SQL_SAS NOTES.pdf

    32/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    ------golden

    SQL> select greatest ('gate, golden') from dual;

    GREATE------Golden

    If any of the parameters is null it will display nothing.

    LEAST:

    This will give the least string/number.Syntax: LEAST (strng1/number1, string2/number2, string3/number3 stringn)

    Example:SQL> select least('smith','john','scott') from dual;LEAST----John

    SQL> select least (121,111,123,321,234,431,102) from dual;LEAST (121,111,123,321,234,431,102)---------------------------------- 102COALESCE:

    This will give the first non-null string/expression.

    Syntax: coalesce (strng1, string2, string3 stringn);

    Example:

    SQL> select coalesce('ab','xy','rt'),coalesce('','as','xy') from dual;

    COALESCE COALESCE-- -- -------

    ab as

    SQL> select coalesce(100,null,120),coalesce(null,100,120),coalesce(null,'aw','fh') fromdual;

  • 7/25/2019 SQL_SAS NOTES.pdf

    33/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    COALESCE (100,NULL,120)COALESCE (NULL,100,120)COALESCE(NULL,AW,FH)---------------------- -------- ----- ---------------------------- ------------------------------------ 100 100 aw

    NUMBER FUNTIONS:

    These functions accept number input and return numeric values.Many functions that return values that are accurate to 38 decimal digits.

    ROUND FUNCTION:

    Syntax: ROUND (m,n)

    It returns m round to n places right of the decimal point. If n is omitted n is rounded to 0,places.

    If n is negative round of the digits left of the decimal point. n must be an integer.

    Example:

    select ROUND (123.34,1) from dual;

    ROUND (123.34,1)--------------- 123.3select round (-122.236,2) from dual;

    ROUND (-122.236,2)----------------- -122.24Select round(345.37,1) from dual;

    ROUND (345.37,1)--------------- 345.4

    select round (237.385,-2) from dual;

    ROUND(237.385,-2)----------------- 200

    TRUNC:

  • 7/25/2019 SQL_SAS NOTES.pdf

    34/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    This will truncate digits of precision from a number.

    Syntax: TRUNC (VALUE, PRECISION)

    Example:

    SLECT TRUNC (123.23, 2) FROM DUAL;TRUNC (123.23, 2)--------------- 123.23

    Select trunc(113.343,2) from dual;TRUNC (113.343,2)---------------- 113.34

    Select trunc(3234.22341,3) from dual;

    TRUNC (3234.22341,3)------------------- 3234.223Select trunc (-324.3456,2) from dual;

    TRUNC (-324.3456,2)------------------ -324.34

    Select trunc(-345.3456,-2) from dual;

    TRUNC (-345.3456,-2)------------------- -300

    ABS:

    Absolute value is the measure of the magnitude of value. Absolute value is always a positive number.

    Syntax: abs (value)

    Example:

    Select abs(5),abs(-6),abs(0),abs(-7.34) from dual;

  • 7/25/2019 SQL_SAS NOTES.pdf

    35/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    ABS (5) ABS (-6) ABS (0) ABS (-7.34) ---------- ---------- ---------- --- ------- 5 6 0 7.34

    SIGN:

    Sign gives the sign of a value.

    Syntax: sign (value)

    Example:

    Select sign (-5), sign (6), sign (0), sign (null) from dual;

    SIGN (-5) SIGN (6) SIGN (0) SIGN (NULL)

    ---------- ---------- ---------- ---------- -1 1 0

    SQRT:

    This will give the square root of the given value.Syntax: sqr t (value)

    Here value must be positive.

    Example:Select sqrt(4),sqrt(12),sqrt(16),sqrt(28) from dual;

    SQRT(4) SQRT(12) SQRT(16) SQRT(28)---------- ---------- ---------- ----------

    2 3.46410162 4 5.29150262Select sqrt(1),sqrt(null),sqrt(0) from dual;

    SQRT(1) SQRT(NULL) SQRT(0)---------- ---------- ---------- 1 0

    MODThis will give the remainder.

    Syntax: mod (value, divisor)

    Ex: select mod(7,4), mod(1,5), mod(null,null), mod(0,0), mod(-7,4) from dual;

  • 7/25/2019 SQL_SAS NOTES.pdf

    36/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    MOD(7,4) MOD(1,5) MOD(NULL,NULL) MOD(0,0) MOD(-7,4)------------ ---------- --------------------- ----------- -------------3 1 0 -3

    NVL

    This will substitutes the specified value in the place of null values.This is used to convert a NULL value to an actual value.

    Syntax: nvl (null _col/exp1, replacement _value/exp2)

    Exp1: Is the source value or expression that may contain NULL.Exp2: is the target value for converting NULL.

    Select nvl(100,200) from dual;

    NVL (100,200)------------

    100Select nvl(null,100) from dual;

    NVL (NULL, 100)------------- 100Select 1000+null from dual;

    1000+NULL----------Select 1000+nvl (null, 0) from dual;

    1000+NVL (NULL, 0)---------------- 1000POWER

    Power is the ability to raise a value to a given exponent.Syntax: power (value, exponent)

    select power(2,5),power(-2,3),power(0,0),power(1,1) from dual;POWER (2,5) POWER(-2,3) POWER(0,0) POWER(1,1)---------- ----------- ---------- ---------- 32 -8 1 1

    EXPThis will raise e value to the give power.

  • 7/25/2019 SQL_SAS NOTES.pdf

    37/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Syntax: exp (value)

    Select exp (0), exp (1), exp (-1), exp (5) from dual;

    EXP (0) EXP (1) EXP (-1) EXP (5)

    ---------- ---------- ---------- ---------- 1 2.71828183 367879441 148.413159

    LNThis is based on natural or base e logarithm.

    Syntax: ln (value)

    Here value must be greater than zero which is positive only.

    Select ln(2),ln(5) from dual;

    LN(2) LN(5) ---------- ---------- .693147181 1.60943791

    Select ln(0) from dual;Error Argument '0' is out of range

    LOGThis is based on 10 based logarithm.

    Syntax: log (10, value) -- here value must be greater than zero which is positive only.Select log(10,100), log(10,2), log(10,1), log(10,null) from dual;

    LOG(10,100) LOG(10,2) LOG(10,1) LOG(10,NULL) ----------- ---------- ---------- ------------ 2 .301029996 0CEIL

    This will produce a whole number that is greater than or equal to the specifiedvalue.

    Syntax: ceil (value)

    Select ceil(5), ceil(5.1), ceil(-5), ceil( -5.1), ceil(0), ceil(null) from dual;

    CEIL(5) CEIL(5.1) CEIL(-5) CEIL(-5.1) CEIL(0) CEIL(NULL)

  • 7/25/2019 SQL_SAS NOTES.pdf

    38/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    --------- ----------- ---------- ------------ -------- --------------5 6 -5 -5 0

    FLOOR

    This will produce a whole number that is less than or equal to the specified value.Syntax: floor (value)

    Select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0), floor(null) from dual;

    FLOOR(5) FLOOR(5.1) FLOOR(-5) FLOOR(-5.1) FLOOR(0) FLOOR(NULL)----------- ------------- ------------ -------------- ----------- ----------------

    5 5 -5 -6 0

    BITANDThis will perform bitwise and operation.

    Syntax: bitand (value1, value2)

    select bitand(2,3), bitand(0,0), bitand(1,1), bitand(null,null), bitand(-2,-3) from dual;

    BITAND(2,3) BITAND(0,0) BITAND(1,1) BITAND(NULL,NULL) BITAND(-2,-3) ----------- ----------- ----------- ----------------- ------------- 2 0 1 -4GREATEST

    This will give the greatest number.

    Syntax: greatest (value1, value2, value3 valuen)

    Select greatest (1, 2, 3), greatest (-1, -2, -3) from dual;

    GREATEST (1, 2, 3) GREATEST (-1,-2,-3)-------------------- -----------------------

    3 -1 If all the values are zeros then it will display zero.

    If all the parameters are nulls then it will display nothing.

    If any of the parameters is null it will display nothing.

    LEASTThis will give the least number.

    Syntax: least (value1, value2, value3 valuen)

  • 7/25/2019 SQL_SAS NOTES.pdf

    39/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Select least (1, 2, 3), least (-1, -2, -3) from dual;

    LEAST (1, 2, 3) LEAST (-1,-2,-3)-------------------- -----------------------

    1 -3

    If all the values are zeros then it will display zero.

    If all the parameters are nulls then it will display nothing.

    If any of the parameters is null it will display nothing.

    COALESCEThis will return the first not null value.

    Syntax: coalesce (value1, value2, value3 valuen)

    Select coalesce(1,2,3), coalesce(null,2,null,5) from dual;

    COALESCE(1,2,3) COALESCE(NULL,2,NULL,5)--------------- -----------------------

    1 2

    DATE FUNCTIONS:

    Oracle stores the dates in an internal numeric format. The default display and input format for any date is DD-MON-YY. We can change the default format to our desired format by using the following

    command.

    Alter session set nls_date_format = DD-MONTH-YYYY ;

    But this will expire once the session was closed.

    SYSDATE:

    It is a date function that returns current date and time.

    Select SYSDATE from dual;

    Date arithmetic:

  • 7/25/2019 SQL_SAS NOTES.pdf

    40/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    As database stores dates as numbers, it allows to perform calculations using arithmeticoperators.

    We can perform the following operations..

    Date + number date adds a number of days to a date. Date Number Date subtracts the number of days from date. Date + Number/24 adds a number of hours to date

    Example:Select sysdate from dual;

    Select Sysdate, Sysdate+48/24 from dual;

    CURRENT_DATE

    This will returns the current date in the sessions timezone.

    select current_date from dual;

    CURRENT_DATE------------------

    25-NOV-11

    CURRENT_TIMESTAMP

    This will returns the current timestamp with the active time zone information.

    Select current_timestamp from dual;

    CURRENT_TIMESTAMP------------------------------------------------------25-NOV-11 03.42.41.383369 AM +05:30

    SYSTIMESTAMP

    This will returns the system date, including fractional seconds and time zone of thedatabase.

    Select systimestamp from dual;

    SYSTIMESTAMP------------------------------------------------------

  • 7/25/2019 SQL_SAS NOTES.pdf

    41/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    25-NOV-11 03.49.31.830099 AM +05:30

    LOCALTIMESTAMP

    This will returns local timestamp in the active time zone information, with no time

    zone information shown.

    Select localtimestamp from dual;

    LOCALTIMESTAMP--------------------------------------------25-NOV-11 03.44.18.502874 AM

    DBTIMEZONE

    This will returns the current database time zone in UTC format. (Coordinated Universal

    Time)

    Select dbtimezone from dual;

    DBTIMEZONE----------------07:00

    SESSIONTIMEZONE

    This will return the value of the current sessions time zone .

    Select sessiontimezone from dual;

    SESSIONTIMEZONE------------------------------+05:30

    MONTHS_BETWEEN FUNCTION:

    Syntax: Months _between (D1,D2)

    It gives the difference between D1 and D2 in number of months.

    If D1 is later than D2, the result is positive, else negative.

    Select months_between(sysdate,'25-DEC-04') from dual;

  • 7/25/2019 SQL_SAS NOTES.pdf

    42/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    MONTHS_BETWEEN(SYSDATE,'25-DEC-04')----------------------------------- 83Select months_between('22-DEC-2010',sysdate) from dual;

    MONTHS_BETWEEN('22-DEC-2010',SYSDATE)------------------------------------- -11.128056

    NEXT DAY FUNTION:

    Syntax: Next_day(D,Char)

    It returns the date of the first week day named by char, that is later than the data D.

    select next_day(sysdate,'wed') from dual;

    NEXT_DAY(---------30-NOV-11

    select next_day(sysdate,'sat') from dual;

    NEXT_DAY---------26-NOV-11

    LAST DAY FUNCTION:

    Syntax: last _day (D)

    It returns the date of the last day of the month that contains D.Mostly is used to determine how many days are left in the current month.

    Select last_day(sysdate), last_day(sysdate)-sysdate daysleft from dual;

    LAST_DAY DAYSLEFT--------- ------- ---30-NOV-11 5

  • 7/25/2019 SQL_SAS NOTES.pdf

    43/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    ROUNDING OF DATES:

    Syntax: Round (date, format)

    Returns date rounded to the unit specified by the format.

    If format is omitted, date is rounded to the nearest day.

    select round(sysdate,'month') from dual;

    ROUND (SYSDATE.---------01-DEC-11

    TRUNCATING DATES:

    Syntax: Trunc(Date, format)

    Returns date with the time portion of the day truncated to the specified unit.

    Select round (sysdate,'DAY'),Trunc(sysdate,'DAY') from dual;

    ROUND (SYS TRUNC (SYS--------- ---------27-NOV-11 20-NOV-11

    Select round (sysdate,'MONTH'),trunc(sysdate,'MONTH') from dual;

    ROUND (SYS TRUNC(SYS--------- ---------01-DEC-11 01-NOV-11

    CONVERSION FUNCTION:

    The conversion functions convert a value from one data type to another.

    Conversion in Oracle is two types.

    Implicit conversion.

    It works according to the convention specified by the Oracle.

  • 7/25/2019 SQL_SAS NOTES.pdf

    44/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    CHAR to NUMBER conversion succeed only if the character string represents a validNUMBER.CHAR to DATES conversion succeed only if the character string represents the defaultformat of DD-MON-YY.

    Explicit conversion.

    SQL provided three conversion functions to convert one data type to another.The explicit conversion functions are

    TO_ CHAR To Character function.TO_DATE To Date conversionTO_NUMBER To Number conversion.

    TO_CHAR Conversion:This function is used in two ways.

    1. TO_CHAR (Number Conversion)

    2. TO_CHAR (Date Conversion)

    TO_CHAR(Number Conversion):

    1 . Decimal Indicator: D99D99

    It returns the specified position of the decimal character.The default decimal delimiter is period.

    SQL> select 1234,to_char(1234,'9999D99') from dual;

    1234 TO_CHAR(---------- -------- 1234 1234.00SQL> select 127864,to_char(127864,'9999D99') from dual;

    127864 TO_CHAR(

    ---------- -------- 127864 ########

  • 7/25/2019 SQL_SAS NOTES.pdf

    45/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    SQL> select 12345,to_char(12345,'99999D99') from dual;

    12345 TO_CHAR(1---------- --------- 12345 123450

    2. SCIENTIFIC NOTATION INDICATOR: EEEE9.9EEEE

    Returns the numeric value using scientific notation.

    SQL> select to_char(3247,'9.9EEEE') from dual;

    TO_CHAR(3--------- 3.2E+03

    3 . GROUP SEPARATOR: G9G9999

    Returns the specified position of the group separator. Multiple group separators can be specified.

    SQL> select to_char(123987,'9G9999G99') from dual;

    TO_CHAR(12----------

    1239,87

    SQL> select to_char(3426354,'99G99G999') from dual;

    TO_CHAR(34----------34,26,354

    LOCAL CURRANCY INDICATOR : L L999 or 999L

    It returns the specified position of the local currency symbol.

    SQL> select to_char(1234,'L9999') from dual;

    TO_CHAR (1234,'L---------------

  • 7/25/2019 SQL_SAS NOTES.pdf

    46/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    $1234

    SQL> select to_char(23765,'L99G999D99', 'NLS_CURRENCY=IndRupees') from dual;

    TO_CHAR (23765,'L99G9

    -------------------- IndRupees 23, 765.00

    TRAILING MINUS INDICATOR: MI9999MI

    It returns negative value with a trailing minus sign -. Returns positive value with a trailing blank.

    SQL> select -10000, to_char(-10000,'L99g999d99MI') from dual;

    -10000 TO_CHAR (-10000,'L99G ---------- -------------------- -10000 $10,000.00-

    SQL> select 12000, to_char(120000,'9g99g999d99MI','NLS_CURRENCY=IndRupees')from dual;

    12000 TO_CHAR (1200 ---------- ------------ 12000 1, 20,000.00

    NEGATIVE NUMBER INDICATOR: PR

    9999PR

    Returns negative number in . It can appear only as trailing declaration.

    SQL> select to_char(-10000,'L99g999d99pr') from dual;

    TO_CHAR(-10000,'L99G9---------------------

    SQL> select to_char(12000,'L99g999d99pr') from dual;

    TO_CHAR(12000,'L99G99---------------------

  • 7/25/2019 SQL_SAS NOTES.pdf

    47/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    $12,000.00ROMAN NEGATIVE INDICATOR:

    RNreturns upper roman numberrn returns lower roman number.

    The value can be an integer between 1 and 3999.

    SQL> select 12,to_char(12,'RN'),to_char(12,'rn') from dual;

    12 TO_CHAR (12,'RN' TO_CHAR(12,'RN' ---------- --------------- --------------- 12 XII xii

    HEXADECIMAL INDICATOR: XXXXX

    Returns the Hexadecimal value of the specified number of digits. If number is not an integer, Oracle rounds it to an integer. Accepts only positive or 0.

    SQL> select 2000, to_char (2000,'xxxx') from dual;

    2000 TO_CH ---------- ----- 2000 7d0

    GROUP SEPARATOR: 9,999

    Returns a comma in the specified position. Multiple commas can be specified.

    SQL> select 20000,to_char(20000,'99,999.99') from dual;

    20000 TO_CHAR (20---------- ----------

    20000 20,000.00

    DOLLAR INDICATOR:

    Returns value with a leading dollar sign.

  • 7/25/2019 SQL_SAS NOTES.pdf

    48/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    SQL> select 200000,to_char(200000,'$9,99,999.99') from dual;

    200000 TO_CHAR (20000---------- -------------

    200000 $2, 00,000.00

    ZERO INDICATORS:

    Returns lading OR trailing Zeros.

    SQL> select 10000,to_char(10000,'09999999'), to_char(10000,'0999990') from dual;

    10000 TO_CHAR(1 TO_CHAR(---------- --------- -------- 10000 00010000 0010000

    ISO CURRENCY INDICATOR: CC9999

    Returns specified position of the ISO currency symbol.

    SQL> select 8000,to_char(8000,'C9999.99') from dual;

    8000 TO_CHAR(8000,'C ---------- --------------- 8000 USD8000.00

    Date format Models:

    The date format models can be used in the TO_CHAR function too translate a DATEvalue from original format to use format.

    DATE FORMATSD -- No of days in weekDD -- No of days in monthDDD -- No of days in yearMM -- No of monthMON -- Three letter abbreviation of monthMONTH -- Fully spelled out monthRM -- Roman numeral monthDY -- Three letter abbreviated dayDAY -- Fully spelled out dayY -- Last one digit of the year

  • 7/25/2019 SQL_SAS NOTES.pdf

    49/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    YY -- Last two digits of the yearYYY -- Last three digits of the yearYYYY -- Full four digit yearSYYYY -- Signed yearI -- One digit year from ISO standard

    IY -- Two digit year from ISO standardIYY -- Three digit year from ISO standardIYYY -- Four digit year from ISO standardY, YYY -- Year with commaYEAR -- Fully spelled out yearCC -- CenturyQ -- No of quartersW -- No of weeks in monthWW -- No of weeks in yearIW -- No of weeks in year from ISO standardHH -- Hours

    MI -- MinutesSS -- SecondsFF -- Fractional seconds

    AM or PM -- Displays AM or PM depending upon time of dayA.M or P.M -- Displays A.M or P.M depending upon time of dayAD or BC -- Displays AD or BC depending upon the dateA.D or B.C -- Displays AD or BC depending upon the dateFM -- Prefix to month or day, suppresses padding of month or dayTH -- Suffix to a numberSP -- suffix to a number to be spelled outSPTH -- Suffix combination of TH and SP to be both spelled out

    SQL> select to_char(sysdate,'dd month yyyy hh:mi:ss am dy') from dual;

    TO_CHAR(SYSDATE,'DD MONTH YYYYHH:MI----------------------------------------------------24 december 2006 02:03:23 pm sun

    SQL> select to_char(sysdate,'dd month year') from dual;TO_CHAR(SYSDATE,'DDMONTHYEAR')-------------------------------------------------------24 december two thousand six

    SQL> select to_char(sysdate,'dd fmmonth year') from dual;

  • 7/25/2019 SQL_SAS NOTES.pdf

    50/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    TO_CHAR(SYSDATE,'DD FMMONTH YEAR')-------------------------------------------------------24 december two thousand six

    SQL> select to_char(sysdate,'ddth DDTH') from dual;

    TO_CHAR(S------------24th 24TH

    SQL> select to_char(sysdate,'ddspth DDSPTH') from dual;

    TO_CHAR(SYSDATE,'DDSPTHDDSPTH------------------------------------------twenty-fourth TWENTY-FOURTH

    SQL> select to_char(sysdate,'ddsp Ddsp DDSP ') from dual;

    TO_CHAR(SYSDATE,'DDSPDDSPDDSP')------------------------------------------------twenty-four Twenty-Four TWENTY-FOUR

    TO_DATE

    This will be used to convert the string into data format.

    Syntax: to_date (date)

    select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month * day') from dual;

    TO_CHAR(TO_DATE('24/DEC/20--------------------------24 * december * Sunday

    SQL> select to_char(sysdate,'i') from dual;

    T-1

    SQL> select to_char(sysdate,'ww') from dual;

  • 7/25/2019 SQL_SAS NOTES.pdf

    51/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    TO--48

    AGGREGATE/GROUP FUNCTIONS:

    Group functions operate on set of rows to give one result per each group.Group functions can appear in select lists and in ORDER BY and HAVING clauses.

    Syntax: group_function(distinct/all column);

    Rules:

    The data types for the arguments can be CHAR, VARCHAR2, NUMBER, or DATE.All group functions ignore null values except COUNT (*).

    Average function:

    It returns the average value of column.It ignores NULL values.

    Syntax: avg(distinct/all column)

    select avg(sal), avg(DISTICT sal) from employees;

    Sum Function:

    It returns the SUM value of column.

    Syntax: sum(distinct/all Column)

    Select SUM(comm.), SUM(distinct comm) from employees;

    Maximum Function:

    It returns the maximum value of column

    Syntax: max(distinct/all column)

    Select max(sal) from employees;

    Minimum Function:

    It returns the minimum value of column.

  • 7/25/2019 SQL_SAS NOTES.pdf

    52/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Syntax : min(distinct/all Column)

    Select min(sal) from employees;

    Count Function:

    It gives the no of rows in the Query.If * used to returns all rows, it includes duplicated and NULLs.

    Syntax: Count (distinct/all column)

    Select count (employee _name) from employees;Select count (*) from employees;

    MISCELLANEOUS FUNCTIONS:

    UID:This will returns the integer value corresponding to the user currently logged in.

    select uid from dual;

    UID----------319

    USER:This will returns the logins user name.select user from dual;

    USER----------------scott

    VSIZE:This will returns the number of bytes in the expression.

    Select vsize(123), vsize('computer'), vsize('12-jan-90') from dual;

    VSIZE(123) VSIZE('COMPUTER') VSIZE('12-JAN-90')------------- ----------------------- ----------------------

    3 8 9

  • 7/25/2019 SQL_SAS NOTES.pdf

    53/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    RANK:This will give the non-sequential ranking.

    Select rownum,sal from (select sal from emp order by sal desc);

    ROWNUM SAL---------- ----------1 50002 30003 30004 29755 28506 2450

    select rank(2975) within group(order by sal desc) from emp;

    RANK(2975)WITHINGROUP(ORDERBYSALDESC)---------------------------------------------------------4

    DENSE_RANK:

    This will give the sequential ranking.

    select dense_rank(2975) within group(order by sal desc) from emp;

    DENSE_RANK(2975)WITHINGROUP(ORDERBYSALDESC)-----------------------------------------------------------------

    3

    OPERATORS:

    Arithmetic Operators:

    Arithmetic operators can be used to create expressions on NUMBER and DATE data.

    Arithmetic operators are +, - , *, /.Operator precedence *, /, +, -

    Arithmetic operators can be used in any clause of SQL statements, except the FROMclause.

    Select empno, ename, sal,sal+500 from employees;

  • 7/25/2019 SQL_SAS NOTES.pdf

    54/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    HANDLING NULL VALUES:

    Null value is unknown value, undefined value. Not equal to 0 or blank space. It represented with null keyword.

    No operations allowed on null,(if performed any arithmetic operations it returnsnull only)

    Select 1000+null from dual;

    1000+NULL ----------

    Select 2500*null from dual;

    2500+NULL

    -------------

    NVL FUNCTION:

    Syntax: NVL (Exp1, Exp2)

    Exp1 is source value or expression that may contain NULL.

    Exp2 is target value for converting NULL.

    Data type of Expression1 and Expression should be same.

    SQL> select 1000+nvl(null,0) from dual;

    1000+NVL(NULL,0) ---------------- 1000

    SQL> select nvl(100,null) from dual;

    NVL(100,NULL)------------- 100

    SQL> select nvl(null,100) from dual;

  • 7/25/2019 SQL_SAS NOTES.pdf

    55/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    NVL(NULL,100)------------- 100

    NVL2 FUNCTION:

    Syntax : NVL2(exp1,exp2,exp3)

    If exp1 is NOT NULL, NVL2 returns exp2. If exp1 is NULL, NVL2 returns exp3. Exp1 may any data type. The data type of return value is always same as the data type of exp2, unless

    exp2 is Character data type.

    SQL> select nvl2(null,0,1000) from dual;

    NVL2(NULL,0,1000)----------------- 1000

    SQL> select nvl2(100,250,300) from dual;

    NVL2(100,250,300)----------------- 250

    SQL> select nvl2(null,200,null) from dual;

    NVL2(NULL,200,NULL)-------------------

    NULLIF FUNCTION:

    Syntax: NULLIF (exp1, exp2)

    Compares two expressions and returns null if they are equal. Returns first if they are not equal.

    select nullif(100,200) from dual;NULLIF(100,200)---------------

  • 7/25/2019 SQL_SAS NOTES.pdf

    56/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    100SQL> select nullif(300,300) from dual;NULLIF(300,300)---------------

    SQL> select nullif('smith','smith') from dual;NULLI-----

    SQL> select nullif('smith','john') from dual;NULLI-----Smith

    Relational or Comparison operators:

    , =,! = these three are not equal operators.>, >=

  • 7/25/2019 SQL_SAS NOTES.pdf

    57/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    It returns TRUE if either of component conditions are TRUE. It returns FALSE if both are FALSE, else returns unknown.

    Select ename,job,sal from emp where sal>=2000 OR deptno=20;

    NOT Operator:

    It returns TRUE if following condition is FALSE. It returns FALSE if following condition is TRUE. If the condition is unknown, it returns unknown.

    Select empno,ename,sal from emp where NOT empno=7788;

    The default precedence order is

    ALL Comparison operatorsNOT Logical condition

    AND Logical condit ionOR Logical condi tion

    SQL OPERATORS:

    BETWEENAND:

    This is used to display the rows based on a range of values.The declared range is inclusive.

    The lower limit should be declared first.

    Select empno, ename, sal from EMP where comm. between 200 and 800;

    IN Operator:

    This operator is used to test for values in a specified list.The operator can be used upon any datatype.

    Select empno,ename,sal from EMP where job in(MANAGER,CLERK);

    Select empno,deptno,sal from EMP where deptno in(10,20,30);

    NOT IN:

    Select empno, ename,sal from EMP where deptno NOT IN(20,30);

  • 7/25/2019 SQL_SAS NOTES.pdf

    58/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    LIKE Operator:

    Use the like condition to perform wildcard. The LIKE operator searches of valid search string values.

    Search condition may contain either literal or numbers.

    The available wild cards are

    % it represents any sequence of zero or more characters._ It represents the any single character, only at that posi tion only.

    Select ename,empno from EMP where ename LIKE M%;

    It displays the employee details whose name starts with M

    Select ename,empno,sal from EMP where ename LIKE _O%;

    It displays the employee details who contains O as second letter of names.

    NOT LIKE:

    Select empno,ename,sal from EMP where ename NOT LIKE M%;

    It display the employee details not starting with M.

    IS NULL, IS NOT NULL Operator:

    The operator tests for NULL values. It is only the operator that can be used to test for NULLs

    Select ename,empno,sal from EMP where comm. Is NULL.

    Select ename,empno,deptno where mgr is NOT NULL.

    SET OPERATORS:

    The set operators allow you to combine rows returned by two or more queries

    The number of columns and the column types returned by the queries mustmatch, although the column names may be different.

    All set operators have equal precedence, if a SQL statements contains multipleSET operators, the Oracle server evaluates them from left(top) to right(bottom) ifno parentheses explicitly another order.

  • 7/25/2019 SQL_SAS NOTES.pdf

    59/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    DIFFERENT TYPES OF SET OPERATORS:

    UNION Operator.UNION ALL Operator

    INTERSECT OperatorMINUS Operator.

    Whenever theses operators are used select statement must haveEqual no of columns, similar data type columns Operator Description

    UNION ALL Returns all the rows retrieved by the queries, including duplicate rows.

    UNION Returns all non-duplicate rows retrieved by the queries.

    INTERSECT Returns rows that are common to both queries.

    MINUS Returns the remaining rows when the rows retrieved by the second query are subtracted from the rows retrieved by the first query.Examples:

    1) Select job from EMP where deptno=10; UNION Select job from EMP where deptno=20;

    2) selct deptno,job from EMP where deptno=10; UNION ALL Select deptno,job from EMP where deptno=20;

    3) select job from EMP where Deptno=10;INTERSECT

    Select job from EMP where deptno=20;

    4 ) select job from EMP where deptno=10;MINUS

    S ELECT JOB FROM EMP where deptno=20;

    JOINS:

    When data from more than one table in the database is required, a join conditionis used.

  • 7/25/2019 SQL_SAS NOTES.pdf

    60/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    A join is a query that combines rows from two or more tables, views, ormaterialized views. a join is performed whenever multiple table appear in thequires FROM clause.

    Join Conditions:

    A column in the join condition need not be part of the SELECT list. When writing a SELECT statement that joins tables, precede the column name

    with the table name for clarity and to enhance database access.

    EQUI JOIN or Simple Join:

    Based on equality condition tables are joined. Only matching records are displayed. Joining tables must have at least one common column with same data type and

    same values. ( not column name same).

    Syntax: Select col1,col2,col3. From ,

    Where .=. And..

    Example:

    Select empno,ename,emp.deptno deptno,dname from emp,dept

    Where emp.deptno=dept.deptno;

    Using table aliases:

    Select e.empno, e.ename, d.deptno, d.dname from emp e,dept dWhere e.deptno=d.deptno;

    Non Equi Joins:

    Between operator is used in non equi joins, it called as between join.

    Syntax:Select col1,col2. From ,

    Where . between . and .;

  • 7/25/2019 SQL_SAS NOTES.pdf

    61/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Example:Select e.ename,e.sal,s.grade from emp e.salgrade sWhere e.sal between 1000 and 3000;

    SELF JOIN:

    It indicates joining the table to itself. The same table appears twice in the FROM clause and is followed by table

    aliases. The table aliases must qualify the column names in the join condition. It is used on same table the table must have at least 2 column with same,

    datatype, values

    Syntax:Select columns from table1 t1,table1 t2

    Where t1.column1=t2.column2;

    Example:

    Select e.ename employee name,m.ename manager name from emp e,emp mWhere e.mgr=m.empno;

    OUTER JOIN:

    Is used to retrieve all the rows from one table but matching rows from other table. An outer join extends the result of a simple or inner join. It is use an operator (+), it called join operator. (+) used with table which missing the data.

    Syntax:Select table1.column, table2.column from table1, table2Where table1.column (+) =table2.column;

    Rules:

    (+) operator can appear only in the where clause.(+) used only with one table.

    Example:

  • 7/25/2019 SQL_SAS NOTES.pdf

    62/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    Select e.ename,d.deptno,d.dname from emp e , dept dWhere e.deptno(+)=d.deptno ORDER BY e.deptno;

    Here from emp table only matching record will display, where as in dept table allthe records will display.

    LEFT OUTER JOIN:

    This will display the all the records from the left side table and only matchingrecords from the right side table

    To perform a left outer join, the WHERE clause is,

    WHERE table1.column1 = table2.column2 (+);

    Example:

    Select empno, ename, job, dname, loc from emp e left outer join dept dOn (e.deptno=d.deptno);

    Or

    Select empno, ename, job, dname, loc from emp e,dept d wheree.deptno=d.deptno (+);

    RIGHT OUTER JOIN:

    This will display all the records from right side of the table and only matching

    records from left side of the table. To perform a right outer join, the WHERE clause is,

    WHERE table1.column1(+)= table2.column2;

    Example:

    Select empno, ename, job, dname, loc from emp e right outer join dept dOn (e.deptno=d.deptno);

    OrSelect empno, ename, job, dname, loc from emp e,dept d where

    e.deptno(+)=d.deptno;

    FULL OUTER JOIN:

  • 7/25/2019 SQL_SAS NOTES.pdf

    63/80

    ______________________________________________________________________STANSYS SOFTWARE SOLUTIONS

    #7-1-621/113(67/3RT), Beside: Nagarjuna Jr.College, Near: S.R.Nagar Community Hall,

    S.R.Nagar, Hyd-38|Ph:040-42204449/8143408688|www.stansys.co.in|[email protected]

    This will display the all matching records and the non-matching records from bothtables.

    Note: Full outer join=left outer join + right outer join;

    Example:

    select empno,ename,job,dname,loc from emp e full outer join dept don(e.deptno=d.deptno);

    CROSS JOIN:

    This will return a Cartesian product from the two tables.

    Example: select empno,ename,job,dname,loc from emp cross