SQL - Oracle - upto Integrity constraints

Post on 19-Jan-2016

17 views 2 download

description

Contains slides on Oracle 10g sql uptointegrity constraints

Transcript of SQL - Oracle - upto Integrity constraints

Database administrator responsibilities Installing and upgrading the Oracle server and application toolsAllocating system storage and planning future storage requirements for the database systemCreating primary objects (tables, views, indexes) once application developers have designed an applicationModifying the database structure, as necessary, from information given by application developers

Enrolling users and maintaining system securityControlling and monitoring user access to the databaseMonitoring and optimizing the performance of the databasePlanning for backup and recovery of database informationBacking up and restoring the database

Selection - selecting all columns and all/some rowsProjection – selecting specific columns

Distinct – (Eliminate duplicate rows)Arithmetic Expressions + , -Column Aliasing – (salary Hike)

Null value – A null value is a value that is unavailable, unassigned , unknown or inapplicable.

Concatenation operator (||)

Literal character string(‘ ‘)

Describe / desc – describes table structure

Limiting Rows using a selection(where clause) - character literals - dates

- comparison operators = > >= < <= < > or !=

Other comparison operators

Between and - between two valuesIn – in a setIs null – is a null valueLike – pattern matching % denotes zero or many characters _ denotes one character

Logical operators and or not (eg is not null, not in)

Order by clause-> sorts data in ascending or descending order-> asc, desc -> order by comes as the last clause in the select command-> sorting by multiple columns select last_name,department_id,salary from employees order by department_id, salary desc.

Queries 1.Query to display the last name and salary of employees earning more than 12000.2.Query to display the employee last name and department number for employee number 176.3. Display last name and salary for all employees whose salary Is not in the range of 5000 and 12000. 4. Display last name, job id and start date of employees hired between february 20,1998, and May 1, 19985. Display the last name and department number of all employees in departments 20 and 50 in alphabetical order by name.6. List the last name and salary of employees who earn between 5000 and 12000, and are in department 20 or 50.

7. List the last name and hire date of every employee who hired in 1994.8. List the last name and job title of all employees who do not have a manager9. List the last name ,salary and commission for all employees who earn commissions.10. List the names of all employees where the third letter of the name is an ‘a’11. List the names of all employees who have a ‘a’ and ‘e’ in their last names

Functions

Uses:1. Perform calculations on data2. Modify individual data items3. Manipulate output for groups of rows4. Format dates and numbers for display5. Convert column data types

Types of functions1. Single row2. Multiple row

Single row functions:1. Character2. Number3. Date 4. Conversion5. General

Character functions:

Lower UpperInitcapConcatSubstr (character , starting, ending)LengthInstr (source,character)Lpad|RpadTrim(character from character)Replace(text,search_txt,replacement_text)

Number functions

1. Round – rounds value to specified decimal2. Trunc - Truncates value to specified decimal3. Mod – Returns remainder of division

Dates: Oracle database stores dates in an internal numeric format: century, year, month ,day ,hours ,Minutes , seconds

The default date display format is DD – MON – RR

Sysdate

Arithmetic operations can be performed on dates(sysdate – hiredate)

Date functions:

Months_between(date1,date2)

Add_months(date,nomonths)

Next_day(date,day)

Last_day(date)

Round(date,{MONTH,Year});

Trunc (date,{MONTH,Year});

Conversion Functions:Implicit Explicit

Implicit varchar or char – Number varchar or char – Date Number – varchar date – varchar

Explicit To_char(date,’MM/YY’) To_Number(‘123’,999)To_Date(char,’DD-MON-YY’)(‘12-JUN-2010’,’DD-MON-YY’)

General Functions:

NVL(expr1,expr2)

NVL2(expr1,expr2,expr3)

NULLif(expr1,expr2)

Colaesce(expr1,expr2,……,exprn)

NVL Converts a null value to an actual value

NVL2 If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3. The argument expr1 can have any data type. eg nvl2(commpct, ’sal+comm’, ’sal’); nvl2(commission_pct,salary+(salary*commission_pct),salary

NULLIF Compares two expressions and returns null if they are equal, or the first expression if they are not equal Nullif(length(firstname),length(last_name))

COALESCE Returns the first non-null expression in the expression list

Coalesce(expr1,expr2,…..,exprn)

expr1 – returns this expression if it is not null expr2 – returns this expression if the first expression is null and this expression is not nullexprn – returns this expression if all other preceding expressions are null

Eg :Coalesce(commission_pct,salary,10) Coalesce(commission_pct,department_id,10)

JoinsA join is an operation which presents data combined from two or more tables.

A join generally requires a join condition which may be omitted.Types of joins: 1. Natural join2. Cross join (select * from table1,table2)3. Equi join (inner join)4. Non equi join5. Outer join left outer right outer join full outer join6. Self join

Outer JoinYou use an outer join to also see rows that do not meet the join condition.

The Outer join operator is the plus sign (+).SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column(+) = table2.column;

SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column = table2.column(+);

Self Join(Joining a table to itself)

SELECT worker.last_name || ’ works for ’ || manager.last_name FROM employees worker, employees managerWHERE worker.manager_id = manager.employee_id ;

Joining Tables Using SQL: 1999 Syntax

SELECT table1.column, table2.columnFROM table1[CROSS JOIN table2] [NATURAL JOIN table2] [JOIN table2 USING (column_name)] [JOIN table2ON(table1.column_name = table2.column_name)] a[LEFT|RIGHT|FULL OUTER JOIN table2ON (table1.column_name = table2.column_name)];

Creating Cross Joins• The CROSS JOIN clause produces the crossproduct of two tables.• This is the same as a Cartesian product between the two tables.

SELECT last_name, department_name FROM employees CROSS JOIN departments ;

The NATURAL JOIN clause is based on all columnsin the two tables that have the same name.

• It selects rows from the two tables that have equal values in all matched columns.

• If the columns having the same names have different data types, an error is returned.

Creating Joins with the USING Clause• If several columns have the same names but the data types do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an equijoin.

• Use the USING clause to match only one column when more than one column matches.

• Do not use a table name or alias in the referenced columns.• The NATURAL JOIN and USING clauses are mutually exclusive.

SELECT e.employee_id, e.last_name, d.location_idFROM employees e JOIN departments dUSING (department_id) ;

Note: In the above query don’t use aliasing for the column used with using clause.

Creating Joins with the ON Clause• The join condition for the natural join is basically an equijoin of all columns with the same name.• To specify arbitrary conditions or specify columns to join, the ON clause is used.

SELECT e.employee_id, e.last_name, e.department_id,d.department_id, d.location_idFROM employees e JOIN departments dON (e.department_id = d.department_id);

INNER Versus OUTER Joins• In SQL: 1999, the join of two tables returning only matched rows is an inner join.

• A join between two tables that returns the results of the inner join as well as unmatched rows left (or right) tables is a left (or right) outer join.

• A join between two tables that returns the results of an inner join as well as the results of a left and right join is a full outer join.

Joins - Comparing SQL: 1999 to Oracle SyntaxOracle SQL: 1999

Equi-Join - Natural/Inner JoinOuter-Join - Left Outer JoinSelf-Join - Join ONNon-Equi-Join - Join USINGCartesian Product - Cross Join

SELECT e.last_name, e.department_id, d.department_nameFROM employees eLEFT OUTER JOIN departments dON (e.department_id = d.department_id) ;

SELECT e.last_name, e.department_id, d.department_nameFROM employees eRIGHT OUTER JOIN departments dON (e.department_id = d.department_id) ;

SELECT e.last_name, e.department_id, d.department_nameFROM employees eFULL OUTER JOIN departments dON (e.department_id = d.department_id) ;

Group Functions

Group functions operate on sets of rows to give oneresult per group.

Unlike single-row functions, group functions operate on sets of rows to give one result per group. These sets may be the whole table or the table split into groups.

Types of Group Functions AVG COUNT MAX MIN SUM

Note: All group functions ignore null values. To substitute a value for null values, use the NVL, NVL2,or COALESCE functions.

The Oracle server implicitly sorts the result set in ascending order when using a GROUP BY clause. To override this default ordering, DESC can be used in an ORDER BY clause.

Creating Groups of Data

SELECT department_id, AVG(salary)FROM employeesGROUP BY department_id ;

Grouping on multiple columns

SELECT department_id dept_id, job_id, SUM(salary)FROM employeesGROUP BY department_id, job_id ;

Having clause in Group by

Integrity Constraints(conditions) Constraints enforce rules at the table level.

• Constraints prevent the deletion of a table if there are dependencies.

• The following constraint types are valid:– NOT NULL– UNIQUE– PRIMARY KEY– FOREIGN KEY– CHECK

NOT NULL Specifies that the column cannot contain a null value.

UNIQUE Specifies a column or combination of columns whose values must be unique for all rows in the table.

PRIMARY KEY Uniquely identifies each row of the table.

FOREIGN KEY Establishes and enforces a foreign key relationship between the column and a column of the referenced table.

CHECK Specifies a condition that must be true

Constraint Guidelines• Name a constraint or the Oracle server generates a name by using the SYS_Cn format.

• Create a constraint either:– At the same time as the table is created, or– After the table has been created

• Define a constraint at the column or table level.