Anda di halaman 1dari 97

SQL (Structured Query Language) Practical

Introduction to databases

Overview of database
What a database is How it fits into the broader information management picture What the different parts of a database are and THEN finally we will move to SQL . . .

What is a database?

A database is a storage space for content / information (data)

But what is data? And where is it now?


Data is factual information about objects and concepts, such as:
measurements statistics

You can find it in:


y y y y y y y filing cabinets spreadsheets folders ledgers lists colleagues memories piles of papers on your desk

What does managing information mean?


Making information work for us Making information useful Avoiding "accidental disorganisation Making information easily accessible and integrated with the rest of our work

Managing as re-organising
We often need to access and re-sort data for various uses. These may include:
Creating mailing lists Writing management reports Generating lists of selected news stories Identifying various client needs

Can you add to the list?

Managing as re-processing
The processing power of a database allows it to:
y Sort y Match y Link y Aggregate y Skip fields y Calculate y Arrange

Databases everywhere!
Because of the versatility of databases, we find them powering all sorts of projects:
y A web site that is capturing registered users y A client tracking application for social service organisations y A medical record system for a health care facility y Your personal address book in your e-mail client y A collection of word processed documents y A system that issues airline reservations

Different parts of a database


Fields Records Queries Reports

Fields
Database storage units Generic elements of content

Records
A simple table showing fields (columns) and records(rows):

And as part of an MS Access database table:

Queries
Queries are the information retrieval requests you make to the database Your queries are all about the information you are trying to gather

Reports
If the query is a question... ...then the report is its answer Reports can be tailored to the needs of the data-user, making the information they extract much more useful Now with this knowledge about databases, lets proceed to explore SQL..........

Objectives of SQL
A database language should allow a user to :
 Create the database and relation structures  Perform basic DBM tasks like
 insertion  Modification  Deletion

 Perform both simple and complex queries

A database language must do all these tasks with minimum user effort , syntax should be easy to learn and it should be portable.

SQL IS INTENDED TO SATISFY ALL THESE REQUIREMENTS.

Components of SQL
As a language, SQL has two major components:
DDL (Data Definition Language) for defining the database structure and controlling access to the data. DML (Data Manipulation Language) for retrieving and updating data.

Advantages of SQL
SQL is a non-procedural language you specify what information you require, rather than how to get it. SQL is free-format it means that parts of the statements do not have to be typed at particular locations on the screen. SQL can be used by a range of users including DBA (database Administrator), management personnel, application developers and many other types of end-users.

Advantages of SQL
The command structure consists of standard English words like CREATE TABLE, INSERT, SELECT. For Example:
CREATE TABLE staff( staffno VARCHAR(5), sname VARCHAR(15), salary DECIMAL(7,2)); INSERT INTO staff VALUES ( SM100 , Suman , 30000); SELECT staffno, sname, salary FROM staff WHERE salary > 20000;

Writing SQL Commands


An SQL statement consists of reserved words and user-defined words. Reserved words are fixed part of SQL language and have fixed meanings. They must be spelt exactly as required. User defined words are made up by the users. Each SQL statement must end with semicolon (;).

Writing SQL Commands


Most components of SQL are case insensitive. But literal character data must be typed exactly as it appears in the database. For e.g. If we store person s name as SUMAN and then search for it using the string Suman then the result will be row not found.

Writing SQL Commands


Better readability can be maintained by following:
Each clause in statement should start on a new line. The beginning of each clause should line-up with beginning of other clauses.

Upper-case letters are used for Reserved words. Lower-case letters for user-defined words.

Writing SQL Commands


The user defined words of SQL statements should follow some rules:
 names -- names of database elements: tables, columns, views, users, schemas; names must begin with a letter (a - z) and may contain digits (0 - 9) and underscore (_)  literals single quoted strings, numeric values, date time values  delimiters -- + - , ( ) = < > <= >= <> . * / || ? ;

Data Manipulation
The SQL DML statements are :
    SELECT -- query tables and views in the database INSERT -- add rows to tables UPDATE -- modify columns in table rows DELETE -- remove rows from tables

SELECT Statement Basics


The statement begins with the SELECT keyword. The basic SELECT statement has 3 clauses:
SELECT - it specifies the table columns that are retrieved. FROM - specifies the tables accessed. WHERE - it specifies which table rows are used.

The WHERE clause is optional; if missing, all table rows are shown. All the three components of SELECT statement must appear in same order.

SELECT Clause
SELECT has the following general format: SELECT [ALL|DISTINCT] select-list
select-list is a list of column names separated by commas. ALL and DISTINCT specifiers are optional. DISTINCT specifies that duplicate rows are discarded. A duplicate row is when each corresponding select-list column has the same value. The default is ALL, which retains duplicate rows.

FROM Clause
The FROM clause always follows the SELECT clause. It lists the tables accessed by the query. For example, SELECT staffno FROM staff; A special select list consisting of a single '*' requests all columns in all tables in the FROM clause. For example, SELECT * FROM staff;

WHERE clause
It is optional. When specified, it always follows the FROM clause. The WHERE clause filters rows from the FROM clause tables. Omitting the WHERE clause specifies that all rows are used.

WHERE clause
Following the WHERE keyword is a logical expression, also known as a predicate. The predicate evaluates to a SQL logical value -true, false or unknown. The most basic predicate is a comparison: example WHERE color = 'Red' This predicate returns:
true -- if the color column contains the string value 'Red', false -- if the color column does not contains value Red unknown -- if the color column contains null.

Comparison Operators
= - it compares two values for equality. > - greater than < - less than >= - greater than or equal to <= - less than or equal to <> - not equal to For example: SELECT * FROM staff WHERE salary >= 20000;

Exercise
Retrieve all columns, all rows.
1. Display the details of all employees 2. Display the details of all departments.

Retrieve specific columns, all rows.


1. Display employee name, job title and salary of all employees.

Retrieve specific rows, all columns.


1. Display details of all employees working in department 10. 2. Display details of all employees working as MANAGER.

Exercise
Use of DISTINCT clause.
1. Display all jobs in the organization. 2. Display numbers of all departments where employees are working.

Use of Calculated fields.


1. Display details of all employees with their annual salaries.

BETWEEN Operator
The BETWEEN operator tests whether a value is between two other values. (both values inclusive) BETWEEN comparisons have the following format: value-1 [NOT] BETWEEN value-2 AND value-3 For example : SELECT * FROM emp WHERE sal BETWEEN 5000 and 15000;

IN operator
The IN operator tests whether a value matches any value in a list of values. IN comparisons have the following general format: value-1 [NOT] IN ( value-2 [, value-3] ... ) This comparison tests if value-1 matches value-2 or matches value-3, and so on. For example, SELECT name FROM emp WHERE deptno IN (10,40);

PRACTICAL Query sheet 1


Display the contents of EMP, DEPT tables. Display the details of all employees Display the details of all departments. Display employee name, job title and salary of all employees. Display details of all employees working in department 10. Display details of all employees working as MANAGER. Display all jobs in the organization. Display numbers of all departments where employees are working. Display details of all employees with their annual salaries. Display details of all employees whose salary range is 10000 to 20000. Display details of all employees who are not working in department 10 and 30. Display the names and job titles of all employees whose salary is either 10000 or 30000 or 50000. 13. Display employee number, salary and jobs of all employees of department 20. 14. Display employee number and name of those employees who do not earn commission. 15. Display details of all employees who were hired before 1st Jan 1989. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

LIKE Operator
The SQL LIKE clause is very useful when you want to specify a search condition within your SQL WHERE clause, based on a part of a column contents. For example if you want to select all customers having FirstName starting with 'J SELECT * FROM Customers WHERE FirstName LIKE 'J% ;

LIKE Operator
The '%' is a so called wildcard character and represents any string in our pattern. Another wildcard character is '_' representing any single character. Example: SELECT * FROM emp WHERE hiredate LIKE %82 ;

Compound conditions - AND & OR


SQL AND clause is used when more than one condition is used in WHERE clause, and at the same time all conditions should be true.
SELECT * FROM Customers WHERE FirstName = 'John' AND LastName = 'Smith ;

The SQL OR statement will return all rows satisfying any of the conditions listed in the WHERE clause.
SELECT * FROM Customers WHERE FirstName = 'James' OR FirstName = 'Paula ;

Aggregate functions
The SQL COUNT aggregate function is used to count the number of rows in a database table.
SELECT COUNT(LastName) AS NumberOfCustomers FROM Customers ;

This will give total No. of Customers . The SQL MAX aggregate function allows us to select the highest (maximum) value for a certain column.
SELECT MAX(DOB) AS MaxDOB FROM Customers ;

Aggregate functions
The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column.
SELECT MIN(DOB) AS MinDOB FROM Customers ;

The SQL AVG aggregate function selects the average value for certain table column.
SELECT AVG(SaleAmount) AS AvgSaleAmount FROM Sales ;

Aggregate functions
The SQL SUM aggregate function allows selecting the total for a numeric column.
SELECT SUM(SaleAmount) FROM Sales WHERE CustomerID = 3 ;

GROUP BY Clause
The SQL GROUP BY statement is used along with the SQL aggregate functions like SUM to provide means of grouping the result dataset by certain database table column(s).
SELECT Date, SUM(Hours) FROM EmployeeHours GROUP BY Date ; SELECT Employee, AVG(Hours) FROM EmployeeHours GROUP BY Employee ;

The first attribute in SELECT clause should always be the same attribute on which grouping is done.

HAVING Clause
The SQL HAVING clause is used to restrict conditionally the output of a SQL statement, by a SQL aggregate function used in your SELECT list of columns. You can't specify criteria in a SQL WHERE clause against a column in the SELECT list for which SQL aggregate function is used. Having clause is always computed after the groups are formed and the aggregates are fully computed

NOTE : WHERE clause is used for filtering rows and HAVING clause is used for filtering Groups.

Examples
SELECT Employee, SUM (Hours) FROM EmployeeHours GROUP BY Employee HAVING SUM (Hours) > 24 ;

ORDER BY Clause
The ORDER BY clause is optional. If used, it must be the last clause in the SELECT statement. The ORDER BY clause requests sorting for the results of a query. When the ORDER BY clause is missing, the result rows from a query have no defined order (they are unordered). Syntax is ORDER BY column-1 [ASC|DESC] [ column-2 [ASC|DESC] ] ... Example: SELECT * FROM emp ORDER BY empno DESC;

PRACTICAL Query sheet2


1. Display total number of employees working in organization. 2. Display employee number, name of those employees, who do not earn commission and they are not clerks. 3. Display details of all employees who were hired in year 1981. 4. Display employee number, salary and department number of all employees, department wise. 5. Display minimum and maximum salaries in organization. 6. Display maximum salary department wise. 7. Total number of employees who are not entitled for commissions. 8. Calculate job wise average salary. 9. Display names, employee number of all employees whose name starts with letter J and ends with S; and were hired before 1-January-1982 . 10. Display employee number and department number of all employees who are earning more than 2500 and whose name has third letter as R and working in department 10.

Concatenation operator(||)
Concatenates columns or character strings to other columns Is represented by two vertical bars (||) Creates a resultant column that is a character expression. Example: SELECT last_name || is a || job AS "Employee Details FROM employees;

Displaying Table Structure


DESCRIBE command is used to display the structure of a table. The command shows the column names and data types, as well as whether a column must contain data. Example : DESC [RIBE] emp; Note: It displays the field name, NULL? - NOT NULL and data type of field.

Data Types
The data types are described as follows: 1. NUMBER(p,s) - Number value having a maximum number of digits p, with s digits to the right of the decimal point. 2. VARCHAR2(s) - Variable-length character value of maximum size s. 3. DATE - Date and time value between January 1, 4712 B.C., and December 31, 9999 A.D. 4. CHAR(s) - Fixed-length character value of size s

Rules of Precedence
1. 2. 3. 4. 5. 6. 7. 8. Arithmetic operators Concatenation operator Comparison conditions IS [NOT] NULL, LIKE, [NOT] IN [NOT] BETWEEN NOT logical condition AND logical condition OR logical condition

Using the GROUP BY Clause on Multiple Columns


Example: SELECT deptno, job, SUM(salary) FROM employees GROUP BY deptno, job ;

Practice sheet 3
Create a query to display all the data from the EMP table. Separate each column by a comma. Name the column THE_OUTPUT. 2. Display the name concatenated with the job, separated by a comma and space, and name the column Employee and Title. 3. Display the employee if an employee is a president or a sales representative, and if the employee earns more than $15,000. 4. Display the last names and salaries of all employees. Order the result by department number, and then in descending order by salary. 5. Display the last name, salary, and commission for all employees who earn commissions. Sort data in descending order of salary and commissions. 6. Display the name of all employees who have an a and an e in their name. 7. Display the name, job, and salary for all employees whose job is sales representative or clerk and whose salary is not equal to 2500, 3500, or 7000. 8. Display of average salaries of those departments that have an average salary greater than 8,000. 9. Display the job and total monthly salary for each job with a total payroll exceeding 13000. Exclude sales representatives and sorts the list by the total monthly salary. 10. Displays the maximum average salary of departments. 1.

11. Display the highest, lowest, sum, and average salary of all employees. Label the columns Maximum, Minimum, Sum, and Average, respectively. 12. Write a query to display the number of people with the same job. 13. Determine the number of managers without listing them. Label the column Number of Managers.

Like operator Escape option


When you need to have an exact match for the actual % and _ characters, then ESCAPE option is used. This option specifies what the escape character is. If you want to search for strings that contain SA_ , you can use the following SQL statement: SELECT employee_id, last_name, job_id FROM employees WHERE job_id LIKE %SA\_% ESCAPE \ ;

Cartesian Product
A Cartesian product is generated if a join condition is omitted. Example : Display employee last name and department name from the EMPLOYEES and DEPARTMENTS tables. SELECT last_name, department_name dept_name FROM employees, departments;

Inner joins
This join involves primary and foreign key complements. It is also known as Equijoins or simple joins. SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id, departments.location_id FROM employees, departments WHERE employees.department_id = departments.department_id;

Using Table Aliases


SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e , departments d WHERE e.department_id = d.department_id;

Guidelines :
Table aliases can be up to 30 characters in length, but shorter is better. If a table alias is used for a particular table name in the FROM clause, then that table alias must be substituted for the table name throughout the SELECT statement. Table aliases should be meaningful. The table alias is valid only for the current SELECT statement.

Non-Equijoins
A non-equijoin is a join condition containing something other than an equality operator. The relationship between the EMP table and the SALGRADE table has an example of a non-equijoin. A relationship between the two tables is that the SALARY column in the EMP table must be between the values in the LOWSAL and HISAL columns of the SALGRADE table. The relationship is obtained using an operator other than equals (=). SELECT e.ename, e.sal, s.grade FROM emp e, salgrade s WHERE e.sal BETWEEN s.losal AND s.hisal;

Outer Join
The missing rows can be returned if an outer join operator is used in the join condition. The operator is a plus sign enclosed in parentheses (+), and it is placed on the side of the join that is deficient in information. This operator has the effect of creating one or more null rows, to which one or more rows from the non deficient table can be joined. Example : Display employee last names, department ID s and department names. SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id(+) = d.department_id ; Note : it will display detail of deptt that donot have any employee.

Self - Join
Sometimes you need to join a table to itself. Example : The example joins the EMPLOYEES table to itself. To simulate two tables in the FROM clause, there are two aliases, namely w and m, for the same table, EMPLOYEES. In this example, the WHERE clause contains the join that means where a worker s manager number matches the employee number for the manager. SELECT worker.last_name || works for || manager.last_name FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id ;

Joining Tables Using SQL: 1999 Syntax


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

Joining Tables Using SQL: 1999 Syntax


CROSS JOIN - Returns a Cartesian product from the two tables NATURAL JOIN - Joins two tables based on the same column name JOIN table USING column_name - Performs an equijoin based on the column name JOIN table ON table1.column_name - Performs an equijoin based on the condition in the ON clause = table2.column_name LEFT/RIGHT/FULL OUTER Performs outer join

Joining Tables Using SQL- Examples


SELECT last_name, department_name FROM employees CROSS JOIN departments ; SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations ; Note: The join can happen only on columns having the same names and data types in both the tables. If the columns have the same name, but different data types, then the NATURAL JOIN syntax causes an error.

Joining Tables Using SQL- Examples


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. The columns referenced in the USING clause should not have a qualifier (table name or alias) anywhere in the SQL statement. SELECT e.employee_id, e.last_name, d.location_id FROM employees e JOIN departments d USING (department_id) ;

NATURAL JOIN - 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. The join condition is separated from other search conditions. The ON clause makes code easy to understand. SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id);

Outer Join - Example


SELECT e.last_name, e.department_id, d.department_name FROM employees e LEFT OUTER JOIN departments d ON (e.department_id = d.department_id) ; Equivalent statement : SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE d.department_id (+) = e.department_id;

Outer Join - Example


SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) ; Equivalent statement : SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE d.department_id = e.department_id (+);

Outer Join - Example


SELECT e.last_name, e.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ; Earlier Equivalent statement : SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id (+) = d.department_id UNION SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id (+);

Using the & Substitution Variable


Use an ampersand (&) to identify each variable in your SQL statement. Example 1 : SELECT empno, last_name, salary, department_id FROM employees WHERE empno = &employee_num ; Example 2 : SELECT last_name, department_id, salary*12 FROM employees WHERE job_id = &job_title ; Example 3 : SELECT employee_id, last_name, job_id,&column_name FROM employees WHERE &condition ORDER BY &order_column ;

Using the && Substitution Variable


Use the double-ampersand (&&) if you want to reuse the variable value without prompting the user each time. Example: SELECT empno, last_name, job_id, &&column_name FROM employees ORDER BY &column_name;

CREATE TABLE Statement


To create a table, a user must have the CREATE TABLE privilege. Syntax: CREATE TABLE table (column datatype [DEFAULT expr][, ...]); where table is the name of the table DEFAULT expr specifies a default value if a value is omitted in the INSERT statement column is the name of the column datatype is the column s data type and length Example : CREATE TABLE dept (deptno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13));

CREATE TABLE Statement


To confirm table creation, use DESCRIBE command. Useful commands: See the names of tables owned by the user. SELECT table_name FROM user_tables ; View distinct object types owned by the user. SELECT DISTINCT object_type FROM user_objects ; View tables, views owned by the user. SELECT * FROM user_catalog;

ALTER TABLE Statement


To add, modify, and drop columns in a table, we use the ALTER TABLE statement. Syntax: ALTER TABLE table ADD |MODIFY|DROP (column datatype [DEFAULT expr] [, column datatype]...); where table is the name of the table ADD|MODIFY|DROP is the type of modification column is the name of the new column datatype is the data type and length of the new column DEFAULT expr specifies the default value for a new column

Practice sheet 5
1. 2. 3. 4. 5. 6. 7. Display the name and hire date of any employee in the same department as ABC. Exclude ABC. Display the employee numbers & names of all employees who earn more than the average salary. Sort the results in ascending order of salary. Display the employee numbers & names of all employees who work in a department with any employee whose name contains a u . Display the name, department number, and job of all employees whose department location is DELHI . Display the name and salary of every employee who reports to King. Display the department number, name & job for every employee in the MARKETING department. Display the names, job & department names for every employee in a location given by user at run-time. It should allow for case-insensitive searches of the department location.

ALTER TABLE Statement


To add, modify, and drop columns in a table, we use the ALTER TABLE statement. Syntax: ALTER TABLE table ADD |MODIFY|DROP (column datatype [DEFAULT expr] [, column datatype]...); where table is the name of the table ADD|MODIFY|DROP is the type of modification column is the name of the new column datatype is the data type and length of the new column DEFAULT expr specifies the default value for a new column Example : ALTER TABLE dept80 ADD (job_id VARCHAR2(9)); ALTER TABLE dept80 MODIFY (last_name VARCHAR2(30));

ALTER TABLE Statement


Modifying a Column
You can change a column s data type, size, and default value. A change to the default value affects only subsequent insertions to the table.

DROP COLUMN clause is used to drop columns no longer needed from the table. ALTER TABLE dept80 DROP COLUMN job_id;

Dropping a Table
It removes the definition of an Oracle table. When a table is dropped, the database loses all the data in the table and all the indexes associated with it. Syntax : DROP TABLE table Any views on table remain but are invalid. Any pending transactions are committed. Only the creator of the table or a user with the DROP ANY TABLE privilege can remove a table. Example : DROP TABLE dept80; Note: The DROP TABLE statement, once executed, is irreversible.

Truncating a Table
Removes all rows from a table Releases the storage space used by that table You cannot roll back row removal when using TRUNCATE. Syntax : TRUNCATE TABLE table; If the table is the parent of a referential integrity constraint, you cannot truncate the table.Disable the constraint before issuing the TRUNCATE statement.

The DELETE statement can also remove all rows from a table, but it does not release storage space.

INSERT Statement
Add new rows to a table by using the INSERT statement. Only one row is inserted at a time Syntax : INSERT INTO table [(column [, column...])] VALUES (value [, value...]); List values in the default order of the columns in the table. Optionally, list the columns in the INSERT clause. Enclose character and date values within single quotation marks.

INSERT Statement
Methods for Inserting Null Values 1. Implicit - Omit the column from the column list. 2. Explicit - Specify the NULL keyword in the VALUES list, specify the empty string ( ) in the VALUES list for character strings and dates. Example: INSERT INTO dept (deptno, dname ) VALUES (30, Purchasing ); (LOC attribute not specified here) INSERT INTO departments VALUES (100, Finance , NULL);

Example
INSERT INTO employees (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id) VALUES (113, Louis , Popp , LPOPP , 515.124.4567 , SYSDATE, AC_ACCOUNT , 6900, NULL, 205, 100); INSERT INTO departments (department_id, department_name, location_id) VALUES (&department_id, &department_name ,&location);

Copying Rows from Another Table


INSERT INTO sales_reps(id, name, salary, commission_pct) SELECT employee_id, last_name, salary, commission_pct FROM employees WHERE job_id LIKE %REP% ; Do not use the VALUES clause. Match the number of columns in the INSERT clause to those in the subquery.

UPDATE Statement
Modify existing rows with the UPDATE statement. Update more than one row at a time, if required. Syntax : UPDATE table SET column = value [, column = value, ...] [WHERE condition] Example : UPDATE employees SET department_id = 70 WHERE employee_id = 113; All rows in the table are modified if you omit the WHERE clause.

Updating Two Columns with a Subquery


UPDATE table SET column = ( SELECT column FROM table WHERE condition) [ , column = ( SELECT column FROM table WHERE condition)] [WHERE condition ] ; Example : Update employee 114 s job and salary to match that of employee 205. UPDATE employees SET job_id = ( SELECT job_id FROM employees WHERE employee_id = 205), salary = ( SELECT salary FROM employees WHERE employee_id = 205) WHERE employee_id = 114;

DELETE Statement
You can remove existing rows by using the DELETE statement. Syntax: DELETE [FROM] table [WHERE condition]; Example: DELETE FROM departments WHERE department_name = Finance ;

All rows in the table are deleted if you omit the WHERE clause. The DELETE statement does not ask for confirmation. However, the delete operation is not made permanent until the data transaction is committed. Therefore, you can undo the operation with the ROLLBACK statement if you make a mistake.

Deleting Rows Based on Another Table


Use subqueries in DELETE statements to remove rows from a table based on values from another table. Example : DELETE FROM employees WHERE deptno = (SELECT deptno FROM dept WHERE dname LIKE %S% ); You cannot delete a row that contains a primary key that is used as a foreign key in another table.

Constraints
The Oracle Server uses constraints to prevent invalid data entry into tables. You can use constraints to do the following: Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from that table. The constraint must be satisfied for the operation to succeed. Prevent the deletion of a table if there are dependencies from other tables Data Integrity Constraints are : 1. NOT NULL - Specifies that the column cannot contain a null value 2. UNIQUE - Specifies a column or combination of columns whose values must be unique for all rows in the table 3. PRIMARY KEY - Uniquely identifies each row of the table 4. FOREIGN KEY - Establishes and enforces a foreign key relationship between the column and a column of the referenced table 5. CHECK - Specifies a condition that must be true

Defining Constraints
Syntax : CREATE TABLE table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]); Example : CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID));

NOT NULL CONSTRAINT


The NOT NULL Constraint
The NOT NULL constraint ensures that the column contains no null values. Columns without the NOT NULL constraint can contain null values by default.

The UNIQUE Constraint


A UNIQUE key integrity constraint requires that every value in a column or set of columns (key) be unique. UNIQUE constraints allow the input of nulls. Any number of rows can include nulls for columns when UNIQUE constraint is given because nulls are not considered equal to anything. Example : CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... CONSTRAINT emp_email_uk UNIQUE(email));

PRIMARY KEY Constraint


A PRIMARY KEY constraint creates a primary key for the table. Only one primary key can be created for each table. The PRIMARY KEY constraint is a column or set of columns that uniquely identifies each row in a table. This constraint enforces uniqueness of the column or column combination and ensures that no column that is part of the primary key can contain a null value.

The FOREIGN KEY Constraint


The FOREIGN KEY, or referential integrity constraint, designates a column or combination of columns as a foreign key and establishes a relationship between a primary key or a unique key in different table. Example : CREATE TABLE employees( employee_id NUMBER(6), last_name VARCHAR2(25) NOT NULL, email VARCHAR2(25), salary NUMBER(8,2), commission_pct NUMBER(2,2), hire_date DATE NOT NULL, ... dept_id NUMBER(4), CONSTRAINT emp_dept_fk FOREIGN KEY (dept_id) REFERENCES departments(department_id));

FK Constraint & clauses


FOREIGN KEY: Defines the column in the child table at the table constraint level REFERENCES: Identifies the table and column in the parent table ON DELETE CASCADE: Deletes the dependent rows in the child table when a row in the parent table is deleted. ON DELETE SET NULL: Converts dependent foreign key values to null.

The CHECK Constraint


The CHECK constraint defines a condition that each row must satisfy. A single column can have multiple CHECK constraints which refer to the column in its definition. There is no limit to the number of CHECK constraints which you can define on a column. CHECK constraints can be defined at the column level or table level. Example : CREATE TABLE employees (... salary NUMBER(8,2) CONSTRAINT e_sal_min CHECK (salary > 0), ...

ALTER TABLE statement


You can add a constraint for existing tables by using the ALTER TABLE statement with the ADD clause. ALTER TABLE statement is used to : Add or drop a constraint Enable or disable constraints Add a NOT NULL constraint by using the MODIFY Clause Syntax : ALTER TABLE table ADD [CONSTRAINT constraint] type (column); Example : ALTER TABLE employees ADD CONSTRAINT emp_manager_fk FOREIGN KEY(manager_id) REFERENCES employees(employee_id);

ALTER TABLE statement


ALTER TABLE employees MODIFY (salary CONSTRAINT emp_salary_nn NOT NULL); Syntax for dropping constraint: ALTER TABLE table DROP PRIMARY KEY | UNIQUE (column) | CONSTRAINT constraint [CASCADE]; Example: ALTER TABLE departments DROP PRIMARY KEY CASCADE; ALTER TABLE employees DROP CONSTRAINT emp_manager_fk;

Examples
ALTER TABLE employees DISABLE CONSTRAINT emp_emp_id_pk CASCADE; ALTER TABLE employees ENABLE CONSTRAINT emp_emp_id_pk;

Practice sheet 5
1. 2. 3. 4. 5. 6. 7. Display the name and hire date of any employee in the same department as ABC. Exclude ABC. Display the employee numbers & names of all employees who earn more than the average salary. Sort the results in ascending order of salary. Display the employee numbers & names of all employees who work in a department with any employee whose name contains a u . Display the name, department number, and job of all employees whose department location is DELHI . Display the name and salary of every employee who reports to King. Display the department number, name & job for every employee in the MARKETING department. Display the names, job & department names for every employee in a location given by user at run-time. It should allow for case-insensitive searches of the department location.

Anda mungkin juga menyukai