* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Relational Database Mgmt.System
Survey
Document related concepts
Oracle Database wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Clusterpoint wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Functional Database Model wikipedia , lookup
Relational algebra wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Transcript
What is DBMS ? A collection of interrelated and persistent data Goal of DBMS is to provide an environment to Retrieve and Store data Designed to Manage Large Bodies of Information. This involves – – – – Data Modeling Query Processing Security Concurrency control Types of Database Systems Relational Data and relationships are represented by a collection of tables Each table has a no. of columns with unique names Network Database Management System Database System Data are represented by collections of records Relationships among data are represented by links Organization is that of an arbitrary graph Hierarchical Database System Similar to Network model Organization of the records is as a collection of trees, rather than arbitrary graph Codd’s Rules The most popular data storage model is the relational database, which grew from the seminal paper "A Relational Model of Data for Large Shared Data Banks," written by Dr. E. F. Codd in 1970. SQL evolved to service the concepts of the relational database model. Dr. Codd defined 13 rules, oddly enough referred to as Codd's 12 Rules, for the relational model: 0. A relational DBMS must be able to manage databases entirely through its relational capabilities. 1. Information rule-- All information in a relational database (including table and column names) is represented explicitly as values in tables. Codd’s Rules... 2. Guaranteed access--Every value in a relational database is guaranteed to be accessible by using a combination of the table name, primary key value, and column name. 3. Systematic null value support--The RDBMS provides systematic support for the treatment of null values (unknown or inapplicable data), distinct from default values, and independent of any domain. 4. Active, online relational catalog--The description of the database and its contents is represented at the logical level as tables and can therefore be queried using the database language. Codd’s Rules... 5. Comprehensive data sublanguage--At least one supported language must have a well-defined syntax and be comprehensive. It must support data definition, manipulation, integrity rules, authorization, and transactions 7. Set-level insertion, update, and deletion--The RDBMS supports not only set-level retrievals but also setlevel inserts, updates, and deletes. 8. Physical data independence--Application programs and ad hoc programs are logically unaffected when physical access methods or storage structures are altered. Codd’s Rules... 9. Logical data independence--Application programs and ad hoc programs are logically unaffected, to the extent possible, when changes are made to the table structures. 10. Integrity independence--The database language must be capable of defining integrity rules. They must be stored in the online catalog, and they cannot be bypassed. 11. Distribution independence--Application programs and ad hoc requests are logically unaffected when data is first distributed or when it is redistributed. 12. Nonsubversion--It must not be possible to bypass the integrity rules defined through the database language by using lower-level languages. RDBMS A relational database is a collection of relations or two-dimensional tables Manipulate relational databases a set at a time rather than a record at a time. Eg. Select all employees who work in department 30 Advantages of RDBMS Redundancy can be reduced Inconsistency can be avoided Data can be shared Standards can be enforced Integrity can be maintained Concurrency can be controlled DBMS vs. RDBMS DBMS No relationship between the tables No transaction control support e.g. COMMIT & ROLLBACK No Crashrecovery on database crash RDBMS Relationship between tables supported Transactions can be controlled easily Crashrecovery possible on database crash Entity Relationship Modelling Identify the basic entities in a business scenario to capture important data Read and explain an Entity-Relationship diagram that captures business data List and define basic kinds of data relationships Define normalization and explain it’s benefits Entity Relationship Model EMPLOYEE DEPARTMENT #*NUMBER *first name *last name *hire date o salary o job #*number Assigned to Responsible for *name *location Advantages of E-R Model E-R model documents an organization’s information requirements in a clear and precise manner User’s can easily understand the pictorial form of an E-R model An E-R model can be easily developed and refined It provides an effective framework for integrating multiple applications. An Find Categories of Data In an effective business system, data are divided into discrete categories or entities.An entity is a “thing of significance” about which information needs to be known. Attributes describe entities and hold the specific pieces of information that need to be known about the entity. Entity Diagram Entity diagrams provide a formal,concise means for recording information about entities Entities are always shown UPPER case. eg. EMPLOYEE #*number *first name *last name o job DEPARTMENT #* number *name *location Kinds of Relationships One to One Relationships Many to One Relationships Many to Many relationships Denotes optional relationship One to One Relationship It has a degree of one and only one in both directions MICROCOMPUTER The host for Incorporated into MOTHERBOARD Each MICROCOMPUTER must be the host for one and only one MOTHERBOARD Each MOTHERBOARD may be incorporated into one and only one MICROCOMPUTER Many to one Relationship It has a degree of one or more in one direction and one and only one in the other direction ORDER Given by May give CUSTOMER Each ORDER must be given by one and only one CUSTOMER Each CUSTOMER may give one or more ORDERs Many to Many Relationship It has a degree of one or more in both directions ORDER Have Allocated to ITEM Each ORDER may HAVE one or more ITEMs Each ITEM may be allocated to one or more ORDERs Attributes Attributes are information about an entity that needs to be known or held Attributes describe an entity by qualifying ,identifying,classifying,quantifying or expressing the state of the entity Attributes are always represented in LOWER case in an E-R diagram Attribute- Examples EMPLOYEE COURSE code code first name name last name duration hiredate fee salary hiredate Attribute - Facts Each attribute should have a single value for each entity instance.A repeated attribute indicates a missing entity An attribute should not be derived or calculated from the existing values of other attributes eg (totals,counts etc.). Do not include derived attributes in an E-R model as derived attributes are redundant. Types of Attributes Identify each attribute’s optionality using an attribute tag Mandatory Attributes A value must be known for each entity occurrence The attribute name is tagged with * Optional Attributes A value maybe known for each entity occurrence • The attribute name is tagged with o Assign Unique Identifier A unique identifier (UID) is any combination of attributes and/or relationships that serve to uniquely identify an occurrence of an entity.Each entity occurrence must be uniquely identifiable eg. DEPARTMENT #*number *name The UID for the entity DEPARTMENT is the attribute number Facts about UID An entity must have a UID or it is not an entity An entity may have more than one UID.In this case select one candidate UID to be the primary UID and the others to be secondary UIDs. Integrity Rules Define primary keys and foreign keys Protect data integrity Translate any ER-data model into a relational database design Integrity Constraints PRIMARY KEY FOREIGN KEY UNIQUE NOT NULL CHECK Primary Key A primary key is a column or a set of columns that uniquely identifies each row in a table. Each table must have a primary key and the primary key must me unique. No part of the primary key may be null ie. no part of a primary key may lack a value. A primary key consisting of multiple columns is called a composite primary key or a compound key. A table can have several candidate keys.A candidate key is a column or a combination of columns that can serve as the primary key for the table where both should be independently unique and not null. Primary Key- Examples Composite primary key Bank No. Account No. Balance Date_opened 104 75760 12,000.50 21-OCT-89 105 77956 100.10 103 89570 55,775.00 15-JAN-85 105 55890 15,001.90 25-SEP-91 The columns of a composite primary key must be unique in combination,although individual columns can have duplicate values. Primary Key - Examples Primary key Alternate key Id. Name Dept_Id Payroll_id 1 Scott 50 9710 2 Martin 30 8730 3 Michael 50 1157 4 George 40 3394 All candidate keys must be unique and NOT NULL individually Foreign Keys A foreign key is a column or a set of columns in one table that refers to a primary key in the same table or another table They are used to combine information from different tables They are purely logical and not physical pointers as they depend on data values A foreign key value must match an existing primary key value (or else be NULL) A foreign key that is a part of a primary key cannot be NULL,since no part of the primary key can be null Foreign Key - Examples Primary key Foreign key Dept_Id EMPLOYEE E Id Name Payroll_id 1 Scott 50 9710 2 Martin 30 8730 3 Michael 50 1157 4 George 40 3394 D Id Name 30 Finance DEPARTMENT Table 40 Sales 50 Operations Table EXAMPLE OF CONSTRAINTS CREATE TABLE emp( id number(5) CONSTRAINT emp_key_pk PRIMARY KEY, name varchar2(15) NOT NULL CONSTRAINT dept_key_unq UNIQUE, salary number(11,2), commission_pct number(4,2) CONSTRAINT emp_comm_pct_check CHECK(commission_pct IN (10,12.5.15)), dept_id number(7) CONSTRAINT emp_fk_dept_id REFERENCES dept(id)); ORACLE DATATYPES CHAR : Fixed length character value of sizes 1-255 VARCHAR2: Variable length character value of sizes 12000 VARCHAR:Same as varchar2 datatype LONG: Similar to varchar2 but max. size is 2GB DATE:Date and time value between Jan 1,4172B.C and Dec. 31,4712 A.D NUMBER(p,s):Number value having a max. precision of p and a maximum scale of s •the precision is the no. of decimal digits •the scale is the no. of digits to the right of the decimal point DDL AND LOGICAL SCHEMA OBJECTIVES Create storage structures(tables) to store data Modify the structure of an existing table Enforce business data integrity by adding and removing constraints Dropping tables CREATING TABLES Produce a data model that includes entities ,attributes and relationships during the analysis stage of system development Document tables,columns,data constraints and sample data with table instance charts(E-R model) CREATE TABLE SYNTAX CREATE TABLE [user.] table_name ({column_name datatype | table constraint}, {column_name datatype | table constraint}……) EXPAMPLE CREATE TABLE dept (id number(5) CONSTRAINT dept_key_pk PRIMARY KEY, name varchar2(15) NOT NULL CONSTRAINT dept_key_unq UNIQUE, location varchar2(15)); Example (CONT’D) Now create a child table(EMP) based on the master table DEPT by enforcing a foreign key CREATE TABLE emp (id NUMBER(10) CONSTRAINT emp_key_pk PRIMARY KEY, name VARCHAR2(30) NOT NULL, salary number(11,2),…….., dept_id NUMBER(5) CONSTRAINT emp_key_fk_id REFERENCES dept(id) ); VERIFYING THE STRUCTURE OF AN OBJECT SYNTAX DESC object_name; DROPPING AN OBJECT SYNTAX DROP object_type object_name; ADD A COLUMN TO A TABLE SYNTAX ALTER TABLE table_name ADD(column_name datatype [,column_name datatype]………) EXAMPLE ALTER TABLE emp ADD(comments VARCHAR2(155)); MODIFY A COLUMN SYNTAX ALTER TABLE table_name MODIFY(column_name datatype [,column_name datatype]………) EXAMPLE ALTER TABLE emp MODIFY(salary NOT NULL); MANIPULATE DATA IN ORACLE TABLES OBJECTIVES Insert data into a table Update existing data in a table Delete data from a table Select data from a table INSERT DATA SYNTAX INSERT INTO table_name [(column1,column2……….) ] VALUES(value1,value2,………..) EXAMPLE INSERT INTO dept (id,name,location) VALUES(60,’PRODUCTION’,’DALLAS’); UPDATE DATA SYNTAX UPDATE table_name SET column1=value,column2=value……… [WHERE condition] If where clause is not given then all the rows will be updated EXAMPLE UPDATE emp SET dept_id=20,salary=3450 where id=4156; DELETE ROWS SYNTAX DELETE FROM table_name [WHERE condition] EXAMPLE DELETE FROM dept where id=70; SELECT STATEMENT Present columns from a database table by listing them in the SELECT clause of the SELECT statement SELECT… : The columns ,expressions or constants to retrieve FROM… : The table from which to retrieve data WHERE… : The rows to retrieve according to criteria ORDER BY… : The sort order by which to display rows DISPLAY ROWS Display specific rows from a table according to a search condition with the WHERE clause SYNTAX SELECT {*|column name [,column name….]} FROM table_name WHERE condition EXAMPLE SELECT * FROM emp WHERE dept_id=10; PROCESS TRANSACTIONS The COMMIT statement makes permanent all the changes performed in the current transaction,tat is , all changes made to the database since last commit The ROLLBACK statement makes the work done in the current transaction undone ADD AND REMOVE DATA CONSTRAINTS EXAMPLE Add a constraint to emp table indicating that a manager must already exist as a valid employee in the emp table ALTER TABLE EMP ADD CONSTRAINT emp_fk_manager_id FOREIGN KEY (manager_id) REFERENCES emp(id); ALTER TABLE emp DROP CONSTRAINT emp_fk_manager_id; SEQUENCES •Sequences generate integer values which are unique •It is useful for on line transactions where all clients use a centralized sequence eg. Railway booking counters •Can be used for generating primary key values. Sequences (CONT’D) SYNTAX CREATE SEQUENCE sequence_name [START WITH n] [INCREMENT BY m] [{MAXVALUE o | NOMAXVALUE}] [{CACHE p | NOCACHE}] EXAMPLE CREATE SEQUENCE dept_id START WITH 10 INCREMENT BY 5 NOCACHE; Sequences ( CONT’D) Reference sequences in INSERT commands to generate unique integer values automatically Sequence_name.NEXTVAL: returns the next available value of sequence Sequence_name.CURRVAL: returns the last value of the sequence obtained by the current user with sequence_name.NEXTVAL.It is undefined for any user session until the user references sequence_name.NEXTVAL at least once USERS & SECURITY OBJECTIVES Control user access to Oracle Server Provide access to database objects(Tables,Views ,Synonyms) Confirm access to database objects Create synonyms for database objects Remove access to database objects from users PRIVILEGES SYSTEM PRIVILEGES (Managed by DBA) OBJECT PRIVILEGES used by the user to provide access to his/her data objects with SQL command GRANT Object privileges include alter,delete,index,insert,references,select, update PRIVILEGES (CONT’D) GRANT SYNTAX GRANT [privilege , privilege…..|ALL] ON object_name TO [user1_name, user1_name…..|PUBLIC] [WITH GRANT OPTION] EXAMPLE GRANT SELECT,INSERT ON emp TO xyz; PRIVILEGES(CONT’D) REVOKE SYNTAX REVOKE [privilege , privilege….] ON object_name FROM [user1_name, user1_name…..|PUBLIC] [CASCADE CONSTRAINTS] EXAMPLE REVOKE SELECT,INSERT On emp FROM xyz; VIEWS •Logically represent subsets of data from one or more tables. •A view does not actually contain data;all data is derived from the underlying table(s) •Useful for security and convenience SYNTAX CREATE OR REPLACE VIEW view_name [(alias, [alias] …..) AS [query] EXAMPLE Views(CONT’D) CREATE OR REPLACE VIEW empview AS SELECT id,last_name,salary FROM emp where dept_id=10; SELECT * FROM empview; For further security reasons the column headings can be controlled by including column aliases within the defining SELECT statement CREATE OR REPLACE VIEW empview AS SELECT id,first_name ||’’||last_name NAME, FROM emp; INDEXES Used primarily to speed up the process of data retrieval The index should be created on a column having the most unique values or the column which is frequently included the the WHERE clause of the SELECT statement. Index is automatically created on the column having the PRIMARY KEY constraint. They are automatically updated when the corresponding column is updated and are dropped when the table is dropped. They can be enabled or disabled explicitly as per the requirements .eg. In case of online processing they can be disabled explicitly Indexes(CONT’D) SYNTAX CREATE INDEX index_name ON table_name(column [,column] …); EXAMPLE CREATE INDEX emp_index ON emp(hiredate); Synonyms(CONT’D) SYNTAX CREATE [PUBLIC] SYNONYM synonym_name FOR table_name; EXAMPLE CREATE PUBLIC SYNONYM emp_synonym FOR emp; COMPARISION BETWEEN VIEWS AND SYNONYMS VIEWS They can be based on one or more tables They are stored objects like tables having a definite structure Users can access views depending on the Grants given by the owner of the view SYNONYMS They are based on only one table They are only canonical names and have no definite structure Users access is limited at the creation time. New Features of Oracle8 •Table Partitions •Object Oriented Features –Define Objects –Define Methods –Support polymorphism –Support inheritance DISTRIBUTED DATABASES •A distributed system is one in which both data and transaction processing are divided between one or more computers connected by a network, each computer playing a specific role in the system. •Replication (insuring that the data at all sites in a distributed system reflects any changes made anywhere in the system) •A distributed database is a set of databases stored on multiple computers that typically appears to applications as a single database. Consequently, an application can simultaneously access and modify the data in several databases in a network Overview of SQL A Brief History of SQL • SQL was first developed in an IBM laboratory in San Jose, California, in the late 1970s. The initials stand for Structured Query Language, and the language itself is often referred to as "sequel.” Features of SQL • English like language. • Non-Procedural language. • Equally used by end users, developer as well as by administrators. Introduction to SQL *Plus SQL *Plus is an Oracle product that supports ANSI-SQL. It acts as a host to SQL commands, additionally it supports • • • • Procedural option of Oracle (PL/SQL) Buffer Commands Script file Commands Formatting commands Starting • • SQL *Plus. Double click on SQL*Plus icon and then key in the username, password and the host string. Username is the name provided DBA, a valid ID to login to the Guidelines for writing SQL Commands. • • • • • • • • SQL • • • An SQL command is entered at the SQL*Plus prompt and the subsequent lines are numbered. Word delimiter is space or tab. Command entry can be in upper case or lower case. Command be of SQL, SQL *Plus or PL/SQL SQL commands may be one line or several lines. Command words cannot be split across lines. Most recent SQL or PL/SQL command is stored in SQL Buffer. Buffer command can be edited or re-executed. Command Entry. SQL commands can be terminated by a semicolon, slash (/) or blank line Commands terminated by a semicolon or a slash are stored in SQL buffer and executed. Commands terminated by a blank line are stored in SQL buffer, but not DESCRIBE Display the structure of the Table, View or Synonym. SQL> describe dept Name Null? Type ------------------------------- -------- ---DEPTNO NOT NULL NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13) SQL> desc emp Name Null? Type ------------------------------- -------- ---EMPNO NOT NULL NUMBER(4) ENAME VARCHAR2(10) JOB SELECT Statement Used to retrieve data stored in database tables and views. SELECT { * | column_name [, column_name …] } FROM Table_name SQL> select * from dept; DEPTNO --------10 20 30 40 DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS LOC ------------NEW YORK DALLAS CHICAGO BOSTON SQL> select empno,ename,job from emp; Column Aliases in SELECT Statement. Used from giving meaning full name to the column heading. By default alias headings cannot contain blank spaces, unless the alias is enclosed in double quotes (“ “) SQL> SELECT ename Employee, sal Salary FROM Emp; EMPLOYEE SALARY ---------- --------KING 5000 BLAKE 2850 CLARK 2450 JONES 2975 MARTIN 1250 ALLEN 1600 TURNER 1500 JAMES 950 WARD 1250 Arithmetic Expression in SELECT statement. An expression is a combination of one or more variables, literal /constants, operators and functions that evaluates to value. An expression may contain column names, literal and the following arithmetic operators. +(addition), - (Subtraction) , * (Multiplication) / (Division), % (Modulus) SQL> SELECT ename, sal * 12 "Annual Salary" FROM Emp; ENAME Annual Salary ---------- ------------KING 60000 BLAKE 34200 CLARK 29400 Concatenation Operator Concatenation operator (||) is used to link columns to other columns, arithmetic expressions or literal to create a character expression. Columns on either side of the operator are combined to make one single column. SQL> SELECT custid "Customer Id", address||', '||city "Address" FROM Customer; Customer Id Address ----------- ------------------------------------------------------------------100 345 VIEWRIDGE, BELMONT 101 490 BOLI RD., REDWOOD CITY 102 9722 HAMILTON, BURLINGAME 103 HILLVIEW MALL, BURLINGAME 104 574 SURRY RD., CUPERTINO Handling Null values A row may have a specific column containing no values, such a column is said to have NULL value. A null value is not equal to zero or space character. A null value occupies 1 byte of space in storage. If column taking part in an expression contains NULL, result of that expression evaluates to NULL. For example, when ever COMM column contains null, the expression (sal * 12 ) + comm results in NULL. SQL> SELECT ename, sal * 12, comm, (sal * 12) + comm FROM Emp; ENAME SAL*12 COMM (SAL*12)+COMM Continue.. NVL function provides facilities to handle NULL values. SQL> SELECT ename, sal * 12, comm, (sal * 12) + NVL(comm,0) FROM Emp; ENAME SAL*12 COMM (SAL*12)+NVL(COMM,0) ---------- --------- --------- ------------------KING 60000 60000 BLAKE 34200 34200 CLARK 29400 29400 JONES 35700 35700 MARTIN 15000 1400 16400 ALLEN 19200 300 19500 DISTINCT Clause. Using ‘DISTINCT’ clause we can eliminate duplicate rows. For example, try and see the output of the following queries. SQL> SELECT deptno FROM Emp; DEPTNO --------10 30 10 20 30 30 30 Sorting Query Results By specifying ORDER BY, the data results are presented in a sorted order. The ordering can be done in ascending or in descending order. Default is ascending. Order by clause must be the last clause in the SELECT statement. While ordering in ascending order • • • • NULL values appear at the end. Numeric values appear with the lowest values first. Date values appear starting from the earliest date. Character values appear alphabetically. (Capital letters first then small letters) SQL> SELECT empno, hiredate FROM emp ORDER BY hiredate; Sorting Result on Multiple Columns When multiple columns are specified, the rows are sorted according to the values of the first column. Rows with repeating values for the first column are then sorted on the second column and so on. For example, to display the names of the employees in descending order within every job in ascending order, the query will be SQL> SELECT job, ename FROM Emp ORDER by job, ename DESC; JOB ENAME --------- ---------ANALYST SCOTT Summary. SQL is the language used by RDBMS to enable users to access data. SQL *Plus is an Oracle product which supports ANSI-SQL. Using DESCRIBE (in short DESC) we can see the structure of the tables in the database. SELECT statement is used to retrieve data from the tables, the full syntax is WHERE Clause For your queries to be more selective you should use WHERE clause. The condition specified with the WHERE clause acts as a filter and returns only those rows that satisfy the condition. Syntax SELECT … FROM.. WHERE condition(s). For example, to display details of all employees from Emp table who are working as salesman. The Continue.. Comparison operators are categorized as Logical Operator SQL Operator Logical Operators. Following is the table of Logical operators. Operator = > >= < <= != , <> SQL> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not Equal to SELECT ename, sal FROM Emp WHERE sal < Continue... Constants used in the WHERE clause can be compared with valid Oracle column types Character and Date constants must be enclosed in single quotation. For Example, to display information of employees joined after ‘15-Dec-1982’, the query is SQL> SELECT ename, hiredate FROM Emp WHERE hiredate > '15-DEC-82'; ENAME HIREDATE ---------- --------ADAMS 12-JAN-83 SQL Operator Following are the four SQL Operators Operator Meaning Between .. AND.. IN (list of values) LIKE IS NULL Between lower value and upper value, both inclusive Matching any of a list of values Matching any of a list of values is a null value Between .. AND .. Operator. Between is used in such situations where you required to retrieve data that lies within a range of values. Both the values (lower and upper) are inclusive. For example, to see the employees whose date of IN Operator Used to retrieve data based on a given list of values. IN operator is much efficient that OR operator (which is Covered later) Consider a situation in which you need to retrieve the names of all employees who works as Analyst or Salesman. The following query would do. SQL> SELECT ename, job FROM IN ('ANALYST','SALESMAN') ENAME ---------MARTIN ALLEN JOB --------SALESMAN SALESMAN Emp WHERE job LIKE operator Used to retrieve similar data from table by matching a portion of a data with a specific value For matching a portion of a data we use wild char characters. The following list the wild card characters and the meaning. Wildcard % _ For Meaning Matches any number of characters Matches any one character example, to retrieve data of employees whose name start with ‘S’, you can use following query. IS NULL operator To check whether the value is NUL, neither IN operator nor not the equality operator can be used. For that IS NULL operator is required. E.g To check out employees who did not earn any commission, use the following query. SQL> SELECT ename FROM Emp WHERE comm IS NULL; ENAME ---------KING BLAKE CLARK JONES JAMES NOT operator NOT is used to negate a condition. They are used with all Logical operators and SQL Operators, like NOT = Same as <>, != NOT <= Same as > NOT > Same as <= NOT BETWEEN Not between the range NOT IN Not in the list NOT LIKE Not matching the pattern IS NOT NULL is not a null value Compound conditions AND and OR operators may be used to make compound logical expressions AND predicate expects both condition to be TURE OR predicate expects either condition to be TURE For example, to find all salesmen who earn 1250, the query would be: SQL> SELECT empno, ename, job, sal FROM Emp WHERE sal = 1250 AND job = 'SALESMAN'; EMPNO --------7654 7521 ENAME ---------MARTIN WARD JOB SAL --------- --------SALESMAN 1250 SALESMAN 1250 Summary WHERE clause in used to select only the required rows. Comparison operators are categorized to Logical Operators and Sql operators. Logical SQL operators are =, >, <, >=, <=, !=, <> operators are BETWEEN…AND.., IN, Functions. Functions are used to manipulate data and summarize query results. You can pass one or more arguments to functions. They will return only one value as a result. Arguments are passed to functions which could be a user-supplied constant, variable or columns. Typically, you would use the functions to; • • • • • • Manipulate numeric and character values. Convert values of one datatype into values of another datatype. Modify individual data item. Format data Alter data format for display Summarize query results. Single Row Functions It is important to note that you can use SQL functions in the queries either with the columns in the select list or with the WHERE clause of the SELECT statement. The format for a function is follows. Function Purpose Examples Character Manipulate values character data types Conversion Converting values of one data TO_CHAR, TO_DATE, type to another TO_NUMBER of UPPER, LOWER, LENGTH, SUBSTRING SELECT function (column or constant),…. FROM Numeric Manipulating values of ABS, TRUNC, ROUND numeric data types table_name Date Manipulate values of date SYSDATE, ,LAST_DAY data types operator condition)] [WHERE function(column Single row functions are divided into the following types, depending upon the datatype on with they Character Functions UPPER (column/values). Converts all alphabetic values into uppercase. To display product numbers along with their names in uppercase the query is SQL> SELECT 'Product No '||prodid||' belongs to '||upper(descrip) FROM Product; 'PRODUCTNO'||PRODID||'BELONGSTO'||UPPER(DESCRI P) -----------------------------------------------------------------------------Product No 100860 belongs to ACE TENNIS RACKET I Product No 100861 belongs to ACE TENNIS RACKET II Product No 100870 belongs to ACE TENNIS BALLS- Number Functions Number functions expect numeric input and return numeric values. Few functions are discussed bellow. ABS(n). Returns the absolute value of a number. SQL> SELECT abs(100), abs(-100) FROM Dual; ABS(100) ABS(-100) --------- --------100 100 ROUND(n,[m]) returns n rounded to m places right of the decimal point, if m is omitted, then n is rounded to 0 places. Date functions Date functions operate on values of the DATE data type. Oracle stores dates in numeric format internally representing • • • • • • • The Century Year Month Day Hours Minutes Seconds. default format for date is dd-mon-yy. The range of dates Oracle offers is between 1 Jan Continue…. It is possible to perform arithmetic operations on date. • • • • date + number date - number date - date date + date Certain date functions are discussed below. ADD_MONTHS(d,n). • • • Returns the date d plus n months. The argument n can be any integer. If d is the last day of the month or if the resulting month has fewer days than the component of d, then the result is the last day of the resulting month. For example to determine 5 months before Jone’s Continue... MONTHS_BETWEEN(d1, • • • d2): Returns number of months between the dates. If d1 is later than d2, the result is positive else negative. If d1 and d2 are either the same days of the month, or the last days of months, the result is always an integer, other wise a fractional portion of the result based on a 31-month is given. For example to calculate the No of months an employee worked for, the following query is used. SQL> SELECT ename, round(months_between (sysdate, hiredate)) FROM Emp; ENAME ROUND(MONTHS_BETWEEN(SYSDATE,HIREDATE)) ---------- -------------------------------------KING 212 Conversion Functions. Conversion functions convert a value from one data type to another . Oracle provides the following 3 conversions functions. • TO_NUMBER(char): – Converts char string to number. • TO_CHAR(number|date,[fmt]): – Converts number or date to character format fmt. • TO_DATE(char, fmt): – Converts the character value, representing date, into a date values according to the fmt specified. If fmt is omitted, it will default to ‘DDMON-YY’. Continue... E.g. Using TO_NUMBER SQL>SELECT empno, hiredate FROM Emp WHERE empno > to_number(substr('7782clark', 1,4)); EMPNO HIREDATE ---7788 7839 7844 7876 7900 7902 7934 E.g --------09-DEC-82 17-NOV-81 08-SEP-81 12-JAN-83 03-DEC-81 03-DEC-81 23-JAN-82 using TO_CHAR SQL> SELECT to_char(hiredate,'Month DD, YYYY') FROM Emp; TO_CHAR(HIREDATE,'MONTHDD,YYYY') Continue... To display the time the following query is used. SQL> SELECT to_char(sysdate, 'HH:MI:SS') FROM Dual; TO_CHAR(SYSDATE,'HH:MI:SS') -----------------------------------------------------09:33:11 Using Used of TO_DATE function. to convert character string to date format. If format is not specified the character string is assumed to contain date in default format. DECODE function This is one of the most powerful functions. It is equivalent to the selection construct if..then..else..end if or case …end case. Syntax DECODE (column/expression, search1, result1, [search2, result2,….]default result) The following query will illustrate the functionality of DECODE function. 1 SELECT ename, deptno, 2 DECODE(to_char(deptno), '10','ACCOUNT', 3 '20','RESEARCH', 4 'SOME OTHER DEPARTMENT') 5* FROM Emp Nesting functions A function used with in a function is called nested function. Single row functions can be nested to any depth. They are evaluated from a innermost to an outermost function. SQL> SELECT length (concat(address, city)) FROM Customer; LENGTH(CONCAT(ADDRESS,CITY)) ---------------------------20 24 23 23 22 24 20 Group functions. Group functions process multiple rows of a table and group them based on a condition. Group function returns a single row for a group. The table given below is a list of functions with their meanings. Function Purpose AVG(DISTINCT|ALL) To take the average. COUNT(*|DISTINCT|ALL|expr) To take the count of rows satisfying the condition MAX(expr) Returns the maximum value. Examples using Group Functions To calculate the average salary of all employees, the query would be, SQL> SELECT avg(sal) FROM Emp; AVG(SAL) --------2255.7143 To calculate the max salary in dept no 30, the query would be, SQL> SELECT max(sal) FROM Emp WHERE deptno = 30; MAX(SAL) --------2850 Group by clause. Used to create groups of rows in a table. For example, to find the minimum salary in each department the following query is issued. SQL> SELECT deptno, MIN(sal) FROM Emp GROUP BY deptno; DEPTNO MIN(SAL) --------- --------10 1300 20 800 30 950 Nested Groups. Used to form a group with in a group. The sequence of columns in the clause should be from the higher group to the lower group, from left to right. E.g. To find out job-wise average salary within each department, the following query is used SQL> SELECT deptno, job, AVG(sal) FROM Emp GROUP BY deptno, job; DEPTNO --------10 10 10 JOB AVG(SAL) --------- --------CLERK 1300 MANAGER 2450 PRESIDENT 5000 Having Clause HAVING Clause is used to restrict the display of grouped rows. For example, to display the department numbers and the minimum salary of the employee having the minimum salary less that 1000, the following query would do. SQL> SELECT deptno, min(sal) FROM Emp GROUP BY deptno HAVING min(sal) < 1000; DEPTNO MIN(SAL) --------- --------20 800 Summary - Functions SQL functions are classified into to , single row functions and Group functions. Single row functions are divided into 4 types, character function, numeric function, date functions and conversion function. Oracle store date in numeric format and is capable of storing century, year, month, day, hours, minutes and seconds. Multiple-table Queries Data is normally distributed over more than one table. As a result you need to retrieve data from more than one table. Multi-table queries retrieve data from more than one table, using a single query statement. This is achieved by using joins. There are two types of joins Equi-join Non-Equi-join Equi-joins Equi-join Continue... SQL> SELECT ename, dname FROM Emp, Dept WHERE Emp.deptno = Dept.deptno; ENAME ---------KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER DNAME -------------ACCOUNTING SALES ACCOUNTING RESEARCH SALES SALES SALES SALES SALES RESEARCH RESEARCH RESEARCH RESEARCH ACCOUNTING 14 rows selected. While making joins, columns having the same name should be prefixed by the table name Table aliases continue... SQL> SELECT I.ordid, I.prodid, P.descrip, I.actualprice 2 FROM Item I, Product P 3 WHERE I.prodid = P.prodid; ORDID PRODID ACTUALPRICE --------- ------------ ----------610 100890 58 611 100861 45 612 100860 30 601 200376 2.4 602 100870 2.8 604 100890 58 ….. ….. DESCRIP -------------------------ACE TENNIS NET ACE TENNIS RACKET II ACE TENNIS RACKET I SB ENERGY BAR-6 PACK ACE TENNIS BALLS-3 PACK ACCOUNTING KING ACE TENNIS NET BLAKE CLARK Aliases can be up to 30 Characters in Oracle Database. SALES RESEARCH Non-Equi-Join When a relationship between two tables is obtained by using an operator other than equal (=), it is called a non-equi-join. SALGRADE For example, to display employees having Grade 1 -------salary, the following query would Namedo. Type -------------------GRAD NUMBER LOSAL NUMBER HISAL NUMBER SQL> SELECT E.ename, E.mgr, E.sal, S.grade FROM Emp E, Salgrade S 2 WHERE E.sal BETWEEN S.losal AND S.hisal AND S.grade = 1; ENAME MGR SAL GRADE ---------- --------- --------- --------JAMES 7698 950 1 SMITH 7902 800 1 ADAMS 7788 1100 1 Outer Join Continue... For example, a query that returns employee names and the respective department names, and also department names for which no person is employed. SQL> SELECT ename, dname FROM Emp E, Dept D 3 WHERE E.deptno (+) = D.deptno; ENAME ---------KING CLARK MILLER JONES SCOTT ADAMS SMITH FORD BLAKE MARTIN ALLEN TURNER JAMES WARD DNAME -------------ACCOUNTING ACCOUNTING ACCOUNTING RESEARCH RESEARCH RESEARCH RESEARCH RESEARCH SALES SALES SALES SALES SALES SALES Self Join Self join allows to join with same columns of a EMP table. --Name Type -------------------------E.g. To retrieve the names ofEMPNO all employees and NUMBER(4) ENAME their managers, the query would be VARCHAR2(10) JOB VARCHAR2(9) MGR HIREDATE SAL COMM DEPTNO NUMBER(4) DATE NUMBER(7,2) NUMBER(7,2) NUMBER(2) SQL> SELECT E.ename "Employee ", M.ename "Manager" FROM Emp E, Emp M WHERE E.mgr = M.empno; Employee ---------BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER Manager ---------KING KING KING BLAKE BLAKE BLAKE BLAKE BLAKE JONES FORD JONES SCOTT CLARK Summary on Joins. Multi-table queries retrieve data from more than one table, using a single query statement. Two type of joins are there. Equi-join and Non-Equi-Join. Equi-Join uses equality operator (=) to join two tables. Set Operators Set operators combine two or more query results in a single result. This kind of queries consists of two or more SELECT statements. Set operators are often referred to as vertical joins. INTERSECT and MINUS operators INTERSECT operator is used to retrieve all rows that are common in the result sets of two or more queries. Considering the above example; use INSERSECT instead of UNION ALL. SQL>SELECT prodname FROM Sales WHERE custid = 107 INTERSECT SELECT prodname FROM Sales WHERE custid = 108 ORDER by 1 PRODNAME -----------------------------ACE TENNIS BALLS-6 PACK MINUS operator is used to retrieve all rows Restrictions on Using Set Operators All SELECT statements joined by set operators must have the same type and number of columns or expressions in the select list. The following statement is wrong. SELECT prodname, custid FROM Sales WHERE custid = 107 UNION SELECT prodname FROM Sales WHERE custid = 108 The corresponding columns in all SELECT statements must have the same data type. The following statement is wrong SELECT prodname FROM Sales WHERE custid = 107 UNION SELECT amount FROM Sales WHERE custid = 108 Sub Queries / Nested queries A subquery is a SELECT statement that has a result which is utilized by another SQL statement. A subquery is also called a nested query since the query statement appears inside another statement. The SQL statement containing a subquery is called the parent statement. A Sample format of a Subquery. SELECT column1, column2, ….. FROM table Single-row Subqueries Single-row subqueries return a single value from a table. The subquery results in then compared to the value of column(s) in the parent statement. For example, to find out names of employees who earn less than the average salary, the following query is issued. The solution involves two steps, • • Find out the average salary . Display the employee name who earns less than average salary. SQL> SELECT ename, sal FROM Emp 3 WHERE sal < ( SELECT avg(sal) 4 FROM Emp); ENAME SAL ---------- --------MARTIN 1250 ALLEN 1600 Multiple-value Subqueries Multiple-value subqueries return more than one value to the parent query statement. Here the expression in the parent statement is compared to the list of values returned by the subquery. For example, to select employees whose department is in ‘NEW YORK’ or ‘DALLAS’ the following query is executed. SELECT ename, deptno FROM Emp WHERE deptno IN (SELECT deptno FROM Dept WHERE loc IN ('NEW YORK','DALLAS')) ENAME DEPTNO ---------- --------- Multiple-column subqueries. In Multiple-column subqueries the inner query returns values for more than one column. For example, the following query retrieves the employee names who earns maximum salary in each job. SQL> SELECT ename, sal, job FROM Emp 2 WHERE (sal, job) IN (SELECT max(sal), job 3 FROM emp GROUP BY job); ENAME SAL JOB ---------- --------- --------MILLER 1300 CLERK ALLEN 1600 SALESMAN JONES 2975 MANAGER KING 5000 PRESIDENT SCOTT 5555 ANALYST Subqueries with HAVING Clause Subqueries can also be used in the HAVING clause This query will find out the Jobs having the average salary less than the average salary of ANALYST SQL> SELECT job, avg(SAL) 2 FROM Emp 3 GROUP BY job 4 HAVING avg(sal) < ( SELECT avg(sal) FROM Emp 5 WHERE job = 'ANALYST'); JOB AVG(SAL) --------- --------CLERK 1037.5 MANAGER 2758.3333 SALESMAN 1400 Correlated Subqueries In correlated subqueries, the inner query is evaluated repeatedly for each row in the result set of parent query. I.e the inner query is executed once for each row considered by the outer query. Following steps are executed this type of queries. • • • • Get a row from the outer query. Execute the inner query using the row’s value. Use the value resulting from the inner query to qualify of disqualify the row fetched from the outer query. Continue step 1 to 3 until no row from the outer query remains. Here is an example that find out employee who earn a salary less than the average salary of their salary for their jobs. SQL> SELECT ename, job, sal EXISTS Operator The EXISTS operator is normally used with subqueries to check whether the subquery returns any rows of query result. If the value exists, it returns TRUE else FALSE. With EXISTS parent does not use the sub query result. So you can use wildcard * for this. For example, to find out employees who are managers, I.e. who have at least one employee reporting to them, the following query would do 1 2 3 SELECT ename, job, deptno FROM Emp oEmp WHERE EXISTS (SELECT empno Summary on Subqueries A subquery is a SELECT statement that has result which is utilized by another SQL statement. There are four type of subqueries • • • • Single-row subquery Multiple-row subquery Multiple-value subquery Correlated subquery Single-row subquery return a single value to the parent query.