Vous êtes sur la page 1sur 31

Introduction to DBMS fundamentals, SQL Introduction to DBMS A database management system (DBMS) consists of an interrelated data and a set

of programs to access that data. The collection of data is usually referred to as database. The primary goal of a database is to provide an environment that is both convenient and efficient to use in retrieving and storing database information. Database systems are designed to manage large bodies of information. The management of data involves both the definition of structures for the storage of information and provision of mechanisms for the manipulation of information. In addition, the database system must provide for the safety of the information stored, despite system crashes or attempts at unauthorized access. If data is stored among several users, the system must avoid possible anomalous results. Database systems overcomes the problems faced in file-oriented system. The database system are controlled by the Database Administrator (DBA) Advantages of DBMS: Reduces Data redundancy (duplicity) and inconsistency of data. Provides data sharing facilities. Provides Data Integrity and Security. Provides Data Independence. Resolves concurrent access anomalies. DATA ABSTRACTION:

A database management system provides users with an abstract view of data, i.e. the system hides certain details of how the data is stored and maintained. This concern has lead to the design of complex data structures for the representation of data in the database. Its complexity is hidden from the users through several levels of abstraction in order to simplify the interaction between the user and the system. Physical Level: The lowest level of abstraction describes the data is actually stored in the database. Conceptual Level: The next-higher level of abstraction describes what data are actually stored in the database and the relationship that exists between them. This level is used by DBA, who must decide what information is to be kept in the database.

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL View Level: The highest level of abstraction describes only a part of the entire database. DATA MODELS:

A data model can be defined as a collection of tools for describing data and the relationship between them.Data models can be classified into the following groups. Object oriented logical models. Record based logical models. Physical data models. Object oriented logical models: They are used in describing data at the conceptual and view levels. Some of the widely known models are Entity Relationship model(ER model): is based on real world perception which consists of collection of basic objects called Entities and relationships among these objects. Object oriented model: is based on collection of objects. An object contains instance variables within the object. An object also contains bodies of code that operate on the object, called methods. Record based logical models: They are used in describing data at the conceptual and view levels. As the database is structured in fixed-format records of several types, they are called as record based logical models. Some of the widely known models are: Relational model: represents data and relationships among data by a collection of tables, each of which has a number of columns with unique names. Network model: represents data by collection of records and relationships among data are represented by links which are viewed as pointers. Hierarchical model: represents data by collection of records, which are organized as trees rather than arbitrary graphs and relationships among data are represented by links which are viewed as pointers. Physical models: They are used in describing data at the lowest level. DATABASE FACILITIES: Two main types of facilities are provided by a DBMS: Data definition facility or Data definition language (DDL).

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Data manipulation or Data manipulation language (DML). Data definition language (DDL): A database scheme is specified by a set of definitions which are expressed by a special language called Data definition language (DDL).The result of compilation of DDL statements is a set of tables which are stored in a special file called Data Dictionary. The storage structures and access methods used by the database system are specified by a set of definitions in a special type of DDL called Data storage and definition language. The result of compilation of these definitions is a set of instructions to specify the implementation details of the database schemes which are usually hidden from others. Data manipulation language (DML): A Data manipulation language (DML) is a language that enables users to access or manipulate data efficiently. Data manipulation means 1. Retrieval of information stored in the database. 2. Insertion of new information into the database. 3. Deletion of information from the database. 4. Modification of data stored in the database. There two types of DMLS: 1. Procedural DMLs requires a user to specify what data is need and how it get it. 2. Non Procedural DMLs requires a user to specify what data is needed without specifying how to get it.

Query is a statement requesting the retrieval of information. A portion of a DML that involves retrieval is called query language.

STRUCTURE OF A DBMS: The major components of this system are Data definition language compiler: The DDL compiler converts data definition statements into a set of tables. These tables contain metadata concerning the database. Data Manager: The data manager is the central software component of the DBMS.Its function is to convert operation queries coming from query processor or indirectly or an application program

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL from the users logical view to physical file system. The data manager is responsible for interfacing the file system. File Manager:

It is responsible for the structure of files and managing the file space and also for locating the block containing required record, requesting this block from the disk manager, and transmitting the required record to the data manager. Disk manager: The disk manager transfers the block containing the data requested by the file manager without the concern of physical characteristics of the underlying storage media. Query Processor: The query processor is used to interpret the online users query and covert it into an efficient series of operations in a form capable of being sent to the data manager for execution. It uses data dictionary to find the structure of the relevant portion of the database and uses this information in modifying the query. Data Files: Data files contain data portion of the database. Data Dictionary: A data dictionary is a file that contains metadata. i.e. data about data. This file is consulted before actual data is read or deleted in the database system.

Different types of Keys: Attribute: An object or an entity is characterized by its properties or attributes, they can also be referred as field. 1. Primary key: An attribute to identify a record uniquely without allowing any null values to be entered into it is called Primary key. Ex: empno attribute in the employee table and deptno attribute in dept table. 2. Foreign key: An attribute which is a primary key in its own table and is used as a reference in another table is called foreign key. 3. Super Key: A primary key with a combination of other attributes for unique identification is called super key. In other words primary key is a minimum super key. Ex: Empno along with ename is super key. Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

4. Candidate Key: The super key for which no proper subset is a super key such a minimal super key is a candidate key. Ex: Ename is a candidate key.

STRUCTURED QUERY LANGUAGE (SQL)

SQL is the official standard language used to access data held in the databases. SQL organizes data as tables , indexes , views etc. SQL is the tool for organizing , managing and retrieving data stored in the database. SQL provides various features like portability , client-server architecture ,dynamic data definition , multiple views of data etc. SQL Statements: SQL statements are divided into 1. Data Definition language(DDL) 2. Data Manipulation Language(DML) 3. Data Control Language (DCL) 4. Transaction Processing Language (TPL) 5. Data Retrieval Language (DRL) Data Definition Language (DDL): These statements define the structure of DDL consists of create, alter and drop statements.

the database.

Data Manipulation Language (DML): These statements are basically required to manipulate the records of the tabled consists of insert, delete, and update statements. Data Control Language (DCL): These statements are basically required to control the tables among several users by giving access or by taking back the access to the tables. DCL consists of grant and revoke statements. Transaction control language (TCL): These statements are basically related to various transactions like insert, delete, and update. Data retrieval language (DRL): These statements are basically required to retrieve the records for the table. DRL consists of select statements. Data types in SQL: 1.Varchar2(size): It is a variable length string with a max length of size bytes. 2. Char (size): Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL It specifies a fixed length character string. Max size is 255 3. Number (n): It specifies integer type of data with max of n digits. 4.Number(p,s): It specifies floating number with p as total no of digits and specifies the number of digits to the right of decimal points. 5. Date: It specifies the date in DD-MM-YY format. Data definition language (DDL): Create statement: It is used to create and define a table. Syntax: Create table <table name> (<field-name1> <data type> [column constraints], <field-name2> <data type> [column constraints], . . . <field-name n> <data type> [column constraints]) ; Column constraints : 1. 2. 3. 4. Primary Key: It will not allow null and duplicate values corresponding to that column. Not Null : It will allow null values corresponding to that column Unique: It will not allow duplicate values corresponding to that column. Check: It will impose the constraints based on the condition being mentioned on the column. 5. Reference( foreign key): It will impose the constraints based on the condition being mentioned on the column 6. Reference (foreign key): It will refer to other column values that are acting as primary key in other table. 7. On delete cascade: It will delete the values in the column in one table, corresponding values in other table will be deleted automatically, and it will work only references only. Example 1: Create a table employee with employee no as primary key, name field not be left empty, salary greater than 2000,job field not to be left empty,deptno is foreign key taken from dept table.

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

Example 2: Create dept table with deptno as primary key and dept name as not null. SQL>Create table Dept (Deptno number(3) primary key, Dname varchar2(10) not null); Example 3: Create a customer table. SQL>Create table Customer (Cust_id number(5) primary key, First_name varcahr2(20) not null, Last_name varchar2(20) not null, Address varchar2(40), City varchar2(20), State varchar2(20), Phone_no number(9) unique); Table Level Constraints: Imposing constraints after declaring all the columns of the table, then we call it as table level constraints. Example 4: Create project table. SQL>Create table Project (Emp_id number(5), Proj_id number(5), Payment number(8), Primary key(Emp_id,Proj_id); Create with Select:

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL To create a table from taking the records from existing table. When creating a table based on existing table then it is going to transfer only not null constraint, other constraints will not be transferred. Example 1: SQL>Create table Emp As select Empno, Ename, Salary from Employee; Create with select using where clause: Example 2: Create a table empno containing the details in deptno 10 only SQL>Create table Empd As select * from Employee Where deptno=10; Alter Statement: It is used to alter the definition of a table in the database Syntax: Alter table<table_name> Add column_name data_type <column_constraint> [Modify column_name data_type <column_constraint>]; Add: is used when ever you want to add a new column to the table. Example 1: Adding Phno as a new field into Employee table SQL>Alter table Employee Add(Phno number(7)); Example 2: Adding empno as primary key to Emp table SQL>Alter table Emp Add(Primary key(empno)); Modify: is used to change the size of the column of the same data type.Modify will not decrease the column size.Whenever it comes to increase in the size of column it is going to allow only when the field is empty. Example 1: Modify the salary field by increasing its size. SQL>Alter table Emp Modify(sal number(9,2)); Droping the Constraints: Example1: Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Dropping Primary key constraint we must see that no references are there from other tables. SQL>Alter table Emp Drop Primary key; Drop command: is used to drop the table. Syntax: Drop table<table_name>; Example 1: Dropping emp table. SQL>Drop table emp; Describe command: is used to display the structure of the table.Desc can also be used

Data Manipulation Language (DML): Insert command: is used to add rows(or records) to the table. The number and sequence should match that of columns in the table.If the number of data values is less, then specify the column names into which data is being entered. To insert null values, NULL can be used. Syntax: Insert into<table_name>values(datavalue_1,..,datavalue_n); Insert into<table_name>(column_1,column_3) Values(datavalue_1,datavalue_3); Example 1: Insert 100th record into employee table.

SQL>insert into employee Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Values(100,James,6000,17-Mar-03); Example 2: Inserting 101th record into employee table with salary and date Of joining as null values. SQL>Insert into employee Values(101,James,null,null); Example 3: Inserting 1001th record into employee table with only empno and name. SQL>Insert into employee(empno,ename) Values(1001,John); Insert with select: is used to transfer the data from one table to another table. Syntax: Insert into<table_name> Select <field_name_1>,<field_name_n> from <table_name> Where<condition>;

Example 1: SQL>Insert into emp Select empno,ename,sal from employee Where deptno=10; Delete Command: is used to delete the records from the specified table. Syntax: Delete <table_name> Where<condition>; Example 1: Deleting the employee holding empno1001 SQL> Delete employee where empno = 1001; Example 2 : Delete all the records of the employee table SQL> Delete employee; Example 3: Delete the employees who are working as clerks. SQL> Delete employee where job =clerk Update command: is used to modify the records of the table Syntax: Update <table_name> Set <field_name> = <value> , . . . Where <condition> ; Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

Example1: Increase all the employees salary by Rs. 500 SQL> update employee set sal=sal+500; Example2: Give an increment of 20% salary and commission by 5%of salary SQL> update employee set sal = sal* 1.2, comm = (sal* 0.05) +comm; Example3: Promote the manager as director of the company SQL> update employee set job =director where job= manager; Example4: Give an increment of 10% salary whose salary is less than Rs. 1000 SQL> update employee set sal = sal*1.1 where sal <1000; Transaction control language(TCL); The DML transactions will not be saved implicitly based on the following reasons. 1. Improper shut down 2. System crash 3. When working under SQL environment DML transactions will not saved. To handle DML transactions explicitly we require a set of commands which are commit, roll back and save point. Commit command: is used to save all the transactions up to the last command explicitly. SQL> insert into employee( empno, ename) values (200, smith); SQL> commit ; Roll back command: is used to undo the transactions up to the last commit. SQL> Rollback; Savepoint: is used to minimize roll back only to certain transactions Example: SQL> insert SQL> savepoint ins; SQL> update . SQL> savepoint upd SQL> delete . SQL> savepoint del; SQL> Rollback; SQL> commit; SQL> Rollback to del;(Once you commit and then give rollback, will remove all save points) Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

Autocommit command: is used to make all DML transactions to save implicitly after the execution of the command. SQL> set autocommit on; SQL> set autocommit off; To see the status of autocommit we use show command. SQL> show autocommit; Data Retrieval language(DRL); Select command: is used to retrieve the records from the table. Syntax: Select < field_name_1>, .. , <field_name_n> from <table_name> where <condition> ; 1:

Example

To

display

the

deptno,dname,loc.

Example 2: To display all the employee details,who are working as manager. SQL>Select * from emp where job-manager; Logical Operators: And Or Not Example 1: To display the employee information who are working in deptno 10 and salary greater than 2000. SQL>select * from emp Where deptno=10 and sal>2000; Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Example 2: To display the employee information who are working as manager corresponding to deptno 20. SQL>select * from emp Where job=manager and depno=20; Example 3: To display the employee information who are working in deptno 10,20. SQL>select * from emp Where deptno=10 or dept=20; Example 4: To display the employee information who are working as managers corresponding to deptno 10 as well as the employees who are receiving salary more than 2000 corresponding to deptno 20. SQL>select * from emp Where job=manager and deptno=10; Special Operators: Is null In Between like is null: is used to check the null values corresponding to the column. Example 1: To display the employee information who are not receiving any commission. SQL>select * from emp Where comm Is null; Between: Whenever we want to frame the condition in the range of values then we use the between operator. Example1: To display the employee information whose salary is greater than 1000 and less than 2000. SQL>select * from emp Where sal between 1000 and 2000; Example 2: To display the employee information for those who are working for deptno 10 with their first alphabet of the name is coming in the range of e to j. SQL>select * from emp Where deptno=10 and(ename between E and J); In: When you have multiple conditions among which any one has to be selected we use in operator. Example 1: To display the employee details who are working as managers ,clerks ,analyst. SQL>select * from emp Where job in(manager,clerk,analyst); Example 2:To display the employee who are working in the deptno 10,20,30. Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL SQL>select * from emp Where deptno in (10,20,30); Like: is used when you want to frame a condition based on a particular pattern, for which we need wild card characters, which are % and _. % is used to replace any no.of characters in the pattern. _ is used to replace only single characters in the pattern. Example 1: To display the employee details whose names are ending with s. SQL>select * from emp Where ename like%s; Example 2: To diplay the employee names have onlay 5 characters. SQL>select * from emp Where ename like_____; Example 3: To display the employee details whose name has a as second character and r as last character. SQL>select * from emp Where ename like_a%r;

Special operators with not: Example1: To display the employee information who are receiving any commission. SQL>select * from emp Where comm. Is not null; Example 2:To display employee information for whose who are working as managers and receiving salary other than the range 2000 to 3000. SQL>select * from emp Where job=manager and sal not between 2000 and 3000; Example 3:To display the employee details who are working in dept other than 20,30. SQL>select * from emp Where deptno not in (20,30); Example 4:To display the employee details who are working in deptno 10,20 for their names not ending with s. SQL>select * from emp Where deptno in(10,20) and ename not like %s;

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

In built functions: Are classified into five types o o o o Number Functions Character Functions Date functions Group functions

Group Functions: 1. Sum(expr) 4.count(*) 2. avg(expr) 5. Max(expr) 3. count(expr) 6. min(expr)

1. Sum(expr): Is used to find total sum of the attribute or field mentioned. Example 1: Find the sum of total salary being paid to all the employees of the organizations. SQL>select sum(sal) from emp; Example 2: Find the sum of salary and commission paid to the employees of deptno 10. SQL>select sum(sal+comm.) from emp Where deptno=10; 2. avg(expr): Is used to find the average of the attribute being mentioned. Example: Find the average amount salary being paid to each employee. SQL>select avg(sal) from emp;

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL 3.Count(*): Is used to count the no.of records in the table,where the also counted. Example 1: find the no.of employees working in the organization. empty record is

SQL>select count(*) from emp; Example 2:find the no.of employees working as managers and clerks in the organization. SQL>select count(*) from emp Where job in(manager,clerk); 4.count(expr): Is used to count the no.of records will the expr is satisfied.If a record has a null value it will not count that record. Example 1: Find the no.of employees who are receiving the commission. SQL>select count(comm.) from emp; Example 2: Find the no.of employees who are receiving the commission corresponding to deptno.10,20. SQL>select count(comm) from emp Where deptno=10 or deptno=20; 5.max(expr): Is used to find the maximum value for the mentioned numerical attribute. Example 1: Find the employees who is paid the highest salary. SQL>select max(sal) from emp; 6.min(expr): Is used to find the minimum value attribute. Example: find the employees who is paid the least salary. SQL>select min(sal) from emp; for the mentioned numerical

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

Numerical Functions: abs(n) sqrt(n) power(n) mod(n)

1.abs(n): Is used to find the absolute value of n.dual is dummy table for Temporary manipulation. SQL>select abs(-5) from dual; 2.sqrt(n): Is used to find the square root of n. SQL>select sqrt(36) from dual; 3.power(n): Is used to find the value of m to the power of n. SQL>select power(3,2) from dual; 4.mod(m,n): Is used to find the remainder after dividing m by n. SQL>select mod(5,2) from dual;

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

CHARACTER FUNCTIONS: Length(str) Concate(str1,str2) Substr(str,pos,n) Ascii(char) Chr(n)

1. length(str): Returns the length of the string mentioned. SQL>select length(student) from dual; 2. concat(str1,str2): Joints string1 and string2 ot form a new string. SQL>select concat(aaaa,bbbb) from dual; 3. substr(str,pos,n): Returns the substring from the string from position pos cut n characters. SQL>select substr(student,3,4) from dual; 4. ascii(char): Returns the ascii value of the mentioned character. Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL SQL>select ascii(a) from dual; 5.chr(n): Returns the character for the ascii value n mentioned. SQL>select chr(68) from dual; 6.lower(str): Converts the given string into lower case. SQL>select lower(AAAA) from dual;

8. upper(str): Converts the given string into upper case. SQL>select upper(dddd) from dual; Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL DATE FUNCTIONS: 1. add months(date,n): system date. To add or remove given n months to the given data.Sysdate gives the

SQL>select sysdate from dual; SQL>select add_month(sysdate,3) from dual; 2. months between(date1,date2): Returns the no.of months between the two dates mentioned.Date1 is maximum value and date2 is minimum value.The output of this function is either float or integer value. SQL>select dual; months_between(29-oct-03,29-apr-03) from

3. Last day(date): Returns the last day in the month specified by the date mentioned. SQL>select last_day(sysdate) from dual;

Group by clause: Is used to group a set of repeated values corresponding to a particular column for which we want to apply group function. Example 1: To display the deptno. And total salary in each dept.

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL SQL>select deptno,sum(sal) from emp Group by deptno; Example 2: To display the depts highest,lowest salary and no.of employees in each dept. SQL>select emp group by deptno; deptno,max(sal),min(sal),count(*) from

Example 3: To display the no.of employees receiving commission corresponding to deptno 10,20 with their deptno. SQL>select deptno,count(comm.) from Emp where deptno=10 or deptno=20 Group by deptno;

Having Clause: Is used when we want to frame the condition of salary is greater than cannot be used with where clause. Example 1: To display the deptno.s for which total amount of salary is greater than 10,000. SQL>select deptno,sum(sal) from emp Group by deptno Having sum(sal)>10000;

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Example 2: To display the deptno.s along with their total salary for which total salary is greater than 10,000 corresponding to deptno 10,20. SQL>select deptno,sum(sal) from emp Where deptno in (10,20) Group by deptno Having sum(sal)>10000; Example 3 : To display the jobs along with the no.of employees working ,provided the highest salary corresponding to the job is greater than 3000 as well as the no.of employees working is more than 3. SQL>select job,count(*) from emp Where deptno in (10,20,30) Group by job Having max(sal)>2000 and count(*)>2;

Order by clause: Is used when we want to display the data in a sorted order. 1. Ascending order |asc| (default ordering) 2. Descending |desc| Example 1: To display the employee information in the ascending order of the empno. SQL> select * from emp Oreder by empno; Example 2: To display the employee information in the descending order of the salary. SQL>select * from emp Order by sal desc; Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

Example 3: To display the employee information in the ascending order of the deptno,descending order of salary. SQL>select * from emp Order by deptno,sal desc; Example 4: To display the depts along with their total payment corresponding to deptno 10,20,30 for which n0.of employees are working is more than 2 and display based on the descending order of total salary. SQL>select deptno,sum(sal) from emp Where deptno in (10,20,30) Group by deptno Having count(*)>2 Order by sum(sal) desc;

SET OPERATORS: Union Intersection Minus

1. union: Is used to take distinct rows from more than one select statement.By using union all the duplication is not removed. Example 1: To display in deptno the jobs. 10 or 20. SQL>select job from emp Where deptno=10 Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Union Select job from emp Where deptno=20; Example 2: To display the jobs from emp. SQL>select job from emp Where deptno=10 Union all Select job from emp Where deptno=20; 2.intersect: Is used to take common rows from more than one select statement. Example 1: To dispalyb the jobs in deptno. 10 and 20. SQL>select job from emp Where deptno=10 Intersect Select job from emp Where deptno=20; Example 2:To disaply the jobs in deptno. 10 and (20 or 30). SQL>select job from emp Where deptno=10 Intersect (select job from emp Where deptno=20 Union Select job from emp Where deptno=30); 2. minus: Is used to select the rows from more than first select statement which are not in the second statement. Example 1: To display the jobs in deptno.10 and not in 20. SQL>select job from emp Where deptno=10 Minus Select job from emp Where deptno=20; Example 2: To list the jobs which are unique to dept 10 as compare to 20 and 30. SQL>(select job from emp Where deptno=20 Union Select job from emp Where deptno=30) Minus (select job from emp Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Where deptno=10);

SUB QUERIES: when we are using more than one select statement to perform particular operation then we will be calling it as a subquery.In subquery the inner statement will be executed first and only noce as compared to the outer statement. Syntax: select ----------From<table name> Where(select ------);

Example 1: To display all the employees information whose salary is greater than Smiths salary. SQL>select * from emp Where sal>(select sal from emp Where ename=SMITH); Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Example 2: To display all the employees information who is receiving the highest salary. SQL>select * from employee Where sal=(select max(sal) from emp); Example 3: To display all the employees information whose job is same like Smith at the same time salary greater than Allen. SQL>select * from emp Where job=(select job from emp where ename=SMITH) And sal>(select sal from emp Where ename=ALLEN); Example 4:To display all the employees information who is receiving salary greater than average salary of all the employees. SQL>select * from emp Where sal>(select avg(sal) from emp); Example 5:To display the manager no.alng with the no.of employees working under him should be maximum no.of employees compared with the other members. SQL>select mgr,count(*) from emp Group by mgr Having count(*)=(select max(count(*) from Emp group by mgr); Example 6: To display the employee information under which maximum no.of employees working. SQL>select * from emp Where empno=(select mgr from emp Group by mgr) Having count(*)=(select max(count(*) fom emp group by mgr); Example 7: To disaply all the employees information who is receiving the second highest salary. SQL>select * from emp Where sal=(select max(sal) from emp where Sa<(select max(sal) from emp)); When the subquery is returning more than one value to frame the condition we have to use all or any. Example 8: To display the employee information whose salary is greater than all the employees salaries of deptno 20. SQL>select * from emp Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Where sal>all(select sal from emp Where deptno=20);

Views: Views can be defined as a virtual table because it doesnt exist by itself,unless you are having one or more ordinary table on which it will be based or dependent.The table on which view is based is called as base table of the view.It is possible to insert,update and delete the data in the view in the same way as in the table. Advantages of views: Providing the security for the table. By giving limited access to your table to other users. Complicated queries can be generated by using views a normal simple table creation.

Creation of view: Syntax: create view <view name> As select ------ from <table name>;

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

Example 1: To create a view for emp table with empno,name,salary. SQL>craerte view empview As select empno,ename,sal from emp; Example 2: To create a view for emp table for dept 10. SQL>create view d10view As select * from emp Where deptno=10;

Insert into view: Example 1: Insert a new record into view empview. SQL>insert into empview Values(101,WILLIAM,2000); Viewing the contents of d10view: Example: To display the contents of d10view. SQL>select * from d10view;

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL

Replace: Replace option is used whenever you want to over write the existing select statement with new select statement. Example: To create empview with empno,name,salary and deptno. SQL>replace view empview As select empno,ename,sal,deptno from emp; With check option: When ever you want to restrict the user to insert thr records which are satisfying the where condition of the view then we use with check option. Syntax: create view <view name> As select-----from <table name> Where <condition> With check option; Example : create a view for employee details of deptno. 20 SQL>create view d20view As select * from emp Where deptno=20 With check option; If you try to enter deptno other than 20,it will not be accepted into the view.

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Sequences: Whenever you want to create a object which is going to generate the numbers in a particular order (i.e. interval) then we will be calling a sequence. Syntax: create sequence <seq.Name> Start with <no.> Increment by <interval> Maxvalue <n> Minvalue <n> Cache Cycle; Whenever you want to generate the next number of the sequence then we will be using nextval and when you want to see the current position of the sequence we use currval. Example: SQL>create sequence eno Start with 5 Increment by 1 Minvalue 5 Maxvalue 15 Cache 5 Cycle; This is going to create a sequence with name eno starting with 5,incrementing by 1,minimum value is 5,maximum value is 15,cache is 5 and with cycle. Altering the sequence: whenever you want to change any options related t To existing sequence then we will be using Alter. Note:start with cannot be changed using Alter. Syntax: alter sequence <seq.name> <options to be changed>; Example: SQL>alter sequence eno Increment by 2 Minvalue 10 Maxvalue 100; Drop sequence: Whenever you want to drop a sequence we use drop statement. Syntax: drop sequence <seq.name> Example: SQL>drop sequence eno; INDEX: Whenever you to retrieve the records faster corresponding to one condition then we will be using Indexing concept. Before going to index,identify the fields which will be using mostly in the where clause then indx on those fields.Apply index when there are more than 500 records are present in a table. There are 3 types of indexes Simple index, Unique index and Concatenated index. Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE

Introduction to DBMS fundamentals, SQL Syntax: SQL>create index <index name> on <table name>(<field name>); 1. Simple index: Is used when indexing is based on the column of the table. Example 1: SQL>create index idept on emp(deptno); Example 2: SQL>create index iename on emp(ename): 2. Unique index: Is used when indexing is based on implementing unique constraint along with indexing. Example : SQL>create unique index iph on emp(phno); 3. concatenated index: combination. Is used when indexing is based on more than one column as a

Example: SQL>create index ds on emp(deptno,sal); Delete index: drop statement is used Example: SQL>drop index idept;

Ayaz Ahmed Shariff K, Asst. Professor (Senior Grade), BITIC-RAK-UAE