You are on page 1of 38

Date Conversion functions

TO_DATE Converts a character field into date field Syntax TO_DATE(char,fmt) Example INSERT INTO EMP VALUES ( Salesman ,1010,Ajay ,32,24000,30, TO_DATE( 25-JUN-2010 , DD-MON-YY )

Date Functions
ADD_MONTHS Returns date after adding the number of months specified in the function Syntax ADD_MONTHS(date ,no of months) Example - SELECT ADD_MONTHS(SYSDATE,4) Add Months FROM DUAL LAST_DAY Returns the last date of the month specified with the function Syntax LAST_DAY(date) Example SELECT SYSDATE, LAST_DAY(SYSDATE) Last Day FROM DUAL

Date Functions Contd.


MONTHS_BETWEEN Returns number of months between d1 and d2 Syntax MONTHS_BETWEEN(date1 ,date2) Example SELECT MONTHS_BETWEEN (SYSDATE, 01-JAN-92 ) Months FROM DUAL NEXT_DAY Returns the date of the first weekday named by char that is after the date named by date. Char must be a day of the week Syntax NEXT_DAY(date , char) Example SELECT NEXT_DAY(SYSDATE, Saturday ) Next Day FROM DUAL

Date Functions Contd.


ROUND Returns a date rounded to a specific unit of measure. If the second parameter is omitted ROUND function will round the date to the nearest day. Syntax ROUND(date, format) Example SELECT ROUND(SYSDATE, YYYY ) Year FROM DUAL

Group By Clause
Another optional clause of SELECT statement that tells Oracle to group rows based on distinct values that exist for specified columns. The GROUP BY clause creates a data set containing several sets of records grouped together based on a condition. Syntax SELECT AGGREGATE_FUNCTION (Expression) FROM TableName WHERE Condition GROUP BY Column1, Column2 ColumnN

Group By Clause Contd.


Example Select Deptno Department Number , SUM(EmpSal) Total Salary Of Each Department FROM EMP GROUP BY Deptno Example - Select Deptno Department Number , SUM(EmpSal) Total Salary Of Each Department And Employee Job FROM EMP GROUP BY Deptno, EmpJob

Having Clause Contd.


Can be used in conjunction with GROUP BY clause. HAVING imposes a condition on GROUP BY clause which further filters the groups created by the GROUP BY clause. Each column specified in the HAVING clause must occur within the function or must occur in the list of columns named in the GROUP BY clause Example SELECT Deptno Department Number , COUNT(Empno) No Of Employees FROM Emp GROUP BY Deptno HAVING Deptno > 10

SUB QUERIES
It is a form of SQL statement that appears inside another SQL statement. It is also termed as nested query. The statement containing a subquery is called a parent statement which uses the rows returned by the subquery It can be used for the following
Insert or Update records in target table Create table and insert records in it Create Views Provide values for conditions in where, having, in and so on used with DML statements

SUB QUERIES Contd


Sub Query Example Select * from Emp where Deptno IN (Select Deptno from Dept whete Dname = Sales ) Nested Sub Query Example Select * from Emp where EmpSal < (Select Max(Empsal) from Emp where EmpSal < (Select Max(EmpSal) from Emp))

JOINS And Its Types


Joins are used to work with multiple tables as if they were like a single entity Tables are joined on columns that have the same data type and data width in the tables The purpose of join is to bind together across tables without repeating all of the data in every table The various types of joins are
INNER JOIN OUTER JOIN
LEFT, RIGHT, FULL

CROSS

TYPES OF JOINS
INNER JOIN Inner Joins are also known as Equi Joins. In this type of join the where statement compares two columns from two tables with equivalence operator =. This type of join is used to return all rows from the tables where there is a match OUTER JOIN They are similar to inner joins but allow to select rows from the tables (left or right or both) regardless whether the other table has values in common and enters NULL where the data is missing CROSS JOIN It returns Cartesian Product that is combines every row from left table with every row from right table. This type of join is used to select all possible combinations of rows and columns from both the tables

Syntax Of Joins
Syntax (ANSI Style) SELECT Column1, Column2, ColumnN FROM Table1 INNER JOIN Table2 ON Table1.Column1= Table2.Column2 WHERE <Condition> ORDER BY Column1, Column2 Syntax (Theta Style) SELECT Column1, Column2, ColumnN FROM Table1, Table2 WHERE Table1.Column1=Table2.Column2 ORDER BY Column1, Column2

Examples Of JOINS
INNER JOIN SELECT E.EmpNo, E.EmpName Name , D.Deptno Department Number FROM Emp E INNER JOIN Dept D ON E.Deptno=D.Deptno INNER JOIN - SELECT E.EmpNo, E.EmpName Name ,D.Deptno Department Number FROM Emp E, Dept D WHERE E.Deptno=D.Deptno CROSS JOIN SELECT E.EmpName, D.Dname FROM Emp E, Dept D LEFT OUTER JOIN SELECT E.EmpNo, E.EmpName, D.DeptNo, D.Dname FROM Emp E LEFT JOIN Dept D ON E.Deptno = D.Deptno LEFT OUTER JOIN SELECT E.EmpNo, E.EmpName, D.DeptNo, D.Dname FROM Emp E, Dept D WHERE E.Deptno = D.Deptno(+)

Examples Of JOINS Contd.


RIGHTT OUTER JOIN SELECT E.EmpNo, E.EmpName, D.DeptNo, D.Dname FROM Emp E RIGHT JOIN Dept D ON E.Deptno = D.Deptno RIGHT OUTER JOIN SELECT E.EmpNo, E.EmpName, D.DeptNo, D.Dname FROM Emp E, Dept D WHERE E.Deptno(+) = D.Deptno FULLOUTER JOIN SELECT E.EmpNo, E.EmpName, D.DeptNo, D.Dname FROM Emp E FULL JOIN Dept D ON E.Deptno = D.Deptno FULL OUTER JOIN SELECT E.EmpNo, E.EmpName, D.DeptNo, D.Dname FROM Emp E, Dept D WHERE E.Deptno(+) = D.Deptno(+)

Constraints and Its Types


Business rules which are enforced on the data being stored in the table are called Constraints Constraints super control the data being entered into the table for permanent storage Oracle permits constraints to be attached to the columns via CREATE TABLE or ALTER TABLE statement. Once a constraint is attached with the data column and if the data value is entered the database engine checks if the is valid or not if the data is valid it is stored in the table else rejected Even if single column fails to pass the constraint the entire record is rejected

Types Of Constraints
PRIMARY KEY Constraint A primary key is one or more columns in a table used to uniquely identify each row in a table. A table can have only one primary key and it is unique and not null A single column primary key is called as Simple Key and a multiple column primary key is called as Composite Key Features Of Primary Key
Record Uniqueness Not Allow Null and duplicate values Not compulsory but recommended Relates tables with one another Only one primary key per table Unique Index automatically created Composite primary key can contain up to 16 columns

Primary Key Created At Column And Table Level


CREATE TABLE EMP (EMPNO NUMBER(2) PRIMARY KEY, EMPNAME VARCHAR2(20),EMMPSAL NUMBER(5) ) CREATE TABLE EMP (EMPNO NUMBER(2), EMPNAME VARCHAR2(20), EMPSAL NUMBER(5), PRIMARY KEY(EMPNO) )

Foreign Key (Self Reference) Constraint


Represents relationship among tables Column or group of columns whose values are derived from primary key or unique key of some other table Foreign Key defined table is called Foreign table or Detail table Primary Key defined table is called Primary table or Master table Master table is referenced by REFERENCES TableName.ColumnName Features of Foreign Key
References a column(s) in same or other table Parent being referenced must be unique or Primary key Child may have duplicate vales If no child record exist parent record can be deleted If child record exist master table cannot be updated Record cannot be inserted in detail table if no record exist in master table

Foreign Key Created At Column And Table Level


CREATE TABLE EMP (EmpNo NUMBER(2), EmpName Varchar2(20), Deptno Number(2) REFERENCES Dept(Deptno) ) CREATE TABLE EMP (EmpNo NUMBER(2), EmpName Varchar2(20), Deptno Number(2), FOREIGN KEY(DeptNo) REFERENCES Dept(Deptno) )

Unique Key Constraint


The UNIQUE column constraint permits multiple entries of NULL into column Features Of Unique Constraint
Will not allow duplicate values Unique index created automatically Table can contain multiple unique keys Can combine up to 16 columns

Unique Key Created At Column And Table Level


CREATE TABLE EMP (EmpNo Number(2), EmpName Varchar(20), EmpSal Number(5) UNIQUE) ) CREATE TABLE EMP (EmpNo Number(2), EmpName Varchar(20), EmpSal Number(5), UNIQUE(Empsal) )

Business Rule Constraint


Business rules are applied to table columns Applied to data prior the data being inserted into the table columns Ensures that the records or data in the table have integrity Implemented by using CHECK constraints and can be bound to the column using CREATE TABLE or ALTER TABLE command Business rule validation checks are performed when any INSERT or UPDATE statement is executed. These constraints are defined at Column Level and Table Level

Business Rule Constraints Contd.


NULL VALUE A NULL value is different from space or zero and can be inserted into columns of any data type. Setting a NULL value is appropriate when the actual value is unknown or not meaningful Will evaluate to NULL in any expression for example NULL multiplied by 10 is NULL If a column has NULL value Oracle ignores any UNIQUE, FOREIGN KEY, CHECK constraints that are applied to that column

NOT NULL Constraint


Oracle has NOT NULL column constraint that ensures that a column cannot be left empty. It implies that a value has to be entered in that column if a record has to be accepted SYNTAX ColumnName DataType(Size) NOT NULL Example CREATE TABLE Dept (DeptNo Number(2) Primary Key, Dname Varchar(20) NOT NULL)

CHECK Constraint
Business rule applied to a table column using CHECK constraint Must be specified as a logical expression that evaluates to TRUE or FALSE COLUMN LEVEL ColumnName DataType Size CHECK Logical Expression CREATE TABLE Emp (EmpNo Number(2), EmpName Varchar(20) CHECK (EmpName=UPPER(EmpName), EmpSal Number(5) CHECK EmpSal > 0) TABLE LEVEL CHECK (Logical Expression) CREATE TABLE Emp (EmpNo Number(2), EmpName Varchar(20), EmpSal Number(5) , CHECK (EmpName=UPPER(EmpName), CHECK EmpSal > 0)

Defining Integrity Constraints Via ALTER Table Command


Integrity constraints can be defined using the constraint clause in ALTER TABLE command Oracle will not allow constraints to be defined if data previously placed in the table violates such constraints ALTER TABLE Emp ADD PRIMARY KEY(EmpNo) ALTER TABLE Emp ADD CONSTRAINT F_Deptno FOREIGN KEY(Deptno) REFERENCES Dept(Deptno) ALTER TABLE Emp DROP PRIMARY KEY(EmpNo) ALTER TABLE Emp DROP CONSTRAINT F_Deptno

DEFAULT VALUE
At the time of table creation a default value can be assigned to a column. The DEFAULT clause can be used to specify a default value for an empty column so that when a record is added to the table and the column is left empty Oracle engine will load this default value in that column SYNTAX ColumnName DataType Size DEFAULT value EXAMPLE CREATE TABLE Emp (EmpNo Number(2), EmpName Varchar(20), EmpSal Number(5), HireDate Date Default SYSDATE) Page 158, 159, 160, 191, 243

Views
To reduce redundant data to minimum possible Oracle allows the creation of an object called as View. A view is mapped to a select statement The table on which the view is based is described in the from clause of the select statement. The select clause consists of a subset of columns of the table. Thus a view which is mapped to the table will in effect have a subset of the actual columns of the tables from which it is built. This technique offers an effective way of hiding the columns When a reference is made to a view its definition is scanned the base table is opened and the view created on top of the base table Hence a view holds no data at all until a specific call to a view is made Oracle engine treats a view as it was base table.

Views Contd
Views that used only for looking at table data are called as Read-Only views. Views that are used to look at the table data as well as Insert, Update and Delete table data is called an Updateable View. SYNTAX CREATE VIEW ViewName AS SELECT Statement EXAMPLE CREATE VIEW V_EMP AS SELECT * FROM EMP VIEW CALL SELECT * FROM ViewName The DROP VIEW command is used to remove a view from the database SYNTAX DROP VIEW ViewName EXAMPLE DROP VIEW V_EMP

Types Of Views
Horizontal View A horizontal view slices the table horizontally to create a view. All columns of the source table are in this view but only some rows are visible EXAMPLE CREATE VIEW V_HORIZ AS Select * FROM Emp WHERE Deptno=10 Vertical View A vertical view slices the table vertically to create a view. All rows of the source table are in this view but only some columns are visible EXAMPLE CREATE VIEW V_VERT AS Select EmpNo,EmpName FROM Emp

Types Of Views
Row/Column Subset View A row/column subset view slices the table horizontally as well as vertically to create a view. Only some columns and some rows of the source table are in this view EXAMPLE CREATE VIEW RowColView AS Select EmpNo, EmpName FROM Emp WHERE DeptNo=10 Grouped View A query specified in a view with a group by clause is called as grouped view EXAMPLE CREATE VIEW GrpView AS Select COUNT(*), SUM(EmpSal) FROM EMP GROUP BY DeptNo Joined View Joined views are created by specifying multi table query that draws data from multiple tables EXAMPLE CREATE VIEW JoinView AS Select D.Dname, E.EmpName From Dept D, Emp E WHERE D.DeptNo=E.EmpNo

Updates on Views
Views can also be used for data manipulation. Views on which data manipulation can be done are called Updateable Views. When an updateable view is given in an Insert, Update or Delete SQL statement modifications to data in the view will be immediately passed to the underlying table For a view to be updateable it should meet the following criteria
Views defined from single table It should not contain GROUP BY, ORDER BY, FUNCTIONS, DISTINCT keyword, Columns with Arithmetic expressions If view uses WITH READ OPTION or WITH CHECK OPTION

Comparison Of Views and Tables


Table
Comprises of rows and columns (records and fields) Stores data in database occupy some space in database

View
Comprises of query in view definition Contains rows and columns but it is virtual table based on result set of an SQL statement Fields in a view are fields from one or two real tables A glimpse of a table can be shown in a view Does not contain data when it is called goes to memory and fetches data from base tables

Advantages Of Views
Restrict the user from accessing all the data Can be a result of complex query and hence no need of writing the query again and again Definition remains unaffected although there is any change in structure of a table. Does not allow direct access to the tables of data dictionary If data is accessed through view the DBMS automatically checks the data for specified integrity constraints

Disadvantages Of Views
If a view is defined by complex multi table query it may take longer time to run As the complexity is hidden by the view users are not aware of how much complicated task the query is actually performing View should be created as per standard so that it simplifies the job of DBA When a user tries to update a view the DBMS must translate this query into an update on rows of underlying base tables Complex views cannot be uploaded as they are read only type

Triggers
It is a procedure that is automatically invoked by the DBMS in response to specific alteration to the database or table in the database Stored in database as database objects A database that has a set of associated triggers is called as active database Enables DBA to create additional relationships between separate databases SYNTAX CREATE OR REPLACE TRIGGER TriggerName ENABLE | DISABLE BEFORE | AFTER INSERT | UPDATE | DELETE OF ColumnName ON TableName FOR EACH ROW WHEN TriggerCondition DECLARE Variable Declaration BEGIN Trigger Code EXCEPTION Exception Clauses END TriggerName

Trigger Types
Row Level Triggers Fired each time the table is affected by the triggering statement Statement Level Triggers Fired once on behalf of the triggering statement regardless of the number of rows affected EXAMPLE CREATE TRIGGER UpperName AFTER INSERT ON Emp INSERT INTO Emp VALUES (UPPER(Ename)) FOR EACH ROW

Trigger Advantages
Useful for enforcing referential integrity which preserves the defined relationships between tables when rows are added, updated or deleted If the new information is inconsistent in the database error will be raised that will cause the entire transaction to rollback

Trigger Disadvantages
Hampers the performance as the database operation becomes slower due to triggers Cannot modify the table on which triggering action is written or connected by primary key foreign key relation

You might also like