0% found this document useful (0 votes)
354 views

Oracle

This document provides an introduction to Oracle databases. It discusses key concepts like relational databases, database models, and the relational model. It also summarizes Oracle's object-relational model and some new features in Oracle 10g. The document is divided into sections that cover topics like restricting and sorting data, SQL functions, displaying data from multiple tables, and subqueries.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
354 views

Oracle

This document provides an introduction to Oracle databases. It discusses key concepts like relational databases, database models, and the relational model. It also summarizes Oracle's object-relational model and some new features in Oracle 10g. The document is divided into sections that cover topics like restricting and sorting data, SQL functions, displaying data from multiple tables, and subqueries.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

BASIC ORACLE

Ver:4

Rev Edi:November 2009

INDEX
1. INTRODUCTION ............................................................................................................................................ 5 1.1 DATABASE................................................................................................................................................. 5 1.2 RELATIONAL DATABASE ........................................................................................................................ 5 1.3 REALTING MULTIPLE TABLES: .............................................................................................................. 5 1.4 DATABASE MODELS: ..................................................................................................................................... 5 1.5 CODDS RULES ............................................................................................................................................... 6 1.6 THE RELATIONAL MODEL .............................................................................................................................. 6 1.7 WHAT IS ORACLE?......................................................................................................................................... 7 1.8 THE OBJECT-RELATIONAL MODEL ................................................................................................................. 7 1.9 ORACLE 10G NEW FEATURES ......................................................................................................................... 7 1.10 DATABASE USERS AND SCHEMAS ............................................................................................................... 10 1.10.1 Security Domain................................................................................................................................. 10 1.10.2 Schema Objects.................................................................................................................................. 10 1.10.3 Nonschema Objects ............................................................................................................................ 11 1.11 ORACLE PRODUCTS INCLUDE: .................................................................................................................... 12 1.12 SQL SUPPORTS THE FOLLOWING CATAGORIES OF COMANDS:- ................................................................... 12 1.12.1 Data Definition Language (DDL) Statements...................................................................................... 12 1.12.2 Data Manipulation Language (DML) Statements ................................................................................ 12 1.12.3 Data control laguage(DCL) statements.............................................................................................. 12 1.12.4 Transaction Control Statements.......................................................................................................... 12 1.13 TRANSACTIONS.......................................................................................................................................... 13 1.14 SELECT STATEMENT ................................................................................................................................ 13 QUESTIONS ....................................................................................................................................................... 14 2. RESTRICTING AND SORTING DATA....................................................................................................... 15 2.1 COMPARISON OPERATORS ............................................................................................................................ 15 2.1.1 Between --- and --- ............................................................................................................................... 15 2.1.2 IN (set)................................................................................................................................................. 15 2.1.3 Like condition ...................................................................................................................................... 15 2.1.4 ALL and ANY ....................................................................................................................................... 16 2.2 LOGICAL OPERATORS ................................................................................................................................... 16 2.3 ORDER BY CLAUSE ................................................................................................................................... 17 2.4 THE SAMPLE CLAUSE ................................................................................................................................ 17 QUESTIONS ....................................................................................................................................................... 18 3. SQL FUNCTIONS.......................................................................................................................................... 19 3.1 TYPES OF FUNCTIONS ................................................................................................................................... 19 3.2 CHARACTER FUNCTIONS: ............................................................................................................................. 19 LENGTH: SHOWS THE LENGTH OF A STRING AS A NUMERIC VALUE. ...................................... 19 LPAD:PADS THE CHARACTER VALUE RIGHT_JUSTIFIED............................................................. 19 3.3 NUMBER FUNCTIONS............................................................................................................................. 20 3.4 DATE FUNCTIONS ........................................................................................................................................ 20 3.5 GENERAL COMPARISON FUNCTIONS ............................................................................................................. 22 3.6 CONVERSION FUNCTIONS ............................................................................................................................. 23 3.7 THE RR DATE FORMAT ELEMENT ................................................................................................................ 23 3.8 GENERAL FUNCTIONS ........................................................................................................................... 24 3.9 GROUP FUNCTIONS (OR) MULTIPLE ROW FUNCTIONS.................................................................................... 26 3.10 GROUP BY CLAUSE............................................................................................................................... 27 3.11 USE THE HAVING CLAUSE TO RESTRICT GROUPS: ...................................................................................... 27

3.12 PARTITION OUTER JOIN IN ORACLE 10G ...................................................................................................... 28 QUESTIONS ....................................................................................................................................................... 28 4. DISPLAYING DATA FROM MULTIPLE TABLES................................................................................. 29 4.1 SET OPERATORS .......................................................................................................................................... 29 4.2 RELATING DATA THROUGH JOIN CONCEPT ..................................................................................................... 30 4.3 SIMPLE JOIN ................................................................................................................................................ 30 4.4 USING TABLE ALIASES ................................................................................................................................ 30 4.5 NON-EQUI JOINS.......................................................................................................................................... 30 4.6 SELF JOINS .................................................................................................................................................. 31 4.7 OUTER JOIN ................................................................................................................................................. 31 4.8 CARTESIAN PRODUCTS ................................................................................................................................ 31 QUESTIONS ....................................................................................................................................................... 32 5. SUB QUERIES ............................................................................................................................................... 33 5.1 USE SUBQUERIES FOR THE FOLLOWING PURPOSES: ........................................................................................ 33 5.2 TYPES OF SUBQUERES .................................................................................................................................. 33 5.3 EXECUTING SINGLE-ROW SUBQUERIES......................................................................................................... 33 5.4 MULTIPLE-ROW SUBQUERIES ....................................................................................................................... 34 5.5 CORRELATED SUBQUERIES........................................................................................................................... 34 QUESTIONS ....................................................................................................................................................... 36 6. CONSTRAINTS ............................................................................................................................................. 37 6.1 DATATYPES ................................................................................................................................................. 37 6.2 DATA DEFINITION LANGUAGE ..................................................................................................................... 39 6.2.1 Create table command: ........................................................................................................................ 39 6.2.2 Command To alter a table .................................................................................................................... 40 6.2.3 Command to rename a column.............................................................................................................. 40 6.2.4 Command to drop a column.................................................................................................................. 40 6.2.5 Command to Truncate a table............................................................................................................... 41 6.2.6 Command to Drop a table .................................................................................................................... 41 6.3 DATA MANIPULATION LANGUAGE ............................................................................................................... 41 6.3.1 Insert Command................................................................................................................................... 41 6.3.2 Update Command................................................................................................................................. 42 6.3.3 Delete Command.................................................................................................................................. 42 6.3.4 Merge Command.................................................................................................................................. 42 6.4 DATACONTROL LANGUAGE COMMANDS....................................................................................................... 42 6.4.1 Grant privilage command..................................................................................................................... 42 6.4.2 Revoke privilage command................................................................................................................... 43 6.5 TRANSACTION CONTROL LANGUAGE............................................................................................................ 43 6.6 INTEGRITY CONSTRAINTS ............................................................................................................................ 44 6.6.1 Domain Integrity Constraints: .............................................................................................................. 44 6.6.2 Entity Integrity constraint..................................................................................................................... 44 6.6.3 Referential integrity constraint ............................................................................................................. 44 6.6.4 Define Constriants ............................................................................................................................... 45 QUESTIONS ....................................................................................................................................................... 47 7. DATABASE OBJECTS.................................................................................................................................. 48 7.1 SYNONYMS.................................................................................................................................................. 48 SYNTAX: ........................................................................................................................................................... 48 7.2 SEQUENCES: ............................................................................................................................................... 48 7.3 VIEW ......................................................................................................................................................... 51 7.4 TOP-N ANALYSIS ................................................................................................................................... 52 7.5 INDEX ....................................................................................................................................................... 53 7.5.1 Unique and Nonunique Indexes ............................................................................................................ 53 7.6 DATA DICTIONARY ...................................................................................................................................... 54

7.7 ROWID ...................................................................................................................................................... 54 7.8 ROWNUM ................................................................................................................................................. 55 QUESTIONS ....................................................................................................................................................... 55 8. ENHANCEMENTS TO GROUP BY CLAUSE......................................................................................... 56 8.1 GROUP BY WITH ROLLUP AND CUBE OPERATORS ...................................................................................... 56 8.2 HIERARCHICAL RETRIEVAL .......................................................................................................................... 56 8.3 ORACLE9I E XTENSIONS TO DML AND DDL STATEMENTS ........................................................................... 57 QUESTIONS ....................................................................................................................................................... 59 9. SQL*PLUS ..................................................................................................................................................... 60 9.1 EDITING COMMANDS ................................................................................................................................... 60 9.2 SQL * PLUS FILE COMMANDS ....................................................................................................................... 61 9.3 RUN SQL STATEMENTS IN A BATCH .............................................................................................................. 61 9.4 USE THE FOLLOWING COMMAND TO ACCESS THE HELP SYSTEM...................................................................... 62 9.5 HOST OPERATING SYSTEM COMMANDS. ........................................................................................................ 62 9.6 COMMANDS TO CREATE AND MODIFY FILES. .................................................................................................. 63 9.7 CREATE AND DISPLAY BIND VARIABLES. ....................................................................................................... 64 9.8 FORMATTING QUERY RESULTS..................................................................................................................... 64 FAQS .................................................................................................................................................................. 67

Introduction to SQL

Page 5 of 71

1. Introduction
1.1 DATABASE
A database is an organized collection of related information.

1.2 RELATIONAL DATABASE


A Relational database is a collection of relations or two-dimensional tables. ENTITY A Thing of significance about which information needs to be known. Examples are Departments, Employees, and Orders. ATTRIBUTE Something that describes or qualifies an Entity. For example, for the employee entity the attributes would be the employee number, name, job title, Dept number and so on. RELATIONSHIP A named Association between entities is called Relationship.

1.3 REALTING MULTIPLE TABLES:


Each table contains data that describes exactly one entity. Because Data about different entities is stored in different tables you may need to combine two or more tables to answer a particular question. For example, you may want to know the location of the dept where an employee works. In this scenario you may need information from Employees table, which contains data about employees, and the Departments Table, which contains data about departments. With an RDBMS you can relate the data in one table to the data in another table by using the Foreign Keys.A Foreign Key is a column or a set of Columns that refer to a primary key in the same table or another table. Relationship among Data: A Relationship is defined as An Association among entities A relationship type is an association of entity types, while a relationship instance is an association of entity instances. A relationship may associate an entity with itself. Several relationships may exist between the same entities. The three different types of relationships recognized among various data stored in the database are: One-to-one One-to-Many (or Many-to-One) Many-to Many.

1.4 Database Models:


The purpose of data models is to communicate, categorize, describe, specify, investigate and analyze data. Database Models are broadly classified into two categories: They are: Object-Based logical models. Record-based logical models The Object-based logical models can be defined as a collection of ideal tools for describing data, data relationships and data constraints.The Object-based logical models can be defined as a collection of ideal tools for describing data, data relationships Application. A structure once created can be reused-this is the fundamentals property Of the OOPs concepts. By combining the object oriented and relational concepts Oracle now offers the best of both worlds.

Introduction to SQL

Page 6 of 71

1.5 Codds Rules


Certain good rules have to be followed for a DBMS to be relational. codds rules Are designed in such a way that when the database is ready for use it encapsulates The relational theory to its full potential. these twelve rules are Listed below The information Rule All information is explicitly and logically represented in tables as data values. The Rule of Guaranteed Access Every item of data must be logically addressable with the help of a table name, Primary key value and column name. The Systematic Treatment of null values The RDBMS must be able to support null values to represent missing or inapplicable Information. The Database Description Rule A description of database is maintained using the same logical structures with which Data was specified by the RDBMS.These are accessible to users with appropriate authority and are stored in the data dictionary. Comprehensive Data Sub Language According to this rule, the system must support Data definition, view definition, Data manipulation, Integrity constraints,Authorization,Transaction management operations. The view updating Rule All the views must be updatable by the system. The Insert and Update Rule This Rule specifies that all the data manipulation commands must be operational on sets of rows having a relation rather than on a single row. The Physical Independence Rule Application programs must remain unimpaired when any changes are made in storage representation or access methods The Logical Data independence rule The changes that are made should not affect the users ability to work with the data. The change can be splitting the table into many more tables. The Integrity Independence Rule The integrity constraints should be stored in the system catalog or in the Database as tables The Distribution Rule The system must be able to access or manipulate the data that is distributed in other systems. The Non_Subversion Rule: The nonsubveresion rule states that different levels of the language cannot subvert or Bypass the integrity rules and constraints. If an RDBMS supports a lower level language then it should not bypass any integrity constraints defined in the higher level.

1.6 The Relational Model


The relational model has three major characteristics:

Structures Operations

Integrity rules

Structures are well-defined objects (such as tables, views, indexes, and so on) that store or access the data of a database. Structures and the data contained within them can be manipulated by operations. Operations are clearly defined actions that enable users to manipulate the data and structures of a database. The operations on a database must adhere to a predefined set of integrity rules. Integrity rules are the laws that govern which operations are allowed on the data and structures of a database. Integrity rules protect the data and the structures of a database.

Relational Database Management System Oracle provides a flexible RDBMS called oracle9i.Using its features, you can store and manage data with all the advantages of relational structure plus PL/SQL,an engine that provides you with the ability to store and execute program units. The Oracle server offers the options of retrieving data based on optimization techniques. It includes Security features that control how a database is accessed and used. Other features include consistency and protection of data through locking mechanisms

Introduction to SQL

Page 7 of 71

1.7 What is Oracle?


Oracle consists of comprehensive set of application building and end-user products, aimed at providing complete information technology solutions. Oracle applications are portable across a wide range of platforms and operating systems from PCs to large parallel processors. Oracle Application may run on the same computer as the Oracle server. Among the many application development and end-user products available within the oracle Family there is a common ability to access the database. Whether directly or indirectly, this is achieved through the structured query language.

1.8 The Object-Relational Model


The object-relational model enables users to define object types, specifying both the structure of the data and the methods of operating on the data, and to use these datatypes within the relational model. An object type differs from native SQL datatypes in that it is user-defined and it specifies both the underlying persistent data (attributes) and the related behaviors (methods). Object types are abstractions of the real-world entities--for example, purchase orders--that application programs deal with. Object types are used to extend the modeling capabilities provided by the native datatypes. An object type has three kinds of components: A name, which serves to identify the object type uniquely. Attributes, which are built-in datatypes or other user-defined types. Attributes model the structure of the real world entity. Methods, which are functions or procedures written in PL/SQL and stored in the database, or written in a language such as C or Java and stored externally. Methods implement specific operations that an application can perform on the data. Every object type has a constructor method that makes a new object according to the datatype's specification. The Object-Relational Model for Database Management Database management systems have evolved from hierarchical to network to relational models. The most widely accepted database model is the relational model. Oracle extends the relational model to an object-relational model, which makes it possible to store complex business models in a relational database. Relational database management systems offer benefits such as: Independence of physical data storage and logical database structure Variable and easy access to all data Complete flexibility in database design Reduced data storage and redundancy

1.9 Oracle 10g New Features


The following are new in this release: The binary floating-point datatypes BINARY_FLOAT and BINARY_DOUBLE The spatial datatype SDO_GEORASTER The interMedia datatype SI_StillImage and six related Still Image object types CREATE INDEX and ALTER INDEX have new syntax that lets you create and maintain global hashpartitioned indexes. DROP TABLE has a new PURGE clause that lets you drop the table without moving it to the recycle bin. MERGE has new syntax that lets you: o o Specify either the update operation or the insert operation, or both Delete rows from the target table during the update operation

Introduction to SQL

Page 8 of 71

PURGE is a new SQL statement that lets you permanently remove previously dropped objects from the recycle bin and release the space that was associated with them. SELECT has new syntax that lets you: o o Issue a versions query, which returns all incarnations of the rows returned by the query within a specified SCN or time range. Perform a query on a partitioned outer join. The new syntax supports data densification, the process of querying sparse data along a particular dimension of data and returning rows that otherwise would have been omitted from the data returned by the query. View the results of a query as a multidimensional array and perform associated calculations.

All of the DML statements (INSERT, UPDATE, DELETE, MERGE) now have an error logging clause "Model Expressions" have been enhanced to allow analytic functions and FOR loops. COLUMN_VALUE Pseudocolumn A new aggregate function COLLECT creates a nested table of the input type out of the rows selected. New locale-independent format elements have been added to the tables in "Format Models" on page 254. Oracle Database now performs implicit conversion between CLOB and NCLOB data. You can now specify a LOB column in the UPDATE OF clause when creating an update DML trigger. A new category of collection functions lets you manipulate nested tables and varrays. The collection functions are o o o o CARDINALITY POWERMULTISET POWERMULTISET_BY_CARDINALITY SET

A new category of model functions are for use in specialized calculations and are valid only in the model_clause of a query. The model functions are o o o o CV PRESENTNNV PRESENTV PREVIOUS TO_BINARY_DOUBLE TO_BINARY_FLOAT NANVL REMAINDER

Functions to manipulate binary floating-point numbers o o o o

Oracle 10g Database New Features Important new features are introduced with the release of the Oracle9i Database, including advancements in Real Application Clusters, systems management, availability, scalability, and security. Availability Enterprises have used their information technology (IT) infrastructure to provide competitive advantage, increase productivity, and empower users to make faster and more informed decisions. However, with these benefits has come an increasing dependence on that infrastructure. Should a critical application, server or data become unavailable, the entire business can be placed in risk. Revenue and customers can be lost, penalties can be owed, and bad press can have a lasting effect on customers and a companys reputation. Building a high availability IT infrastructure is critical to the success and well being of all enterprises in todays fast moving economy.

Introduction to SQL

Page 9 of 71

Trends in computing technology are also enabling a new IT architecture, referred to as Grid computing(in 10g, g stand for Grid Computing), to be deployed. Grid computing is a new computing architecture that effectively pools large numbers of servers and storage into a flexible, on-demand computing resource for all enterprise computing needs. Oracle Business Intelligence Oracle provides the technology foundation needed to build a complete and integrated solution for Business Intelligence and Data Warehousing. Oracle Database 10 g , Oracle Application Server 10 g , and Oracle Developer Suite allow users to rapidly develop and deploy data warehouses and data marts with a complete and integrated array of reporting, querying, and analytic capabilities. Oracle Database 10 g is an analysis-ready database with ETL, OLAP, and Data Mining built right into the data server where analysis takes place. Oracle Application Server 10 g comes with built-in portal and services that allow easy development and delivery of customized intelligent information to all. Oracle Developer Suite comes with tools to build and manage the data warehouse, to build applications, and to provide easy access and distribution of information across the enterprise. Grid Technology Center Oracle 10g allows companies to begin evolving their IT toward a grid computing model. From storage, to databases, application servers, and applications, Oracle's new technology addresses the requirements of grid computing. Oracle Information Integration Information integration is an important feature of Oracle Database. Oracle provides many features that allow customers to synchronously and asynchronously integrate their their data including Oracle Streams, Oracle Advanced Queuing, replication, and distributed SQL. Oracle also provides gateways to non-Oracle database servers, providing seamless interoperation in heterogeneous environments. Oracle Database Application Development SQL, XML, and procedural languages (e.g., PL/SQL, Java, C/C++) are the core technologies used by application developers today. The table below summarizes the core strengths and capabilities that each brings to the table. Any complete application solution must have elements of all three. Oracle Database 10 g is a single integrated platform that supports all three of these capability areas in a simple fashion with high performance and scalability. Capability OLTP Analysis Relational Data (Structured) Documents (Unstructured) Messages (SemiStructured) Integration and Transformation Business Logic SQL X X X X X X X X X XML PL/SQL, Java, C/C++ Oracle Database X X X X X X X

Oracle Spatial & Oracle Locator: Location Features for Oracle Database 10g The location features in Oracle Database 10 g provide a platform that supports a wide range of applications-from automated mapping/facilities management and geographic information systems (GIS), to wireless location services and location-enabled e-business. The Oracle Database 10 g, Oracle Application Server 10 g , and Oracle E-Business Suite include and make use of location features to deliver unique business advantages to users. Through Oracle Spatial and Oracle Locator , geographic and location data are managed in a native type within Oracle Database 10 g . Oracle Locator is a feature of Oracle Database 10 g Standard and Enterprise Editions that provides core location functionality needed by most customer applications to support a variety of location-based services (LBS) and 3rd party GIS solutions. Oracle Spatial is an option for Oracle Enterprise Edition that provides advanced spatial features to support high-end GIS and LBS solutions. Oracle MapViewer is an Oracle Application Server Java

Introduction to SQL

Page 10 of 71

component and JDeveloper extension used for map rendering and viewing geospatial data managed by Oracle Spatial or Locator. Oracle Spatial and Oracle Locator have been adopted as the preferred location platform by leading GIS and LBS vendors. Oracle Spatial and Oracle Locator have also been deployed by telecommunications, utilities, and government organizations worldwide. Oracle Database Manageability Oracle10g introduces a sophisticated database that automatically adapts, monitors, diagnoses and fixes itself. The new self-managing database reduces the costs of managing the IT environment with a simplified install, greatly reduced configuration and intuitive day-to-day administration. The Oracle Database 10g manageability features allow DBAs to become more productive, help their organizations reduce management costs, and scale to manage the Enterprise Computing Grid. Oracle Real Application Clusters 10g Oracle Real Application Clusters (RAC) 10 g is an option to the award-winning Oracle Database 10 g Enterprise Edition. Oracle RAC is a cluster database with a shared cache architecture that overcomes the limitations of traditional shared-nothing and shared-disk approaches to provide a highly scalable and available database solutions for all your business applications. Oracle Platform Security Oracle Platform Security is the set of security capabilities and services implemented in the Oracle Database and Oracle Applicaiton Server. These consist of Database Security features, Application Server Security features, and the Oracle Identity Management infrastructure. Combined, these capabilities and services enable the development and deployment of secure e-business applications. XML Technology Centre Whether you are a beginner, intermediate, or advanced XML user, the XML Center provides you up-to-date content and guidance to develop all types of XML and Web Service applications.

1.10 Database Users and Schemas


Each Oracle database has a list of usernames. To access a database, a user must use a database application and attempt a connection with a valid username of the database. Each username has an associated password to prevent unauthorized use.

1.10.1 Security Domain


Each user has a security domain--a set of properties that determine such things as: The actions (privileges and roles) available to the user The tablespace quotas (available disk space) for the user The system resource limits (for example, CPU processing time) for the user

1.10.2 Schema Objects


A schema is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated with SQL and include the following types of objects: Clusters Constraints Database links Database triggers Dimensions External procedure libraries Index-organized tables

Introduction to SQL Indexes Indextypes Java classes, Java resources, Java sources Materialized views Materialized view logs Object tables Object types Object views Operators Packages Sequences Stored functions, stored procedures Synonyms Tables Views

Page 11 of 71

1.10.3 Nonschema Objects


Other types of objects are also stored in the database and can be created and manipulated with SQL but are not contained in a schema: Contexts Directories Parameter files (PFILEs) and server parameter files (SPFILEs) Profiles Roles Rollback segments Tablespaces Users

Introduction to SQL

Page 12 of 71

The image above shows a system tablespace and a data tablespace. The system tablespace contains several objects (tables and indexes). The data tablespace also contains several objects (tables, indexes, and clusters). The system tablespace is stored in the DBFILE1 datafile. It is physically stored on one of the disks of Disk Drive 1. The data tablespace is stored in the DBFILE2 and DBFILE3 datafiles. The datafiles are stored on two of the disks of Disk Drive 1, including the disk that the system tablespace is stored on.

1.11 Oracle Products include:


SQL,i SQL*plus and PL/SQL SQL: Structured Query Language is used to access a relational database including Oracle. It may be used with each of the Oracle tools where access to the database is required. The oracle server supports ANSI standard SQL.Statements manipulate data and data definitions in the database. SQL*plus It is an Oracle Product with which SQL and PL/SQL languages may be used. It has its own command language for controlling the behavior of the product, and for formatting the output from SQL Queries. Isql*plus is an oracle tool that recognizes and submits SQL statements to the Oracle server for execution and contains its own command language ISQL*plus is an environment which is oracle proprietary.It runs on the browser and access local and remote database. These commands do not allow manipulation of values in the database PL/SQL It is the Oracles Procedural Language for writing application logic and for manipulating data out side the database. It includes sub-set of SQL commands and is available in the Oracle Server itself.

1.12 SQL Supports The Following Catagories Of Comands:Data Definition Language Data Manipulation Language Data Control Language Transaction Control Language -create,alter,drop,truncate,rename commands -insert,select,delete and update commands -grant and revoke commands -commit,savepoint and rollback commands

A SQL statement can be thought of as a very simple, but powerful, computer program or instruction. SQL statements are divided into the following categories:

1.12.1 Data Definition Language (DDL) Statements


Data definition language statements define, maintain, and drop schema objects when they are no longer needed. DDL statements also include statements that permit a user to grant other users the privileges, or rights, to access the database and specific objects within the database.

1.12.2 Data Manipulation Language (DML) Statements


Data manipulation language statements manipulate the database's data. For example, querying, inserting, updating, and deleting rows of a table are all DML operations. Locking a table or view and examining the execution plan of an SQL statement are also DML operations.

1.12.3 Data control laguage(DCL) statements


Data Control Language provides users with privilage commands.The owner of database objects, say Tables, has the sole authority over them.The owner can allow other database users access to the objects as per his/her discretion.Granting privilages(insert,select..) to others allows them to perform operations within their(privilages) Purview.Privilages granted can also be withdrawn by the owner any time.

1.12.4 Transaction Control Statements

Introduction to SQL

Page 13 of 71

Transaction control statements manage the changes made by DML statements. They enable the user or application developer to group changes into logical transactions. Examples include COMMIT, ROLLBACK, and SAVEPOINT.

1.13 Transactions
A transaction is a logical unit of work that comprises one or more SQL statements executed by a single user. According to the ANSI/ISO SQL standard, with which Oracle is compatible, a transaction begins with the user's first executable SQL statement. A transaction ends when it is explicitly committed or rolled back by that user. Consider a banking database. When a bank customer transfers money from a savings account to a checking account, the transaction can consist of three separate operations: decrease the savings account, increase the checking account, and record the transaction in the transaction journal. Oracle must guarantee that all three SQL statements are performed to maintain the accounts in proper balance. When something prevents one of the statements in the transaction from executing (such as a hardware failure), the other statements of the transaction must be undone; this is called rolling back. If an error occurs in making any of the updates, then no updates are made.

1.14 SELECT Statement


Select *|{[distinct] column|expression[alias],..} from table; A select clause specifies the columns to be displayed. A from clause specifies the table name *Selects all columns Distinct suppress duplicates Selecting all columns SQL> select * from emp; SQL> select * from dept; Selecting specific columns SQL>select empno, ename from emp; SQL>select deptno, dname from dept; Arithmetic Expression You can change the way the data is displayed, perform calculations or look what if scenarios.we can create expressions with number and date data by using arithmetic operators + Add, -subtract, *multiply, / divide SQL>select ename, sal, sal*200 from emp; SQL>select ename, sal, 10*sal+300 from emp; SQL>select ename, sal, 10*(sal+300) from emp; If an arithmetic expression contains more than one operator, multiplication and division are evaluated first .If the operator within an expression are of same priority, then evaluation is done from left to right you can use parentheses to force the expression within the parentheses to be evaluated first Defining a Null Value: A null is a value that is unavailable, unassigned, unknown or inapplicable. A null is not same as zero or a blank space SQL>select ename, job, sal, comm from emp; Note: Arithmetic expressions containing a null value evaluated to null. SQL>select ename, 10*(sal+comm) from emp;

Introduction to SQL

Page 14 of 71

Defining Column Alias A column alias renames the column heading. It requires double quotation marks if it contains spaces or special characters or is case sensitive SQL>select ename "employee name, job, sal salary from emp; Concatenation operator A concatenation operator concatenates columns or character strings to other columns. Two vertical bars represent it ( || ) SQL>select ename || job as "Employees info" from emp; Eliminating Duplicate Rows Eliminate duplicate rows by using the distinct keyword in the Select Clause SQL>select distinct deptno from emp; Displaying Table Structure In iSQL*plus we display the structure of a table using DESCRIBE command this shows all the column names and data types. SQL>DESCRIBE emp;

Questions
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. What are the features of Isql*plus ? List the different jobs available in the emp table ? Where are the different catagerios of SQL commands ? What is a Relation ship and explain howmany types are there ? Explain about Codd Rules? What Is a SELECT Statement? How To Select All Columns of All Rows from a Table? How To Select Some Columns from a Table and Explain with Example? How To Sort the Query Output? How To Filter Out Duplications in the Returning Rows? How To Name Query Output Columns? Explain about DCL,DDL and DML with Examples ? How can you Alias name for a column in Result ?

Restricting and Sorting Data

Page 15 of 67

2. Restricting and Sorting Data


Restrict the rows returned by using the Where clause. The Where clause follows the from clause. We Can retrieve only the rows which satisfy the Where condition.To arrange the displayed rows. According to some pre-defined order we can usee the order by clause.It is also used to arrange rows in the asecending and descending order. Ex: Display all the employees of department 30 SQL>select * from emp where deptno=30 Ex: Display all details of Scott SQL>Select * from emp where ename='SCOTT';

2.1 Comparison operators


Comparison conditions are used in conditions that compare one expression to another value or expression = equal to, > greater than, < less than, >= greater than equal to <= less than equal to, <> not equal to Other comparison operators

2.1.1 Between --- and --to get results Between two values Ex: Display employees who are in the salary range 3000 and 5000 SQL>select * from emp where sal between 3000 and 5000;

2.1.2 IN (set)
Match any of the lists of values Ex:Display employees whose department no is 20 or 30 SQL>select * from emp where deptno in (20,30);

2.1.3 Like condition


Match a character pattern Ex: Display employees whose name starts with S SQL>select * from emp where ename like'S%'; Ex: Display employees whose name ends with T SQL>select * from emp where ename like '%T'; Ex: Display employees whose name contains M as second character

Restricting and Sorting Data SQL>select * from emp where ename like'-M%' ; Combinig Wildcard Characters The % and _ symbols can be used in any combination with literal characters.

Page 16 of 67

You can use the escape identifier to search for the actual % and _symbos.When you need to have an exact match for the actual % and _characters,use The ESCAPE option. 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 SQL>select empno,ename,job from employees where job like %SA\_% escape \; Ex: Display the names of the employees who are not entitled to get a comm SQL>select * from emp where comm is null;

2.1.4 ALL and ANY


ALL The ALL operator compares a value to all values in another value set. EX: 1) SQL>select * from emp where emp_salary > ALL (select emp_salary from emp where emp_job = 'OPERATOR'); It will compares salary value to see whether it is greater than all salaries of the employee whose status is operator. 2) SQL>select * from emp where emp_age <= ALL (select emp_age from emp where emp_state='CA'); It will compares age value to see whether it is less than or equal to all employee's age who is staying in CA. ANY The ANY operator compares a value to any values in another value set. Ex: 1) SQL>select * from emp where emp_salary > ANY (select emp_salary from emp where emp_job = 'PROGRAMMER'); It will compares salary value to see whether it is greater than ANY salaries of the employee whose status is programmer.

2.2 Logical operators


And operator: This returns true if both component conditions are true
Ex: Display the details of clerks in department 10 SQL>select * from emp where job='CLERK' and deptno=10; OR operator: This returns true if either of the componet condition is true Ex: Display the details of employees who are manager or sal >3000 SQL>select * from emp where job='MANAGER' or sal >3000; Not operator: This returns true if the following condition is false Ex: Display all the details of employees whose job id is not a manager or a president

Restricting and Sorting Data SQL> Select * from emp where job not in ('MANAGER','PRESIDENT');

Page 17 of 67

2.3 ORDER BY Clause


Sorts rows with the ORDER BY clause Asecending order is default Order by comes last in the select statement if Desc is used after the order by clause the rows are displayed in the descending order of that column Ex: Display the information of employees in the ascending order of their salary SQL>Select * from emp order by sal; Ex: Display the names and salaries of employees in descending order SQL>select * from emp order by sal desc; Note: If the order by clause is not used the sort order is undefined and the oracle server may not fetch rows in the same order for the same query twice. use the ORDER BY clause to display the rows in a specific order. we can Sort on multiple columns. the order of ORDER BY list is the order of sort. you can order by a column which is not in the select list

2.4 The SAMPLE Clause


From Oracle 8i, the easiest way to randomly select rows from a table is to use the SAMPLE clause with a SELECT statement. Examples: Ex: SELECT * FROM emp SAMPLE(10); In the above example, Oracle is instructed to randomly return 10% of the rows in the table. Ex: SELECT * FROM emp SAMPLE(5) BLOCKS; This example will sample 5% of all formatted database blocks instead of rows. This clause only works for single table queries on local tables. If you include the SAMPLE clause within a multi-table or remote query, you will get a parse error or "ORA-30561: SAMPLE option not allowed in statement with multiple table references". One way around this is to create an inline view on the driving table of the query with the SAMPLE clause. Example: SELECT t1.dept, t2.emp FROM (SELECT * FROM dept SAMPLE(5)) t1, emp t2 WHERE t1.dep_id = t2.dep_id; If you examine the execution plan of a "Sample Table Scan", you should see a step like this: TABLE ACCESS (SAMPLE) OF 'EMP' (TABLE)

Restricting and Sorting Data

Page 18 of 67

Questions
1. 2. 3. 4. 5. List all the information about all the employees from emptable. List all employees names along with their salaries from em table. List the names of analyst and salesmen. List names of employees who are not managers. List the name of the employee and designation (job) of the employee,who does not report to body.Manager is null) 6. List the employees who are not eligible for commission 7. List the employee details not belonging to the department 10 and 20. 8. List the empno,ename,sal in ascending order of salary. 9. List the employee name and hiredate in descending order of hiredate. 10. How To Select Some Rows from a Table?

11. What is the result of select 1*NULL 12. What is the result of select 'srinivas'+NULL

SQL Functions

Page 19 of 71

3. SQL Functions
SQL functions are used to perform calculations on data.To manipulate output from groups of rows.It can also format date and numbers for display.It can also be used for modifiying individual data items. SQL function sometimes take arguments and always return a value.

3.1 Types of functions


Single Row functions Multiple Row Functions Single Row Functions operate on single rows only and return one result per row.The different types of single_row functions are Character functions Number functions Date functions Conversion functions General functions NOTE: The DUAL table is owned by the user 'SYS' and may be accessed by all users. It contains one columns, DUMMY, and one row with a value 'X'. The DUAL table is useful when you want to return a value once only - for instance, the value of a constant, pseudo_column or expressionthat is not derived from a table with 'user' data.

3.2 Character Functions:


UPPER: This returns char,with all lettters into uppercase. SQL>Select upper('oracle') from dual; LOWER:This converts the mixed case or uppercase character strings to lower case SQL>select LOWER('ORACLE') from dual; INITCAP:converts the first letter of each word to uppercase and remaining letters to lowercase SQL>select INITCAP('SQL functions') from dual; CONCAT:Joins values together you are limited to two arguments with concat SQL>select CONCAT('sql ',' functions') from dual; SUBSTR:This extracts a string of determined length SQL>select SUBSTR('SQLfunctions',1,5) from dual; LENGTH: Shows the length of a string as a numeric value. SQL>select LENGHT('SQLfunctions') from dual; INSTR:Finds numeric position of a named character SQL>select INSTR('SQLfunctions','f') from dual; LPAD:Pads the character value right_justified SQL>select LPAD(sal,15,'*') from emp; RPAD:pads the character value left_justified

SQL Functions SQL>select RPAD(sal,15,'*') from emp; TRIM:Trims heading or trailing characters from a character string SQL>select TRIM('S' FROM 'SSMITHS') from dual; REPLACE: to replace a set of characters SQL>SELECT REPLACE(JACK AND JUE,J,BL) FROM DUAL;

Page 20 of 71

ASCII: Returns the decimal representation in the database character set of the first character of char. SQL>SELECT last_name FROM employees WHERE ASCII(SUBSTR(last_name, 1, 1,)) = 76; Copy : Oracle SQL*Plus copy command is useful for data transfer between oracle databases. The copy command copies data from one Oracle instance to another. The data is simply copied directly from a source to a target. The format of the copy command is: create If the destination table already exists, copy will report an error, otherwise the table is created and the data is copied. replace If the destination table exists, copy will drop and recreate the table with the newly copied data. Otherwise, it will create the table and populate it with the data. insert If the destination table exists, copy inserts the new rows into the table. Otherwise, copy reports an error and aborts. append Inserts the data into the table if it exists, otherwise it will create the table and then insert the data. Ex: SQL> copy from scott/tiger@ORCL92 to scott/tiger@ORCL92 create new_emp using select * from emp; TRANSLATE: change a character to a new described character SQL>select translate(jack,j,b) from dual;

3.3 NUMBER FUNCTIONS


ROUND: Rounds value to specified decimal SQL>select Round(35.823,2),Round(35.823,0),Round(35.823,-1) from dual; TRUNC:The TRUNC function truncates the column,expression, or value to n decimal places. SQL>select TRUNC(35.823,2),TRUNC(35.823),TRUNC(35.823,-2) from dual; MOD:The MOD function finds the remainder of value1 divided by value2. SQL>select ename,sal,mod(sal,2000) from emp where job='SALESMAN';

3.4 Date Functions


Date functions operate on Oracle dates. All date functions return a value of DATE datatype except MONTHS_BETWEEN which returns a numeric value. Oracle stores dates in an internal numeric format, representing

SQL Functions Century Day Year Hours Month Minutes Seconds

Page 21 of 71

The default display/input format for any date is DD-MON-YY. Oracle dates can range between 1st Jan 4712 BC and 31st Dec 4712 AD. SYSDATE Is a pseudo-column that returns the current date and time. You can use SYSDATE just as you would use any other column name. For example, you can display the current date by selecting SYSDATE from a table. It is customary to select SYSDATE from a dummy table called DUAL. To display the current date: SQL> select sysdate from dual; you would have easily selected SYSDATE FROM EMP, but 14 rows of the same SYSDATE would have been returned, one for every row of the EMP table. DUAL is preferred because it conviniently returns one row only. Using Arithmetic Operators Due to the fact that the date is stored as a number, it is possible to perform calculations with dates using arithmatic operators such as addition and substraction. You can add and subtract number constants as well as other dates from dates. The operations you may perform are: date+number date-number date-date date+number/24 adds a number of days to a date, producing a date subtracts number of days from a date, producing a date subtracts one date from another, producing a number of days. adds a number of hours to a date producing a date.

SQL>select hiredate,hiredate+7,hiredate-7,sysdate-hiredate From emp Where hiredate like %jun%; subtracting SYSDATE from the HIREDATE column of the EMP table returns the number of days since each employee was hired. MONTHS_BETWEEN finds the number of months between date1 and date2. The(date1, date2) result can be positive or negative. If date1 is later than date2, the result is positive; if date 1 is earlier than date2, the result is negative. SQL>select months_between(sysdate,hiredate),months_between(01-jan-84,05-nov-88) From emp Where months_between (sysdate,hiredate)>59; ADD_MONTHS(date,n) Adds n number of calender months to date n must be an integer and can be negative. SQL>select hiredate,add_months(hiredate,3),add_months(hiredate,-3) From emp where deptno=20; NEXT_DAY(date1, char) date of the next specified day of the week(char) following date 1, Char may be a number representing a day, or a character. Ex: SQL>select hiredate,next_day(hiredate, 'friday'),next_day(hiredate,6) from emp where

SQL Functions where deptno=10; LAST_DAY(date1) Finds the date of the last day of the month thatcontains date1. Ex: SQL>select sysdate,last_date(sysdate),hiredate,last_day(hiredate),last_day(15-feb-88) from emp where deptno=20; Note: The Round Function Can Be Applied To Dates ROUND(date1)

Page 22 of 71

returns date1 with the time set to 12:00AM (midnight). This is useful when comparing dates that may have different times. ROUND(date1,'MONTH') returns the first to the month containing date1 if date1 is in the first half of the month; otherwise returns the first of the following month. ROUND(date1,'YEAR') returns the first day of the year containing date1 if date1 is in the first half of the year; otherwise returns the first of the following year. SQL>select sysdate,round(sysdate,'month'),round(sysdate,'year') from dual; TRUNC(date1,'char') finds the date of first day of the month containing in date1 when char='MONTH'. if char='YEAR', it finds first day of year containing date1. SQL>select sysdate, trunc(sysdate,'month'), trunc(sysdate,'year') from dual; TRUNC is useful if you want to remove the time portion of the day. The time component of the day is in fact removed by default.

3.5 General Comparison Functions


GREATEST Returns the greatest of the list of one or more expressions. Oracle Database uses the first expr to determine the return type. If the first expr is numeric, then Oracle determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that datatype before the comparison, and returns that datatype. Ex: The following statement selects the string with the greatest value: SELECT GREATEST ('HARRY', 'HARRIOT', 'HAROLD') "Greatest" FROM DUAL; Output Greatest -------HARRY LEAST returns the least of the list of exprs. All exprs after the first are implicitly converted to the datatype of the first expr

SQL Functions

Page 23 of 71

before the comparison. Oracle Database compares the exprs using nonpadded comparison semantics. If the value returned by this function is character data, then its datatype is always VARCHAR2. Ex: The following statement selects the string with the least value: SELECT LEAST('HARRY','HARRIOT','HAROLD') "LEAST" FROM DUAL; LEAST -----HAROLD

3.6 Conversion Functions


SQL provides a number of functions to control date type conversions. These conversion functions convert a value from one datatype to another. T0_CHAR(number | date, ['fmt']) TO_NUMBER(char) TO_DATE('char','fmt') TO_CHAR TO_CHAR( date, 'date picture') specifies that date is to be converted to a new format an output.To convert the current date from the default format (DD-MON-YY) to a new 'date picture': SQL>select to_char(sysdate,'day,ddth month yyyy') from dual; Note: The 'date picture',which must be embedded within single quotes, can include any of the formats listed below. The column and 'date picture' must be separated by a comma. Day and Month in the output are automatically padded with blanksto a length of 9. to remove the blank padding use the FM(Fill Mode) prefix: SQL>select to_char(sysdate,'fmday, ddth month yyyy') from dual; FM can be used to suppress leading zeroes for the ddth format, e.g. 05TH is changed to 5th.The case in which the 'date picture' is entered is the case in which it will be displayed.TO_CHAR can also be used to extract the time of day only, and display it in a specified format. To display the time of the day: SQL>select to_char(sysdate,'hh:mi:ss') from dual; The TO_CHAR function is also used to convert a value of NUMBER data type to a value of CHAR datatype. TO_CHAR(number,'number picture') SQL>select to_char(sal,'$9,999') from emp; If the 'date picture' is omitted, the date is converted to a char value in ORACLE's default date format - DD-MON-YY. If the 'number picture' is not specified, the number is converted to a char value.Also note that format models do not affect the actual internal representation of the column value. They only affect how the column value is displayed when retrieved with a SELECT statement. Converts number or date to character format fmt. converts char, which contains a number to a NUMBER. converts the char value representing date, into a date value according to fmt specified. If fmt is omitted, format is DD-MON-YY. The TO_CHAR function is freequently used to change a date format from the default to an alternative display format.

3.7 The RR Date format Element


If you use the RR date format element instead of YY, the century of the return value varies according to the specified two-digit year and the last two digits of the current year. The table summarizes the behaviour of the RR element.

SQL Functions TO_NUMBER It is used to transform a number stored as a character to numberdatatype: SQL>select empno,ename,job,sal from emp where sal>to_number('1500'); TO_DATE To show all employees hired on June 4, 1984 (non-default format)we can use the TO_DATE function:

Page 24 of 71

SQL>select empno,ename,hiredate from emp where hiredate=to_date('june 4,1984','month dd, yyyy'); The constant is converted to a date and then compared to the HIREDATE value. The TO_DATE function is freequently used to supply a value to ORACLE expects to be passed a date with the default date format of DD-MON-YY. If you do not want to use the default date format, you must use the TO_DATE function and the appropriate alterantive format mask. To enter a row into the EMP table with a non-standard date picture enter: SQL>insert into emp (empno,deptno,hiredate) ] Values(7777,20,to_date(19/08/90,dd/mm/yy); SQL>UPDATE emp SET hiredate = TO_DATE('1998 05 20','YYYY MM DD') WHERE ename = 'smith';

3.8 GENERAL FUNCTIONS


The following are the some of the functions supported by oracle uid This function returns the integer value corresponding to the user currently logged in. SQL>select uid from dual; user This function returns the login's user name,which is in varchar2 datatype. SQL>select user from dual; USERENV Returns information about the current session. This information can be useful for writing an application-specific audit trail table or for determining the language-specific characters currently used by your session. You cannot use USERENV in the condition of a CHECK constraint. The values for the parameter argument are shown in following table. All calls to USERENV return VARCHAR2 data except for calls with the SESSIONID and ENTRYID parameters, which return NUMBER. Parameter CLIENT_INFO ENTRYID Return Value CLIENT_INFO returns up to 64 bytes of user session information that can be stored by an application using the DBMS_APPLICATION_INFO package. The current audit entry number. The audit entryid sequence is shared between fine-grained audit records and regular audit records. You cannot use this attribute in distributed SQL statements.

SQL Functions ISDBA LANG LANGUAGE SESSIONID TERMINAL

Page 25 of 71 ISDBA returns 'TRUE' if the user has been authenticated as having DBA privileges either through the operating system or through a password file. LANG returns the ISO abbreviation for the language name, a shorter form than the existing 'LANGUAGE' parameter. LANGUAGE returns the language and territory used by the current session along with the database character set in this form: language_territory.characterset SESSIONID returns the auditing session identifier. You cannot specify this parameter in distributed SQL statements. TERMINAL returns the operating system identifier for the terminal of the current session. In distributed SQL statements, this parameter returns the identifier for your local session. In a distributed environment, this parameter is supported only for remote SELECT statements, not for remote INSERT, UPDATE, or DELETE operations.

Ex:The following example returns the LANGUAGE parameter of the current session: SELECT USERENV('LANGUAGE') "Language" FROM DUAL; Output Language ----------------------------------AMERICAN_AMERICA.WE8ISO8859P1 Rank RANK calculates the rank of a value in a group of values. The return type is NUMBER. Rows with equal values for the ranking criteria receive the same rank. Oracle Database then adds the number of tied rows to the tied rank to calculate the next rank. Therefore, the ranks may not be consecutive numbers. This function is useful for top-N and bottom-N reporting. As an aggregate function, RANK calculates the rank of a hypothetical row identified by the arguments of the function with respect to a given sort specification. As an analytic function, RANK computes the rank of each row returned from a query with respect to the other rows returned by the query, based on the values of the value_exprs in the order_by_clause. Aggregate Example The following example calculates the rank of a hypothetical employee in the sample table hr.employees with a salary of $15,500 and a commission of 5%: SELECT RANK(15500, .05) WITHIN GROUP (ORDER BY salary, commission_pct) "Rank" FROM employees; Rank ---------105 Similarly, the following query returns the rank for a $15,500 salary among the employee salaries: SELECT RANK(15500) WITHIN GROUP (ORDER BY salary DESC) "Rank of 15500" FROM employees; Rank of 15500 -------------4 Analytic Example The following statement ranks the employees in the sample hr schema in department 80 based on their salary and commission. Identical salary values receive the same rank and cause nonconsecutive ranks.

SQL Functions SELECT department_id, last_name, salary, commission_pct, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC, commission_pct) "Rank" FROM employees WHERE department_id = 80; DEPARTMENT_ID LAST_NAME SALARY COMMISSION_PCT Rank ------------- ------------------------- ---------- -------------- ----------------------------------------------80 Russell 14000 .4 1 80 Partners 13500 .3 2 80 Errazuriz 12000 .3 3 80 Ozer 11500 .25 4 80 Cambrault 11000 .3 5 80 Abel 11000 .3 5 80 Zlotkey 10500 .2 7 nvi This function is used in case where we want to consider Null values as zero. SQL>select ename,nvl(comm,0) from emp; vsize The function returns the number of bytes in the expression if expression is null it returns null SQL>select vsize('hello') from dual; case CASE expression let you use IF-THEN-ELSE logic in SQL statements without having to invoke procedures. SQL>select ename,job,sal case job when 'CLERK' then 1.10*sal when 'MANAGER' then 1.15*sal when 'SALESMAN' then 1.20*sal else sal end from emp;

Page 26 of 71

In this query Oracle searches for the first WHEN...THEN pair for which expr is equal to comparision_expr and return return_expr.If none of when..then pairs meets this condition and an else clause exists, then Oracle returns else_expr. other wise oracle returns null. DECODE function The decode function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages. The DECODE function decodes expression after comparing it to each search valu. if the expression is same as search,result is returned. SQL>select ename,job,sal, DECODE(job,'CLERK',1.10*sal,'MANAGER',1.15*sal, 'SALESMAN',1.20*sal,sal) "revised salary" from emp;

3.9 Group Functions (or) Multiple Row Functions


.A group function returns a result based on a group of rows. some of these are just puerly mathematical functions.

SQL Functions

Page 27 of 71

The group fuctions operate on sets of rows to give one result per group .These sets may be the whole table or the table split into groups. The group functions supported by oracle are sum The sum function can be used to obtain the sum of a range of values of a record set. SQL>select sum(sal) "Total Salary" from emp; Avg The avg function will return the average of values of the column specified in the argument of the column SQL>select avg(sal) from emp; Min This function will give the least of all values of the column present in the argument SQL>select Min(sal) "Minimum salary" from emp; Max To perform an operation which gives the maximum of a set of values the max function can be made use of SQL> select max(sal) from emp; Count It counts all rows,inclusive of duplicates and nulls. SQL>select count(*) from emp;

3.10 GROUP BY CLAUSE


you can use the GROUP BY CLAUSE to divide the rows in a table into groups.you can then use the group functions to return summary information for each group. Ex: Display sum of salaries department wise SQL> select deptno,sum(sal) from emp group by deptno; Ex: Display no of employees under each job catageory SQL>select job,count(*) from emp group by job;

3.11 Use the HAVING clause to restrict groups:


Rows are grouped The group function is applied Group matching the having clause are displayed. Ex:Display the total salary of department 20 SQL>select deptno,sum(sal)

SQL Functions

Page 28 of 71

from emp group by deptno Having deptno=20; Ex:Display the deptno and average salaries of all departments whose maximum salary is greater than 3000 SQL>select deptno,avg(sal) from emp group by deptno having max(sal)SQL>3000 Note: If you restrict rows based on the result of a group function, you must have a GROUP BY clause as well as the HAVING clause.

3.12 Partition outer Join in Oracle 10g


Partition outer join is a new mechanism in 10g to "invent" data to fill the gaps in non-contiguous results. Example as shown below. SELECT department_id, last_name, salary, commission_pct, RANK() OVER (PARTITION BY department_id ORDER BY salary DESC, commission_pct) "Rank" FROM employees WHERE department_id = 80; DEPARTMENT_ID LAST_NAME SALARY COMMISSION_PCT Rank ------------- ------------------------- ---------- -------------- -----------------------------------------------------------80 Russell 14000 .4 1 80 Partners 13500 .3 2 80 Errazuriz 12000 .3 3 80 Ozer 11500 .25 4 80 Cambrault 11000 .3 5 80 Abel 11000 .3 5 80 Zlotkey 10500 .2 7

Questions
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. List the employee name ending with an S List the employee names having I as the second character. List the number of jobs available in the em table. List the number of employees working with the company. List the minimum salary from em table. List the department numbers and number of employees in each department. List the total salary,maximum and minimum salary and the average salary of employees job Wise,for department number 20 only. List the average salary for all departments employing more than five people. List the maximum salary of employee working as salesman. List the average salary and number mployees working in the department 20. How to copy data of one table to another table ? How To Sort the Query Output? Can the Query Output Be Sorted by Multiple Columns? How To Sort Output in Descending Order?

Displaying data from Multiple Tables

Page 29 of 71

4. Displaying Data from Multiple Tables


4.1 Set Operators
Set operators combine the results of two component queries into a single result. Queries containing set operators are called compound queries. They combine the results of two or more select statements into one result. A Query may therefore consists of two or more SQL statements linked by one or more set operators . Set operators are often called vertical joins,because the join is not according to rows between two tables,but columns. You can combine multiple queries using the set operators UNION, UNION ALL, INTERSECT, and MINUS. All set operators have equal precedence. If a SQL statement contains multiple set operators, Oracle evaluates them from the left to right if no parentheses explicitly specify another order. The corresponding expressions in the select lists of the component queries of a compound query must match in number and datatype. If component queries select character data, the datatype of the return values are determined as follows: If both queries select values of datatype CHAR, the returned values have datatype CHAR. If either or both of the queries select values of datatype VARCHAR2, the returned values have datatype VARCHAR2. Restrictions on set operators: The set operators are not valid on columns of type BLOB, CLOB, BFILE, varray, or nested table. The UNION, INTERSECT, and MINUS operators are not valid on LONG columns. To reference a column, you must use an alias to name the column. You cannot also specify the for_update_clause with these set operators. UNION All rows selected by either query. SQL>select job from emp where deptno=10 union select job from emp where deptno=30; UNION ALL All rows selected by either query, including all duplicates. SQL>select job from emp where deptno=10 union all select job from emp where deptno=30; INTERSECT All distinct rows selected by both queries. SQL>select job from emp where deptno=10 intersect select job from emp where deptno=30; MINUS All distinct rows selected by the first query but not the second. SQL>select job from emp where deptno=10 minus select job from emp where deptno=30;

Displaying data from Multiple Tables

Page 30 of 71

4.2 Relating data through join concept


Join is a query that combines rows from two or more tables or views. Oracle performs a join whenever Multiple tables appear in the queries FROM clause. The querys select list can select any columns from any of these tables. If any two of these tables have a column name in common, you must qualify all references to these columns throughout the query with table names to avoid ambiguity. Join condition: Most join queries contain WHERE clause conditions that compare two columns, each from a different table. such a condition is called a join condition. To execute a join Oracle combines pairs of rows, each containing one row from each table for which the join condition evaluates to TRUE. The Columns in the join conditions need not also appear in the select list.To execute a join of three or more tables. Oracle first joins two of the tables based on the join conditions comparing their columns and then joins the result to another table based on join conditions containing columns of the joined tables and the new table. Oracle continues this process until all tables are joined into the result. There are basically three different types of joins.

4.3 Simple join


It is the most common type of join. It retrieves from two tables having a common column and is further classified into equi-join and non equi-join A join, which is based on equalities, is called an equi-join. Ex:Display all employee name and their department name in desc order of the department name SQL>select ename, dname from emp, dept Where emp.deptno=dept.deptno Order by deptno desc Ex:Display the name, location and department of employees Whose salary is more than 1500 a month SQL>select ename, dname from emp, dept where emp.deptno=dept.deptno and sal>1500 Ex:Display all employees working in newyork SQL> select ename, sal, loc location from emp, dept Where emp.deptno=dept.deptno and loc=NEWYORK

4.4 Using Table Aliases


Simplify queries by using table aliases Improve performance by using table prefixes Qualifying column names with table names can be very time consuming, particularly if table names are lengthy. Table aliases help to keep SQL code smaller, therefore using less memory.

4.5 Non-Equi Joins


A non equi-join specifies the relationship between columns belonging to different tables by making use of the relational operator (>, <, <=, >=, <>) other than equal to (=) Ex:Display the employees salary grade SQL>select e.ename, e.sal, e.grade from emp, salgrade

Displaying data from Multiple Tables where sal between losal and hisal; Ex:Display all employees on grade 3 SQL>select ename, sal, job, grade from emp,salgrade where sal between losal and hisal grade =3;

Page 31 of 71

4.6 Self Joins


A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition. To perform a self join, Oracle combines and returns rows of the table that satisfy the join condition. To find the name of each employees manager,you need to join the employees table to itself,or perform a selfjoin. Ex:Display the name and their manager name SQL>select worker.ename||works for||manager.ename from emp worker,emp manager where worker.mgr=manager.empno; Ex:Display employees whose salary is greater than their boss salary SQL>select e1.ename from emp e1,emp e2 where e1.mgr=e2.empno and e1.sal > e2.sal;

4.7 Outer join


The outer join extends the result of a simple join.An outer join returns all the rows returned by simple join as well as those rows from one table that do not match any row from the other table this cannot be done with a simple join The Symbol (+) represents outer join. The outer join operator can appear on only on one side of the expression - the side that has information missing. It returns those rows from one table that have no direct match in the other table. Ex:Display all information along with the departments that do not have employees SQL>select ename,sal,job,dname,dept.deptno from emp.deptno(+) =dept.deptno

4.8 Cartesian Products


If two tables in a join query have no join condition, Oracle returns their Cartesian product. Oracle combines each row of one table with each row of the other. A Cartesian product always generates many rows and is rarely useful. For example, the Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always include a join condition unless you specifically need a Cartesian product. If a query joins three or more tables and you do not specify a join condition for a specific pair, the optimizer may choose a join order that avoids producing an intermediate Cartesian product.

Displaying data from Multiple Tables

Page 32 of 71

Questions
1. 2. 3. 4. 5. 6. 7. 8. What is the basic difference between a join and a union? Explain an outer join. List the employee numbers,names,department numbers and the department name; Display the ename and dname of employees and their departments in desc order of deptno Display the list of employees working in each department.Display the department information Even if no empoyee belongs to that department. List all employees who joined the company before their manager. List the jobs common to department 20 and 30. List the jobs unique to department 20.

9.

Sub Queries

Page 33 of 71

5. SUB QUERIES
A subquery is a form of select statement which appears inside another sql statement.A statement containing a subquery is called a parent statement.Subqueries are used to retrieve data from tables that depend on the values in the table itself.

5.1 Use subqueries for the following purposes:


To define the set of rows to be inserted into the target table of an INSERT or CREATE TABLE statement To define the set of rows to be included in a view or materialized view in a CREATE VIEW or CREATE MATERIALIZED VIEW statement To define one or more values to be assigned to existing rows in an UPDATE statement To provide values for conditions in a WHERE clause, HAVING clause, or START WITH clause of SELECT, UPDATE, and DELETE statements To define a table to be operated on by a containing query. You do this by placing the subquery in the FROM clause of the containing query as you would a table name. You may use subqueries in place of tables in this way as well in INSERT, UPDATE, and DELETE statements. Subqueries so used can employ correlation variables, but only those defined within the subquery itself, not outer references. Outer references ("left-correlated subqueries") are allowed only in the FROM clause of a SELECT statement.

5.2 Types of Subqueres


Single-row subqueries: Multiple-row subquery: Queries that return one row from the inner SELECT statement Queries that return more than one row from the inner SELECT statement

Note: Always enclose subquery within paranthesis Subquery will be evaluated first followed by the main query You can place the subquery in a number of SQLclauses including The Where clause,The Having clause ,The From clause.

5.3 Executing Single-Row Subqueries


Ex: Display the employees whose job is same as that of 7788 SQL>select ename,job,sal from emp where job=(select job from emp where empno=7788) Ex: Display all employees who have the same job as blake SQL>select ename,job from emp where job=(select job from emp where ename='BLAKE'); Using group Functions in a Subquery You can display data from a main query by using a group function in a subquery to return a single row. Ex: Display the employees who earns the minimum salary in the company SQL>select * from emp where sal=(select min(sal) from emp); Note: the inner query returns a value that is used by the outer query or the main query. Using Having clause with subqueries You can use subqueries not only in the where clause,but also in the having clause.The Oracle server executes the subquery ,and the results are returned into the having clause of the main query.

Sub Queries Ex: Find the job with the lowest average salary SQL>select job,avg(sal) from emp group by job having avg(sal) = (select min(avg(sal))from emp group by job);

Page 34 of 71

5.4 Multiple-Row subqueries


subqueries that return more than one row are called multiple-row subqueries you use multiple row operator,instead of a single row operator,with a multiple-row subquery.The multiple row operator expects one or more values. The multiple row comparision operators are IN,ANY,ALL Ex: Display employees who earn the lowest salary in each department SQL>select ename,sal,deptno from emp where sal in(select min(sal) from emp group by deptno); Ex: Display the employees who are not managers and whose salary is less than that of any Manager SQL>select empno,ename,job,sal from emp where sal<any(select sal from emp where job='MANAGER');

5.5 Correlated Subqueries


A correlated subquery is a nested subquery which is executed once for each 'candidate row' considered by the main query and which on execution uses a value from a column in the outer query. This causes the correlated subquery to be processed in a different way from the ordinary nested subquery. A correlated subquery is identified by the use of an outer query's column in the inner query's predicate cluase. With a normal nested subquery, the inner select runs first and it executes once, returning values to be used by the main query. A correlated subquery, on the other hand, executes once for each row(candidate row) considered by the outer query. The inner query is driven by the outer query. Steps to execute a correlated sub-query: 1. Get candidate row(fetched by outer query) 2. Execute inner query using candidate row's value. 3. Use value(s) resulting from the inner query to qualify or disqualify candidate 4. Repeat until no candidate row remains. Although the correlated subquery executes repeatedly, once for each in the main query, there is no suggestion that correlated subqueries are less efficient than ordinary non-correlated subqueries. We can use a correlated subquery to find employees who earn a salary greater than the average salary for their department: SQL> select empno,ename,sal,deptno from emp e where sal>(select avg(sal) from emp where deptno = e.deptno) order by deptno; We can see immediately that this is a correlated query since we have a column from the outer SELECT in the WHERE cluase of the inner SELECT. Note that the alias is necessary only to avoid ambiguity in column names. Now, let us analyze the above example using the EMP table: The Main Query Select first candidate row-Suresh in department 20 earning 800 EMP in FROM cluase has alias E which qualifies DEPTNO column references in inner query's WHERE cluase.

Sub Queries WHERE cluase compares 800 against value returned by inner query. The inner Query

Page 35 of 71

Computes AVG(SAL) for employee's department. WHERE department value is candidate's department (E.DEPTNO)- value passed into inner query from outer query's DEPTNO column. Candidate row does not meet condition. So, discard. Repeat from step 1 for next candidate row. The selection of candidate rows continues with those meeting the condition appearing in the query result. A correlated subquery is signaled by a column name, a table name or table alias in the WHERE clause that refers to the values of a column in each repeatedly for each candidate row in the main query. Operators When you are nesting select statements, the logical operators are all valid as well as ANY and ALL. In addition the EXISTS operator may be used., EXIST OPERATOR The EXISTS operator is freequently used with correlated subqueries. It tests whether a value is there ( NOT EXISTS) ensures that something is not there). If the value exists it returns TRUE; if it does not exist FALSE is flagged. To find employees who have at least one person reporting to them, enter: SQL>select empno,ename,job,deptno from emp e where exists ( select empno from emp where emp.mgr=e.empno) order by empno; Ex:Display employees who earns a salary greater than the average for their departments SQL>Select ename,sal,deptno from emp e Where sal>(select avg(sal) from emp where deptno=e.deptno)order by deptno; Ex:list all the departments where there are no employees SQL>select deptno,dname from dept d where not exists(select * from emp where deptno=d.deptno); Ex:find employee who have at least one person reporting to them SQL>select empno,ename,job,deptno from emp where empno in(select mgr from emp where mgr is not null);

Sub Queries

Page 36 of 71

Questions
1. 2. 3. 4. 5. 6. 7. 8. 9. Display the details of employees who work in new york. List the employees belonging to the department of MILLER List the name of the employees drawing the highest salary. List employee details who earn salary greater than the average salary for their department. List all employees who have atleast one person reporting to them. List all the employees details who do not manage any one. List The employee details of those employees whose salary is greater than any of the managers. List the employee names whose salary is greater than the highest salary of all Employees belonging to departmentno 20.

10. List The details of the employee earning more than the highest paid MANAGER.

SQL - Constraints

Page 37 of 71

6. CONSTRAINTS
6.1 Datatypes
Each value manipulated by Oracle has a datatype. A value's datatype associates a fixed set of properties with the value. These properties cause Oracle to treat values of one datatype differently from values of another. For example, you can add values of NUMBER datatype, but not values of RAW datatype. When you create a table , you must specify a datatype for each of its columns. When you create a procedure or stored function, you must specify a datatype for each of its arguments. These datatypes define the domain of values that each column can contain or each argument can have. For example, DATE columns cannot accept the value February 29 (except for a leap year) or the values 2 or 'SHOE'. Each value subsequently placed in a column assumes the column's datatype. For example, if you insert '01-JAN-98' into a DATE column, Oracle treats the '01JAN-98' character string as a DATE value after verifying that it translates to a valid date. Oracle provides a number of built-in datatypes as well as several categories for user-defined types. Character Datatypes Character datatypes store character (alphanumeric) data, which are words and free-form text, in the database character set or national character set. They are less restrictive than other datatypes and consequently have fewer properties. For example, character columns can store all alphanumeric values, but NUMBER columns can store only numeric values. VARCHAR2 Datatype The VARCHAR2 datatype specifies a variable-length character string. When you create a VARCHAR2 column, you supply the maximum number of bytes or characters of data that it can hold. Oracle subsequently stores each value in the column exactly as you specify it, provided the value does not exceed the column's maximum length. If you try to insert a value that exceeds the specified length, Oracle returns an error. You must specify a maximum length for a VARCHAR2 column. This maximum must be at least 1 byte, although the actual length of the string stored is permitted to be zero. Oracle treats zero-length strings as nulls. You can use the CHAR qualifier, for example VARCHAR2(10 CHAR), to give the maximum length in characters instead of bytes. The maximum length of VARCHAR2 data is 4000 bytes. Oracle compares VARCHAR2 values using nonpadded comparison semantics. Number Datatype The NUMBER datatype stores zero, positive, and negative fixed and floating-point numbers with magnitudes between 1.0 x 10-130 and 9.9...9 x 10125 (38 nines followed by 88 zeroes) with 38 digits of precision. If you specify an arithmetic expression whose value has a magnitude greater than or equal to 1.0 x 10126, Oracle returns an error. Specify a fixed-point number using the following form: NUMBER(p,s) where: p is the precision, or the total number of digits. Oracle guarantees the portability of numbers with precision ranging from 1 to 38. s is the scale, or the number of digits to the right of the decimal point. The scale can range from -84 to 127. Specify an integer using the following form: NUMBER(p) This represents a fixed-point number with precision p and scale 0 and is equivalent to NUMBER(p,0). Long datatype

SQL - Constraints
31

Page 38 of 71

LONG columns store variable-length character strings containing up to 2 gigabytes, or 2 -1 bytes. LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columns to store long text strings. The length of LONG values may be limited by the memory available on your computer.

Raw datatype Raw data type is used to store byte-oriented data like binary data or byte strings and the maximum size of this datatype is 2000 bytes. Long Raw datatype Long raw datatype is used to store binary data of variable length,which can have a maximum size of 2GB. Date datatype The DATE datatype stores date and time information. Although date and time information can be represented in both character and number datatypes, the DATE datatype has special associated properties. For each DATE value, Oracle stores the following information: century, year, month, date, hour, minute, and second. You can specify a date value as a literal, or you can convert a character or numeric value to a date value with the TO_DATE function. To specify a date as a literal, you must use the Gregorian calendar. You can specify an ANSI date literal, as shown in this example: DATE '1998-12-25' In addition to the above Oracle supports CLOB BLOB BFILE CLOB stores character objects with single byte characters.A table can have multiple columns with CLOB as its data type. BLOB can store large binary objects as graphics,video clips and sound files.A table can have Multiple columns with BLOB as its datatype. Bfile column stores file pointers to LOBs managed by the filesystems external to the Database. A BFILE column may contain filenames for photes stored on the CD-ROM Large Object (LOB) Datatypes The built-in LOB datatypes BLOB, CLOB, and NCLOB (stored internally) and BFILE (stored externally), can store large and unstructured data such as text, image, video, and spatial data up to 4 gigabytes in size. When creating a table, you can optionally specify different tablespace and storage characteristics for LOB columns or LOB object attributes from those specified for the table. LOB columns contain LOB locators that can refer to out-of-line or in-line LOB values. Selecting a LOB from a table actually returns the LOB's locator and not the entire LOB value. The DBMS_LOB package and Oracle Call Interface (OCI) operations on LOBs are performed through these locators. LOBs are similar to LONG and LONG RAW types, but differ in the following ways: LOBs can be attributes of a user-defined datatype (object). The LOB locator is stored in the table column, either with or without the actual LOB value. BLOB, NCLOB, and CLOB values can be stored in separate tablespaces. BFILE data is stored in an external file on the server. When you access a LOB column, the locator is returned. A LOB can be up to 4 gigabytes in size. BFILE maximum size is operating system dependent, but cannot exceed 4 gigabytes.

SQL - Constraints

Page 39 of 71

LOBs permit efficient, random, piece-wise access to and manipulation of data. You can define more than one LOB column in a table. With the exception of NCLOB, you can define one or more LOB attributes in an object. You can declare LOB bind variables. You can select LOB columns and LOB attributes. You can insert a new row or update an existing row that contains one or more LOB columns and/or an object with one or more LOB attributes. (You can set the internal LOB value to NULL, empty, or replace the entire LOB with data. You can set the BFILE to NULL or make it point to a different file.) You can update a LOB row/column intersection or a LOB attribute with another LOB row/column intersection or LOB attribute. You can delete a row containing a LOB column or LOB attribute and thereby also delete the LOB value. Note that for BFILEs, the actual operating system file is not deleted. You can access and populate rows of an internal LOB column (a LOB column stored in the database) simply by issuing an INSERT or UPDATE statement. However, to access and populate a LOB attribute that is part of an object type, you must first initialize the LOB attribute using the EMPTY_CLOB or EMPTY_BLOB function. You can then select the empty LOB attribute and populate it using the DBMS_LOB package or some other appropriate interface. BFILE Datatype The BFILE datatype enables access to binary file LOBs that are stored in file systems outside the Oracle database. A BFILE column or attribute stores a BFILE locator, which serves as a pointer to a binary file on the server's file system. The locator maintains the directory alias and the filename. BLOB Datatype The BLOB datatype stores unstructured binary large objects. BLOBs can be thought of as bitstreams with no character set semantics. BLOBs can store up to 4 gigabytes of binary data. BLOBs have full transactional support. Changes made through SQL, the DBMS_LOB package, or the OCI participate fully in the transaction. BLOB value manipulations can be committed and rolled back. However, you cannot save a BLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session. CLOB Datatype The CLOB datatype stores single-byte and multibyte character data. Both fixed-width and variable-width character sets are supported, and both use the CHAR database character set. CLOBs can store up to 4 gigabytes of character data. CLOBs have full transactional support. Changes made through SQL, the DBMS_LOB package, or the OCI participate fully in the transaction. CLOB value manipulations can be committed and rolled back. However, you cannot save a CLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session. Note: Currently varchar is equivalent to varchar2 datatype.

6.2 Data Definition Language


Data Definition Language is used to create an object,alter the structure of an object and also to drop the object created. Table Definition: A table is a unit of storage that hold data in the form of rows and columns.

6.2.1 Create table command:


A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the useraccessible data. Table data is stored in rows and columns. Every table is defined with a table name and set of columns. Each column is given a column name, a datatype (such as CHAR, DATE, or NUMBER), and a width (which could be

SQL - Constraints

Page 40 of 71

predetermined by the datatype, as in DATE) or scale and precision (for the NUMBER datatype only). Once a table is created, valid rows of data can be inserted into it. The table's rows can then be queried, deleted, or updated. Tables are created with no data unless a query is specified. You can add rows to a table with the INSERT statement. After creating a table, you can define additional columns, partitions, and integrity constraints with the ADD clause of the ALTER TABLE statement. You can change the definition of an existing column or partition with the MODIFY clause of the ALTER TABLE statement. Syntax Create table <table_name> (column definition1,column definition2,.....); The table name should adhere to the following norm While naming a table the first letter should be an alphabet Oracle reserved words cannot be used to name a table Maximum length for a table name is 30 characters Two different tables should not have same name underscore,numerals and letters are allowed but not blank space and single quotes. SQL>create table student(id number,name varchar2(10), course varchar2(10));

6.2.2 Command To alter a table


alter table <table name> modify (column definition...); alter table <table name> add (column definition...); Alter Table commands cater to the need arising out of the following situations: When a user wants to add a new column To change the width of a datatype or the datatype itself To include or drop integrity constraints

6.2.3 Command to rename a column


Syntax: Alter table <tablename> rename column <column name>;

6.2.4 Command to drop a column


Syntax: Ater table <tablename> drop column <columnname> Dropping Unused Columns It is possible to drop a column from a table. Prior to this it was neccessary to drop the entire table and rebuild it. Now you can mark a column as unused (logical delete) or delete it completely (physical delete). Logical Delete Physical Delete Logical Delete On large tables the process of physically removing a column can be very time and resource consuming. For this reason you may decide to logically delete it: ALTER TABLE table_name SET UNUSED (column_name); ALTER TABLE table_name SET UNUSED (column_name1, column_name2);

SQL - Constraints

Page 41 of 71

Once this is done the columns will no longer be visible to the user. If at a later date you have time to physically delete the columns this can be done by: ALTER TABLE table_name DROP UNUSED COLUMNS; On large tables you can reduce the amount of undo logs accumulated by using the CHECKPOINT option which forces a checkpoint after the specified number of rows has been processed: ALTER TABLE table_name DROP UNUSED COLUMNS CHECKPOINT 250; The DBA_UNUSED_COL_TABS view can be used to view the number of unused columns per table. Physical Delete To physically drop a column you can use one of the following syntaxes, depending on whether you wish to drop a single or multiple columns: ALTER TABLE table_name DROP COLUMN column_name; ALTER TABLE table_name DROP (column_name1, column_name2); Dropping a column from a table will cause all unused columns in that table to be dropped at the same time.

6.2.5 Command to Truncate a table


If there is no further use of records stored in a table and the structure has to be retained then the records alone can be deleted. Syntax: Truncate table<table_name>

6.2.6 Command to Drop a table


In order to drop a table,we can use the drop table command supported by SQL. Use the DROP TABLE statement to remove a table or an object table and all its data from the database. Syntax: drop table <table_name> Note: For an external table, this statement removes only the table metadata in the database. It has no affect on the actual data, which resides outside of the database.

6.3 Data Manipulation Language


Data manipulation Commands are the most frequently used SQL commands. The DML commands are Insert, pdate, Delete

6.3.1 Insert Command


The insert command is used to add one or more rows to a table.While using this command the values are separated by commas and the datatypes varchar2,char,date,long are enclosed in single quotes. The values must be entered in the same order as they are defined in the table.

SQL - Constraints Syntax: insert into <table_name> values (a list of values);

Page 42 of 71

If data has to be written into only specific columns this too is possible with slight variations to the general syntax syntax Insert into <tablename(col_names)>values(list of values);

6.3.2 Update Command


The update command consists of a 'set' clause and an optional 'where' clause To reflect changes to the existing data update command is used. With the update command we can update rows in the table.A single column may be updated or more than one column could be updated .Specific rows could be updated based on a specific condition. syntax update table_name set field=value,...where condition;

6.3.3 Delete Command


After inserting rows in a table we can also delete them if required The delete command consists of a 'from' clause followed by the optional 'Where' clause. Syntax: delete from <table_name> where conditions;

6.3.4 Merge Command


Oracle introduced MERGE command in version 9i. It is also known as UPSERT (Insert and Update statement together). Using the MERGE command, we can write insert and update statement using single SQL statement rather than coding two separate sets of SQLs, one for insert and one for update. It contains two clauses, WHEN MATCHED THEN (used for updating existing records) and WHEN NOT MATCHED THEN (used for inserting new records). In 9i, when we use MERGE command, we have to use both these clauses. In release 10g, Oracle made some enhancements to MERGE command. In 10g, both these clauses are optional and we can use any one of them to insert new records or to update the existing records. Let us see that with example. MERGE INTO test t USING (SELECT object_id, object_name, status, created FROM user_objects) u ON (t.object_id = u.object_id) WHEN MATCHED THEN UPDATE SET t.CREATE_DATE = u.created WHEN NOT MATCHED THEN INSERT (t.object_id, t.object_name, t.status, t.create_date) VALUES (u.object_id, u.object_name, u.status, u.created) /

6.4 Datacontrol Language Commands


6.4.1 Grant privilage command
If The user creates a table,there is no necessity for the user to be given Any privilages to use its being its creator,the user inherits authority over the table.In case,the user wants to share an object with others,the appropriate privilages can be granted on that particular object to others. Objects are logical data storage structures like tables,views,sequences, Indexes,synonyms etc. We can also specify ALL to grant all the privilages. Object privilages can be granted to others using the SQL command GRANT

SQL - Constraints Syntax Grant privilages on <object_name> to <username>;

Page 43 of 71

6.4.2 Revoke privilage command


To withdraw the privilage that has been granted to a user,we use the revoke command. This command is closely similar to that of the grant command . Syntax: Revoke privilage on<object_name> from <username>;

6.5 Transaction Control Language


A Transaction is a logical unit of work.All Changes made to the database can be refered to as a transaction Maintaining security and integrity of a database is the most important factor in judging the success of a system. This integrity can be applied to different degrees of severity. An integrity Constraint is a mechanism used by Oracle to prevent invalid data entry into the table. In other words constraints are used for enforcing rules that the columns in a table have to conform with.Commit and rollback controls the transaction with the database. Commit: This command is used to end a transaction.Only with the help of the commit command, Transaction changes can be made permanent to the database. This command also erases all savepoints in the transaction thus releasing the transaction locks. COMMIT WORK;(OR) COMMIT; Savepoint Savepoints are like markers to divide a very lengthy transaction to smaller ones.They are used to identify a point in A transaction to which we cam latter rollback.Thus savepoints is used in conjuction with rollback portions of current transaction. All savepoints marked after the savepoint to which you roll back are erased. However, the savepoint to which you roll back is not erased. For example, if you mark savepoints A, B, C, and D in that order, then roll back to savepoint B, only savepoints C and D are erased. An implicit savepoint is marked before executing an INSERT, UPDATE, or DELETE statement. If the statement fails, a rollback to the implicit savepoint is done. Normally, just the failed SQL statement is rolled back, not the whole transaction. However, if the statement raises an unhandled exception, the host environment determines what is rolled back. In SQL, the FORCE clause manually rolls back an in-doubt distributed transaction. However, PL/SQL does not support this clause. For example, the following statement is illegal: Savepoint savepoint_id; Rollback A rollback command is used to undo the work done in the current transaction.We can either rollback The entire transaction so that all changes mader by sql statements are undone,or rollback a transaction to a savepoint So that the SQL statements after the savepoint are rolled back. Rollback work;or Rollback; To rollback to a particular stage in a transaction,a savepoint Rollback to savepoint save_pt;

SQL - Constraints Where save_pt is the savepoint.

Page 44 of 71

6.6 Integrity Constraints


An integrity constraint is a declarative way to define a business rule for a column of a table. An integrity constraint is a statement about a table's data that is always true and that follows these rules: If an integrity constraint is created for a table and some existing table data does not satisfy the constraint, the constraint cannot be enforced. After a constraint is defined, if any of the results of a DML statement violate the integrity constraint, the statement is rolled back and an error is returned. Integrity constraints are defined with a table and are stored as part of the table's definition, centrally in the database's data dictionary, so that all database applications must adhere to the same set of rules. If a rule changes, it need only be changed once at the database level and not many times for each application. The following are the various types of integrity constraints: Domain integrity constraints Entity integrity constraints Referential integrity constraints

6.6.1 Domain Integrity Constraints:


These constraints set a range, and any violations that take place will prevent the user from performing the manipulation that caused the breach. There are basically two types of domain integrity constraints. Not null constraint Check constraint By default the tables can contain null values. The enforcement of Not Null constraints in a table essures that the table contains values. Oracle will not validate the record until this is satisfied. The other type of constraint available under this classification is the 'check' constraint. This can be defined to allow only a particular range of values. When the demarcation specified in this range is violated Oracle rejects the record.

6.6.2 Entity Integrity constraint


These entity integrity constraints are of two types unique constraints primary key constraints The unique constraint designates a column of a group of columns as a unique key. This constraint allows only unique values to be stored in the column Oracle rejects duplication of records when the unique key constraint is used. The primary key constraint is similar to the unique key constraint. The primary key constraint just like the former avoids duplication of values. Its need is best felt when a relation has to be set between tables, because in addition to preventing duplication it also does not allow null values. - A unique index is automatically created for a primary key - A composite primary key is created by using the table level definition

6.6.3 Referential integrity constraint


This enforces relationship between tables. It designates a column or combination of columns as a foreign key. The foreign key establishes a relationship with a specified primary or unique key in the another table, called the referenced key. In this relationship, the table containing the foreign key is called the child table and the table containing the referenced key is called the parent table.

SQL - Constraints

Page 45 of 71

One can either enable or disable a constraint. The former enforces the constraint and the later will not enforce the rule, even tough the constraint would remain as it is in the data dictionary. By default, the constraint would be enabled. Further we can define a constraint either at table or column level. On the other hand, if it is defined at the column level, it holds good only for the column for which it is defined. Now, let us look at how to impose all these constraints as per the need

6.6.4 Define Constriants


Create table [schema.] table (column datatype [default expr] [column_constraint], . [table_constraint][,..]); Create table emp( Empno number(4), Ename varchar2(10), .. deptno number(2) not null, constraint emp_empno_pk primary key(empno)); column level constraint column [constraint constraint_name] constraint_type, Table level constraint Column,.. [constraint constraint_name] constraint_type (column,..), Note: constraints are usually created at the same time as the table.Constraints can be added to a table after its creation and also temporarily disabled. We cannot define a Not null constraint at table level SQL>create table dept( Deptno number(2), Dname varchar2(14), Loc varcahr2(13), Constraint dept_dname_uk unique(dname), Constraint dept_deptno_pk primary key(deptno)); The foreign key constraint SQL>create table emp (.., deptno number(2) constraint emp_deptno_fk references dept(deptno), , ); Note: Identifies the table and column in the parent table. On delete cascade - allows deletion in the parent table and deletion of the Dependent rows in the child table. A single column can have multiple check constraints that reference the column in its definition .There is no limit to the number of check constraints CHECK constraint can be defined at the column level or table level. SQL>create table emp(empno number, ..,deptno number(2),

SQL - Constraints constraint emp_deptno_ck check(deptno between 10 and 99),

Page 46 of 71

6.7 Adding a Constriant by using Alter Command


Alter table table_name add [constraint constraint_name] constraint_type (column); Note: 1. we can add or drop a constraint,but we cannot modify a constraint. 2. We can enable or disable a constraint 3. We add a not null constraint by using the modify clause Add a foreign key constraint to the emp table indicating that a manager must Already exist as a valid employee in the emp table SQL>alter table emp add constraint emp_mgr_fk foreign key (mgr) references emp(empno); This constraint ensures that a manager exists as a valid employee in the emp table. Dropping A Constraint remove the manager constraint from the emp table SQL> alter table emp drop constraint emp_mgr_fk; Remove the primary key constraint on the dept table and drop the associated foreign key Constraint on the emp.deptno column. SQL>alter table dept drop primary key cascade; Disabling Constraints Execute the disable clause of the alter table statement to deactivate an integrity constraint ALTER TABLE table DISABLE CONSTRAINT constraint CASCADE; Enabling Constraint Activating an integrity constraint currently disabled in the table definition by using The ENABLE clause. ALTER TABLE table_name ENABLE CONSTRAINT constraint_name; Viewing Constraints Query the USER_CONSTRAINTS table to view all constraint definitions and names Query the USER_CONS_COLUMNS view columns associated with the constraint names.

SQL - Constraints

Page 47 of 71

Questions
1. 2. 3. 4. 5. 6. 7. 8. 9. Why does the primary key constraint automatically enforces a NOT NULL constraint. Write the syntax for inserting the selective columns in a table. Write the command to change the department of king to 40. Write the command to give everybody a commision of 500. Delete the records of clerk. Write the statement that you can use to drop the unused columns from table emp Revoke UPDATE privilage from every body on the emp tables. Write a statement to grant INSERT privilage on the empno column of the emp Table to SCOTT. Modify the sal column of the emp table to not null and increase its size to 10

10. Display a columns and constriants of table emp. 11. Write a command to Delete the table . 12. Modify the emp table,add constraint CHECK for SAL of TABLE EMP(condition will be salary should be greater than 2500) 13. Add a column to the existing table emp,which will hold the grades for each employee 14. While working ,set appropriate save points.Do a couple COMMIT and ROLLBACK operations and Record your observations. 15. What is referential integrity? 16. How many columns can be set as primary key in sql? 17. Differentiate Drop,Delete and Truncate commands ?

SQL Enhancements to Group by Clause

Page 48 of 71

7. DATABASE OBJECTS
The various database objects are Synonym Sequences views Indexes

7.1 Synonyms
A synonym is a database object,which is used as an alias(alternative name) for a table,views or sequence. Synonym can be private or public.The former is created by normal user,which is available only to that person whereas the latter is created by DBA ,which can be availed by any database user. A synonym is an alias for any table, view, materialized view, sequence, procedure, function, or package. Because a synonym is simply an alias, it requires no storage other than its definition in the data dictionary. Synonyms are often used for security and convenience. For example, they can do the following: Mask the name and owner of an object Provide location transparency for remote objects of a distributed database Simplify SQL statements for database users You can create both public and private synonyms. A public synonym is owned by the special user group named PUBLIC and every user in a database can access it. A private synonym is in the schema of a specific user who has control over its availability to others. Synonyms are very useful in both distributed and nondistributed database environments because they hide the identity of the underlying object, including its location in a distributed system. This is advantageous because if the underlying object must be renamed or moved, then only the synonym needs to be redefined. Applications based on the synonym continue to function without modification.

syntax:
create [public] synonym <synonym_name> for <table_name>; SQL>create synonym e for emp; When a grant is given to a other user on this synonym he can perform DML operations such as insert,delete,update on the synonym in the same way that of the table but he cannot perform any DDL operations on the synonym except dropping the synonym. The synonym is just an alias of the table and all the manipulations on it actually effect the table. Public synonyms are created by database administrator to hide the identity of the base table and reduce the complexity of SQL statements.One such public synonym is TAB,which we use for selecting the tables owned by the user.These public synonyms are owned by user group PUBLIC. Note: To get the details of the sequences that the user has created we use USER__SYNONYMS

7.2 Sequences:
Asequence is a database object,which can generate unique,sequential integer values. It can be used to automatically generate primary key or unique key values.A sequence can be either in an ascending or a descending order.

SQL Enhancements to Group by Clause

Page 49 of 71

A sequence generates a serial list of unique numbers for numeric columns of a database's tables. Sequences simplify application programming by automatically generating unique numerical values for the rows of a single table or multiple tables. For example, assume two users are simultaneously inserting new employee rows into the EMP table. By using a sequence to generate unique employee numbers for the EMPNO column, neither user has to wait for the other to enter the next available employee number. The sequence automatically generates the correct values for each user. Sequence numbers are independent of tables, so the same sequence can be used for one or more tables. After creation, a sequence can be accessed by various users to generate actual sequence numbers. Syntax: Create sequence <seq_name> [increament by n] [start with n] [maxvalue n] [minvalue n] [cycle/nocycle] [cache/nocache] While creating a sequence we can define the following ,start with , increament by n,n is an integer which specifies the interval between sequence numbers. The default is 1. Start with Minvalue Maxvalue Cycle No cycle Cache specifies the first sequence numbers to be generated. specifies the minimum value of the sequence specifies the maximum valu that the sequence can generate. specifies that the sequence continues to generate values from the beginig after reaching either its max or min value. specifies that the sequence cannot generate morevalues after reaching either its maxvalue or minvalu. The default is no cycle. The CACHE option pre-allocates a set of sequence numbers and retains them in memory so that sequence numbers can be assigned faster.When the last of the sequence numbers in the cache has been used,Oracle reads another set of numbers into the cache. The default value nocache,does not preallocate sequence numbers for faster access

Nocache Ex:

SQL>create sequence stdid Increament by 1 Start with 1 Maxval 10 Minval 1 Cycle Cache 4; A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from pseudocolumns, but you cannot insert, update, or delete their values. After creating the sequence we can access it with the pseudo columns like currval and Nextval. Nextval - Returns initial value of the sequence, when referred to,for the first time. Currval - Returns the current value of the sequence which is the value returned by the last reference to nextval. SQL>select stdid.nextval from dual Note: A sequence can be altered to change the increment value or to change the number of cached sequence numbers.

SQL Enhancements to Group by Clause SQL>alter sequence stdid maxval 30; Note: To get the details on sequences that user has created we query USER_SEQUENCES CURRVAL NEXTVAL The CURRVAL pseudocolumn returns the current value of a sequence. The NEXTVAL pseudocolumn increments the sequence and returns the next value.

Page 50 of 71

You must qualify CURRVAL and NEXTVAL with the name of the sequence: sequence.CURRVAL sequence.NEXTVAL To refer to the current or next value of a sequence in the schema of another user, you must have been granted either SELECT object privilege on the sequence or SELECT ANY SEQUENCE system privilege, and you must qualify the sequence with the schema containing it: schema.sequence.CURRVAL schema.sequence.NEXTVAL Where to Use Sequence Values You can use CURRVAL and NEXTVAL in: The SELECT list of a SELECT statement that is not contained in a subquery, materialized view, or view The SELECT list of a subquery in an INSERT statement The VALUES clause of an INSERT statement The SET clause of an UPDATE statement Restrictions: You cannot use CURRVAL and NEXTVAL: A subquery in a DELETE, SELECT, or UPDATE statement A query of a view or of a materialized view A SELECT statement with the DISTINCT operator A SELECT statement with a GROUP BY clause or ORDER BY clause A SELECT statement that is combined with another SELECT statement with the UNION, INTERSECT, or MINUS set operator The WHERE clause of a SELECT statement DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement The condition of a CHECK constraint Also, within a single SQL statement that uses CURRVAL or NEXTVAL, all referenced LONG columns, updated tables, and locked tables must be located on the same database. How to Use Sequence Values When you create a sequence, you can define its initial value and the increment between its values. The first reference to NEXTVAL returns the sequence's initial value. Subsequent references to NEXTVAL increment the sequence value by the defined increment and return the new value. Any reference to CURRVAL always returns the sequence's current value, which is the value returned by the last reference to NEXTVAL. Note that before you use CURRVAL for a sequence in your session, you must first initialize the sequence with NEXTVAL. Within a single SQL statement, Oracle will increment the sequence only once for each row. If a statement contains more than one reference to NEXTVAL for a sequence, Oracle increments the sequence once and returns the same value for all occurrences of NEXTVAL. If a statement contains references to both CURRVAL and NEXTVAL, Oracle increments the sequence and returns the same value for both CURRVAL and NEXTVAL regardless of their order within the statement. A sequence can be accessed by many users concurrently with no waiting or locking.

SQL Enhancements to Group by Clause

Page 51 of 71

7.3 VIEW
A view is a Stored query or virtual table. We can use views in most places where a table can be used.The table upon which a view is based are called base tables. Views provide an additional level of table security by restricting the access to a predetermined set of rows and /or columns of a table. They hide data complexity.i.e a single view can be defined with a join,which is a collection of related columns or rows in multiple tables.the view hides the fact that this information actually originates from several tables. They simplify commands for the user because they allow them to select information from multiple tables without actually knowing how perform a join.They isolate applications from changes in definitions of base tables. Syntax: Create [or repalce][no][force]] view <view_name> [column alias name] as <query> [with[check option][read only][constraint]]; Or Replace Specify OR REPLACE to re-create the view if it already exists. You can use this clause to change the definition of an existing view without dropping, re-creating, and regranting object privileges previously granted on it. INSTEAD OF triggers defined in the view are dropped when a view is re-created. With Read Only Specify WITH READ ONLY if you want no deletes, inserts, or updates to be performed through the view. With Check Option Specify WITH CHECK OPTION to guarantee that inserts and updates performed through the view will result in rows that the view subquery can select. The CHECK OPTION cannot make this guarantee if: There is a subquery within the subquery of this view or any view on which this view is based or INSERT, UPDATE, or DELETE operations are performed using INSTEAD OF triggers. Force Specify FORCE if you want to create the view regardless of whether the view's base tables or the referenced object types exist or the owner of the schema containing the view has privileges on them. These conditions must be true before any SELECT, INSERT, UPDATE, or DELETE statements can be issued against the view. If the view definition contains any constraints, CREATE VIEW ... FORCE will fail if the base table does not exist or the referenced object type does not exist. CREATE VIEW ... FORCE will also fail if the view definition references a constraint that does not exist. No Force Specify NOFORCE if you want to create the view only if the base tables exist and the owner of the schema containing the view has privileges on them. This is the default. CONSTRAINT Constraint Specify the name of the CHECK OPTION constraint. If you omit this identifier, Oracle automatically assigns the constraint a name of the form SYS_Cn, where n is an integer that makes the constraint name unique within the database. SQL>Create view vemp as select * from emp; The above command will create a view with name vemp,which will have the same structure of emp and all the rows of the base table are accessible through this view.

SQL Enhancements to Group by Clause

Page 52 of 71

SQL>Create or replace view vemp as select employee_id,last_name,job_id,manager_id,department_id from emp where deptno=10 with check option. Output

The following command creates a view with specific columns and we try to update any other columns it gives a error. We cn even insert rows into the view,provided other columns in the base table accept null vaules.If any of the table columns, which are not selected in view query were assigned as not null,then we cannot insert tows. Note: USER_VIEWS will provide details on VIEWS that the user has created.

7.4 TOP-N Analysis


Top-n queries for the n largest or smallest values of a column -what are the ten best selling products? -What are the ten worst selling products? Both the largest values and smallest values sets are considered Top_N queries. Performing Top_N Analysis Syntax: select [column_list],rownum From (select [column_list] from table order by top_n_column) Where rownum<=N To display top 3 earners of a company SQL>select rownum as rank,ename,sal From (select ename,sal from emp Order by sal desc) Where rownum<=3; To display the four most senior employees of a company SQL>select rownum as senior ,e.ename,e.hiredate From (select ename,hiredate from emp order by hiredate) E Where rownum<=4;

SQL Enhancements to Group by Clause

Page 53 of 71

7.5 INDEX
Indexs are optional structures associated with tables. We can create indexes explicitly to speed up sql statement execution on a table. Similar to the indexes in books that help us to locate information faster,an Oracle index provides a faster access path to table data. The index points directly to the location of the rows containg the value.Indexes are the primary means of reducing disk I/O when properly used appropriately.We create an index on a column or combinations of columns. Indexes are optional structures associated with tables and clusters. You can create indexes on one or more columns of a table to speed SQL statement execution on that table. Just as the index in this manual helps you locate information faster than if there were no index, an Oracle index provides a faster access path to table data. Indexes are the primary means of reducing disk I/O when properly used. You can create many indexes for a table as long as the combination of columns differs for each index. You can create more than one index using the same columns if you specify distinctly different combinations of the columns. For example, the following statements specify valid combinations: SQL>create index emp_idx1 on emp (ename, job); SQL>create index emp_idx2 on emp (job, ename); You cannot create an index that references only one column in a table if another such index already exists. Oracle provides several indexing schemes, which provide complementary performance functionality: B-tree indexes B-tree cluster indexes Hash cluster indexes Reverse key indexes Bitmap indexes Bitmap Join Indexes Oracle also provides support for function-based indexes and domain indexes specific to an application or cartridge. The absence or presence of an index does not require a change in the wording of any SQL statement. An index is merely a fast access path to the data. It affects only the speed of execution. Given a data value that has been indexed, the index points directly to the location of the rows containing that value. Indexes are logically and physically independent of the data in the associated table. You can create or drop an index at any time without affecting the base tables or other indexes. If you drop an index, all applications continue to work. However, access of previously indexed data can be slower. Indexes, as independent structures, require storage space. Oracle automatically maintains and uses indexes after they are created. Oracle automatically reflects changes to data, such as adding new rows, updating rows, or deleting rows, in all relevant indexes with no additional action by users. Retrieval performance of indexed data remains almost constant, even as new rows are inserted. However, the presence of many indexes on a table decreases the performance of updates, deletes, and inserts, because Oracle must also update the indexes associated with the table. The optimizer can use an existing index to build another index. This results in a much faster index build.

7.5.1 Unique and Nonunique Indexes


Indexes can be unique or nonunique. Unique indexes guarantee that no two rows of a table have duplicate values in the key column (or columns). Nonunique indexes do not impose this restriction on the column values. Oracle recommends that unique indexes be created explicitly, and not through enabling a unique constraint on a table.

SQL Enhancements to Group by Clause

Page 54 of 71

Alternatively, you can define UNIQUE integrity constraints on the desired columns. Oracle enforces UNIQUE integrity constraints by automatically defining a unique index on the unique key. However, it is advisable that any index that exists for query performance, including unique indexes, be created explicitly.

7.6 Data Dictionary


Each Oracle database has a data dictionary. An Oracle data dictionary is a set of tables and views that are used as a read-only reference about the database. For example, a data dictionary stores information about both the logical and physical structure of the database. In addition to this valuable information, a data dictionary also stores such information as: The valid users of an Oracle database Information about integrity constraints defined for tables in the database How much space is allocated for a schema object and how much of it is in use A data dictionary is created when a database is created. To accurately reflect the status of the database at all times, the data dictionary is automatically updated by Oracle in response to specific actions (such as when the structure of the database is altered). The data dictionary is critical to the operation of the database, which relies on the data dictionary to record, verify, and conduct ongoing work. For example, during database operation, Oracle reads the data dictionary to verify that schema objects exist and that users have proper access to them.

7.7 ROWID
For each row in the database, the ROWID pseudocolumn returns a row's address. rowid values contain information necessary to locate a row: The data object number of the object Which data block in the datafile Which row in the data block (first row is 0) Which datafile (first file is 1). The file number is relative to the tablespace. Usually, a rowid value uniquely identifies a row in the database. However, rows in different tables that are stored together in the same cluster can have the same rowid. Values of the ROWID pseudocolumn have the datatype ROWID Rowid values have several important uses: They are the fastest way to access a single row. They can show you how a table's rows are stored. They are unique identifiers for rows in a table. You should not use ROWID as a table's primary key. If you delete and reinsert a row with the Import and Export utilities, for example, its rowid may change. If you delete a row, Oracle may reassign its rowid to a new row inserted later. Although you can use the ROWID pseudocolumn in the SELECT and WHERE clause of a query, these pseudocolumn values are not actually stored in the database. You cannot insert, update, or delete a value of the ROWID pseudocolumn. This statement selects the address of all rows that contain data for employees in department 20: Ex: 1. SQL>select rowid, Ename from emp where deptno = 20;

2.select Every 4th row from emp table


SELECT * FROM emp WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4) FROM emp);

SQL Enhancements to Group by Clause

Page 55 of 71

7.8 ROWNUM
For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on. You can use ROWNUM to limit the number of rows returned by a query, as in this example: SQL>select * from emp where rownum < 10; If an ORDER BY clause follows ROWNUM in the same query, the rows will be reordered by the ORDER BY clause. The results can vary depending on the way the rows are accessed. For example, if the ORDER BY clause causes Oracle to use an index to access the data, Oracle may retrieve the rows in a different order than without the index. Therefore, the following statement will not have the same effect as the preceding example: SQL>select * from emp where rownum < 4 order by sal; If you embed the ORDER BY clause in a subquery and place the ROWNUM condition in the top-level query, you can force the ROWNUM condition to be applied after the ordering of the rows. For example, the following query returns the top 3 earners in a company. This is sometimes referred to as a "top-N query": SQL>select * from(select * from emp order by sal) where rownum < 4; In the preceding example, the ROWNUM values are those of the top-level SELECT statement, so they are generated after the rows have already been ordered by sal in the subquery.

Questions
1. 2. 3. 4. 5. 6. 7. 8. 9. How does a view differ from a table Create a view empview,which will contain the empno,ename,sal,deptno and dname. In what situation must a sequence be used. Create index on ename column of emp table. Delete the indexes that are no longer needed. What is the data dictionary view to see the sequence. What is a synonym? How is it used? How does one select TOP N rows of a table ? How does one select every Nth row of a table ?

10. How can you retrive Rows from 10 to 20 of Emp Table ? 11. How can you eliminate a Column from a Table ?

SQL Enhancements to Group by Clause

Page 56 of 71

8. Enhancements to GROUP BY Clause


8.1 Group by with ROLLUP and CUBE operators
Use ROLLUP and GROUP BY to produce superaggregate rows by cross-referencing columns. ROLLUP grouping produces a result set containing the regular grouped rows and the subtotal values. CUBE grouping produces a results set containing the rows from ROLLUP and cross-tabulation rows. The ROLLUP and CUBE operators are available only in Oracle8i and later releases. ROLLUP operator Select [column,] group_function(column). From table [where condition] [group by [Rollup] group_by_expression] [having having_expression]; [order by column]; Rollup is an extension to group by clause. SQL>select deptno,job,sum(sal) from emp Where deptno<30 group by rollup(deptno,job); CUBE operator Select [column,] group_function (COLUMN).. From table_name [Where condition] [Group by [CUBE] group_by_expression] [HAVING having_expression] [ORDER BY column]; The CUBE operator is used with an aggregate function to generate additional rows in a result set. The number of extra groups in the result set is determined by the number of columns included in the GROUP BY clause. SQL>select deptno,job,sum(sal) From emp where deptno<30 Group by cube(deptno,job);

8.2 Hierarchical Retrieval


Using hierarchical queries ,you can retrieve data based on a natural hierarchical relationship between Rows in a table.A relational database does not store records in a hierarchical way.However ,where A hierarchical relationship exists between the rows of a single table,a process called treewalking Enables the hierarchy to be construted.A hierarchical query is a method of reporting,in order, the branches of a tree. Select [LEVEL],column,expr from tables [where condition(s)] [connect by prior condition(s)] In the syntax SELECT LEVEL is the standard select clause for each row returned by a hierarchical query,the LEVEL,pseudocolumn

SQL Enhancements to Group by Clause FROM table WHERE Condition START WITH CONNECT BY PRIOR -

Page 57 of 71

Returns 1 for a root row,2 for a child of a root, and so on specifies the table,view,or snapshot containing the columns.you can select from only one table Restricts the rows returned by the query without affecting other rows of the hierarchy comparision with the expressions Specifies the root rows of the hierarchy(Where toi start).This clause is Required for a true hierarchical query Specifies the columns in which the relationship between parent and child Rows exist.This clause is required for a hierarchical query.

Note: Hierarchical trees are used in various fields such as corporate management(management hierarchies), Manaufacturing (product assembly), and scientific research The SELECT statement cannot contain a join or query from a view that contains a join. 1.Walking the tree:From the Bottom Up SQL>select empno,ename,job,mgr From emp Start with empno=7788 Connect by prior mgr=empno; 2.Walking the tree: From the top down SQL>select ename||reports to|| Prior ename walk top down From emp Start with ename=KING CONNECT BY PRIOR empno=mgr;

8.3 Oracle9i Extensions To DML AND DDL Statements


Overview of multitable INSERT Statements The INSERTSELECCT statement can be used to insert rows into multitables as a part Of a single DML statement Multitable INSERT statements can be used in data warehousing systems to transfer data from one or more operational sources to a set of target tables. They provide significant performance improvement over Single DML versus multiple INSERTSELECT statements Single DML versus a procedure to do multiple inserts using IFTHEN syntax. Once the data is loaded into a oracle9i,database, data transformations can be executed using SQL operations. With Oracle9i multitable INSERT statements is one of the techniques for implementing SQL data transformations. Oracle9i introduces the following types of multitable INSERT statements: Unconditional INSERT Conditional all insert Conditional first insert Pivoting insert Syntax: INSERT [ALL] [CONDITIONAL_INSERT_CLAUSE] [INSERT_INTO_CLAUSE VALUES_CLAUSE] (SUBQUERY) Conditional_Insert_Clause

SQL Enhancements to Group by Clause [ALL] [FIRST] [WHEN condition THEN] [insert_into_clause values_clause] [ELSE] [insert_into_clause values_clause unconditional insert all select empno,hiredate sal and mgr values from the emp table for those employees whose SAL >3000 insert these values into two tables salary and manager. Tables using a multitable insert SQL>insert all into salary values(empno,hiredate,sal) into manager values(empno,mgr,sal) select empno,hiredate,sal,mgr from emp where sal >3000; conditional insert all SQL>insert all when sal>4000 then into salary values(empno,hiredate,sal) when mgr >7500 then into mgr values(empno,mgr,sal) select empno,hiredate,sal,mgr from emp where empno >7700;

Page 58 of 71

If the sum(sal) is greater than 25000 then insert these values into the special sal,using a conditional first multitable insert SQL> Insert first When sal>25000 then Into special_sal values(deptno,sal) When hiredate like(%00%) then Into hire_tab_00 values(deptno,hiredate) When hiredate like (%99%) then Into hire_tab_99 values(deptno,hiredate) Else Into hire_tab values(deptno,hiredate) Select deptno,sum(sal),max(hiredate) from emp group by deptno; Note:make sure hire_tab_00,hire_tab_99,hire_tab tables exists with proper structure before executing this statement. Pivoting Insert Suppose you receive a set of sales records from a nonrelational database table Sales_source_data in the following format Employee_id,week_id,sales_mon, sales_tue,sales_wed,sales_thur,sales_fri You would want to store these records in the sales_info table in a more typical relational format Employee_id,week,sales Using pivoting insert ,convert the set of sales records from the nonrelational database tables to Relational format. You need to build a transformation such that each record from the original nonrelational database table,sales_source_data, is converted into five records for the data warehouses sales_info table.This operation is Commenly referred to ass pivoting First create a table sales_info with the following structure Employee_id number(6) Week number(2) Sales number(8,2)

SQL Enhancements to Group by Clause

Page 59 of 71

Pivoting insert command SQL>insert all into sales_info values(employee_id,week_id,sales_mon) into sales_info values(employee_id,week_id,sales_tue) into sales_info values(employee_id,week_id,sales_wed) into sales_info values(employee_id,week_id,sales_thur) into sales_info values(employee_id,week_id,sales_fri) select empno,week_id,sales_mon,sales_tue,sales_wed sales_thu,sales_fri from sales_source_data;

Questions
1. 2. 3. 4. Create a report that shows the hierarchy of the managers for the employee scott. Display his Immediate manager first. Create an indented report showing the management hierarchy starting from the employee whose Ename is Smith.Print the employees ename,mgr and deptno. Give alias names to the columns .

SQL * Plus

Page 60 of 71

9. SQL*Plus
SQL*Plus is a client terminal software allowing users to interact with Oracle server to manipulate data and data structures. Users type in SQL statements in SQL*Plus that send statements to Oracle server. Oracle server then validates and executes the statements on its databases. The query results are returned to SQL*Plus and displayed to the user. Besides sending SQL statements to the server, SQL*Plus also saves them into a local buffer and allow users to view and change the statements. The following figure illustrates the process.

With SQL*Plus, you can do the following: Issue a SELECT query and view the results Insert, update, and delete data from database tables Submit PL/SQL blocks to the Oracle server for execution Issue DDL commands, such as those used to create, alter, or drop database objects such as tables, indexes, and users Execute SQL*Plus script files Write output to a file Execute procedures and functions that are stored in a database

9.1 Editing Commands


SQL*Plus does not store commands in the buffer, you edit a SQL*Plus command entered directly to the command prompt by using [Backspace] or by re-entering the command. You can use a number of SQL*Plus commands to edit the SQL command or PL/SQL block currently stored in the buffer. Alternatively, you can use a host operating system editor to edit the buffer contents.

Command
APPEND text CHANGE /old/new CHANGE /text CLEAR BUFFER DEL DEL n

Abbreviation
A text C /old/new C /text CL BUFF (none) (none)

Purpose
adds text at the end of a line changes old to new in a line deletes text from a line deletes all lines deletes the current line deletes line n

SQL * Plus DEL * DEL n * DEL LAST DEL m n DEL * n INPUT INPUT text LIST LIST n LIST * LIST n * LIST LAST LIST m n LIST * n (none) (none) (none) (none) (none) I I text L L n or n L* Ln* L LAST Lmn L*n deletes the current line deletes line n through the current line deletes the last line deletes a range of lines (m to n) deletes the current line through line n adds one or more lines adds a line consisting of text lists all lines in the SQL buffer lists line n lists the current line lists line n through the current line lists the last line lists a range of lines (m to n) lists the current line through line n

Page 61 of 71

9.2 Sql * Plus File Commands


SAVE filename - Saves current Content of SQL buffer to the file. GET filename - calls up contents of previously saved file into the buffer START filename Runs a prvoiusly saved command file @ filename - Runs a prvoiusly saved command file(same as start) EDIT filename - Invokes the editor and saves the buffer content to a file named afiedit.buf Exit Leaves SQL * Plus

9.3 Run SQL statements in a batch


To run SQL commands in a batch, you can put all your SQL commands into a text file and execute these commands in this file in SQL*PLUS. Use your favorite editor to type in your SQL queries into a text file. For example, wanghao@sf3:~/cs6203[513]$ more table.sql DROP TABLE employee / commit / CREATE TABLE employee ( empno INTEGER NOT NULL, name VARCHAR2(50) NOT NULL, sal REAL NOT NULL, primary key (empno)); / INSERT INTO employee VALUES (1, 'Jack', 6000); INSERT INTO employee VALUES (2, 'Tom', 6000);

SQL * Plus INSERT INTO employee VALUES (3, 'John', 6000); INSERT INTO employee VALUES (4, 'Jane', 6000); / UPDATE employee SET sal=500 WHERE name='Jack' / CREATE INDEX test_index on employee(sal) / wanghao@sf3:~/cs6203[514]$

Page 62 of 71

Connect into SQL*Plus, and run the batch of commands. For example, assume that you name the SQL file as table.sql. SQL> START table.sql; Output results to a file You can record your SQL command outputs to a file for output or editing purpose. SQL> SPOOL <your file name> ; For example, SQL> SPOOL myoutput.out ; All SQL commands and their outputs after this command are written into the file myoutput.out that by default is stored in the current working directory where you invoked SQL*Plus. To end recording, use the following command: SQL> SPOOL OFF;

9.4 Use the following command to access the help system.


If you forget a specific SQL command you could enter SQL> HELP <the SQL command>; You could also find out all commands by entering: SQL> HELP menu; Sometimes when you get something fuzzy, you can try the following

SQL> SET SERVEROUTPUT ON SQL> SET ARRAYSIZE 1 Sending Results to a Printer To print query results, spool them to a file as described in the previous section. Then, instead of using SPOOL OFF, enter the command in the following form: SPOOL OUT SQL*Plus stops spooling and copies the contents of the spooled file to your host computer's standard (default) printer. SPOOL OUT does not delete the spool file after printing.

9.5 Host operating system commands.


HO[ST] [command]

SQL * Plus Executes a host operating system command without leaving SQL*Plus.

Page 63 of 71

Note: With some operating systems, you can use another character instead of HOST such as "$" (VMS), "!" (UNIX) and "$" (Windows). See the Oracle installation and user's manuals provided for your operating system for details.

9.6 commands to create and modify files.


@ { uri | file_name[.ext] } [arg ...] Runs the SQL*Plus statements in the specified command file. The command file can be called from the local file system or from a web server. You can pass values to script variables in the usual way. uri is only supported on Windows platforms in this release. @@ file_name[.ext] Runs the specified command file. This command is identical to the @ ("at" sign) command. It is useful for running nested command files because it looks for the specified command file in the same path or uri as the command file from which it was called. ED[IT] [file_name[.ext]] Invokes a host operating system text editor on the contents of the specified file or on the contents of the SQL buffer. To edit the buffer contents, omit the file name. GET file_name[.ext] [LIS[T]|NOL[IST]] Loads a host operating system file into the SQL buffer. REM[ARK] Begins a comment in a command file. The REMARK command must appear at the beginning of a line, and the comment ends at the end of the line (a line cannot contain both a comment and a command). SQL*Plus does not interpret the comment as a command. SAV[E] file_name[.ext] [CRE[ATE]|REP[LACE]|APP[END]] Saves the contents of the SQL buffer into a host operating system file (a command file). STORE SET file_name[.ext] [CRE[ATE]|REP[LACE]|APP[END]] Saves the attributes of the current SQL*Plus environment in a host operating system file (a command file). STA[RT] { uri | file_name[.ext] } [arg ...] Runs the SQL*Plus statements in the specified command file. The command file can be called from the local file system or from a web server. You can pass values to script variables in the usual way. uri is only supported on Windows platforms in this release. WHENEVER OSERROR {EXIT [SUCCESS|FAILURE |n|variable|:BindVariable] [COMMIT|ROLLBACK]|CONTINUE [COMMIT|ROLLBACK|NONE]} Exits SQL*Plus if an operating system error occurs (such as a file I/O error). WHENEVER SQLERROR {EXIT [SUCCESS|FAILURE|WARNING |n|variable|:BindVariable] [COMMIT|ROLLBACK]|CONTINUE [COMMIT|ROLLBACK|NONE]} Exits SQL*Plus if a SQL command or PL/SQL block generates an error.

SQL * Plus Use the following commands to write interactive commands. ACC[EPT] variable [NUM[BER]|CHAR|DATE] [FOR[MAT] format] [DEF[AULT] default] [PROMPT text|NOPR[OMPT]] [HIDE] Reads a line of input and stores it in a given user variable. DEF[INE] [variable]|[variable = text]

Page 64 of 71

Specifies a user variable and assigns it a CHAR value. Alternatively, lists the value and variable type of a single variable or all variables. PAU[SE] [text] Displays an empty line followed by a line containing text, then waits for the user to press [Return]. Alternatively, displays two empty lines and waits for the user's response. PROMPT [text] Sends the specified message or a blank line to the user's screen. UNDEF[INE] variable ... Deletes given user variables that you defined either explicitly (with the DEFINE command) or implicitly (with an argument to the START command).

9.7 Create and display bind variables.


VAR[IABLE] [variable {NUMBER|CHAR|CHAR (n [CHAR|BYTE])|NCHAR |NCHAR (n)|VARCHAR2 (n [CHAR|BYTE])| NVARCHAR2(n)|CLOB|NCLOB|REFCURSOR}] Declares a bind variable which can then be referenced in PL/SQL. If no arguments are supplied, VARIABLE lists all declared bind variables. PRI[NT] [variable ...] Displays the current values of bind variables. Use the following symbols to create substitution variables and parameters for use in command files. &n Specifies a parameter in a command file you run using the START command. START substitutes values you list after the command file name as follows: the first for &1, the second for &2, and so on. &user_variable, &&user_variable Indicates a substitution variable in a SQL or SQL*Plus command. SQL*Plus substitutes the value of the specified user variable for each substitution variable it encounters. If the user variable is undefined, SQL*Plus prompts you for a value each time an "&" variable is found, and the first time an "&&" variable is found. . (period) Terminates a substitution variable followed by a character that would otherwise be part of the variable name.

9.8 Formatting Query Results


Use the following commands to format, store and print your query results.
ATTRIBUTE [type_name.attribute_name [option...]]

SQL * Plus

Page 65 of 71

Specifies display attributes for a given object attribute, or lists the current display attributes for a single attribute or for all attributes; option represents one of the following clauses: ALI[AS] alias CLE[AR] FOR[MAT] format LIKE {type_name.attribute_name|alias} ON|OFF BRE[AK] [ON report_element [action [action]]] ... Specifies where and how formatting will change in a report (for example, skipping a line each time a given column value changes). Enter BREAK with no clauses to list the current BREAK definition. Where report_element has the following syntax: {column|expr|ROW|REPORT} and where action has the following syntax: [SKI[P] n|[SKI[P]] PAGE] [NODUP[LICATES]|DUP[LICATES]] BTI[TLE] [printspec [text|variable] ...]|[ON|OFF] Places and formats the specified title at the bottom of each report page, or lists the current BTITLE definition. See TITLE for additional information on valid printspec clauses. CL[EAR] option ... Resets or erases the current value or setting for the specified option; option represents one of the following clauses: BRE[AKS] BUFF[ER] COL[UMNS] COMP[UTES] SCR[EEN] SQL TIMI[NG] COL[UMN] [{column|expr} [option ...]] Specifies the display attributes for a given column, such as text for the column heading, or formats for CHAR, NCHAR, VARCHAR2 (VARCHAR), NVARCHAR2 (NCHAR VARYING), LONG, CLOB, NCLOB and NUMBER data; option represents one of the following clauses: ALI[AS] alias CLE[AR] ENTMAP {ON|OFF} FFOLD_A[FTER] FOLD_B[EFORE] FOR[MAT] format HEA[DING] text JUS[TIFY] {L[EFT]|C[ENTER]|C[ENTRE]|R[IGHT]} LIKE {expr|alias} NEWL[INE] NEW_V[ALUE] variable NOPRI[NT]|PRI[NT] NUL[L] text OLD_V[ALUE] variable ON|OFF WRA[PPED]|WOR[D_WRAPPED]|TRU[NCATED]

SQL * Plus

Page 66 of 71

Enter COLUMN followed by column or expr and no other clauses to list the current display attributes for only the specified column or expression. Enter COLUMN with no clauses to list all current column display attributes. Enter COLUMN [{column |expr} FORMAT format] where the format element specifies the Display format for the column Questions

1. 2. 3. 4. 5. 6.

What is SQL*Plus? My query does not work, SQL*Plus is saying something like "2 ". How do I get help in SQL*Plus? How do I run a script in SQL*Plus? How do I set my Oracle password? What is the Difference between @ and @@ ?

FAQs

Page 67 of 71

FAQs
1. What is the difference between oracle,sql and sql server ? SQLServer is an RDBMS just like oracle,DB2 from Microsoft Structured Query Language (SQL), pronounced "sequel", is a language that provides an interface to relational database systems. It was developed by IBM in the 1970s for use in System R. SQL is a de facto standard, as well as an ISO and ANSI standard. SQL is used to perform various operations on RDBMS. 2. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables? One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. It will be a good idea to read up a database designing fundamentalstext book. 3. What's the difference between a primary key and a unique key? Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. 4. Define candidate key, alternate key, composite key A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is calledcomposite key. 5. What are defaults? Is there a column to which a default can't be bound? A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFUALT in books online. 6. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. 7. What is a transaction and what are ACID properties? A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties. 8. CREATE INDEX myIndex ON myTable(myColumn). What type of Index will get created after executing the above statement? Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

FAQs 9. How can you Change SQL prompt name SQL> set sqlprompt Manimara > 10. What's the difference between DELETE, DROP and TRUNCATE commands?

Page 68 of 71

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. 11. What are constraints? Explain different types of constraints? Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults. Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY 12. What is an index? What are the types of indexes? indexes helps to retrieve the data quicker.Indexes are of two types. Clustered indexes and nonclustered indexes.When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it's row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table. 13. Write down the general syntax for a SELECT statements covering all the options Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax). SELECT select_list [INTO new_table_] FROM table_source [WHERE search_condition] [GROUP BY group_by__expression] [HAVING search_condition] [ORDER BY order__expression [ASC | DESC] ] 14. What is a join and explain different types of joins Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS. 15. What is a Transaction? Can you have a nested transaction? A transaction is a logical unit of work that comprises one or more SQL statements executed by a single user. Yes we can have nested Transactions. 16. What is a self join? Explain it with an example Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

FAQs CREATE TABLE emp ( empid int, mgrid int, empname char(10) ) INSERT emp SELECT 1,2,'Vyas' INSERT emp SELECT 2,3,'Mohan' INSERT emp SELECT 3,NULL,'Shobha' INSERT emp SELECT 4,2,'Shridhar' INSERT emp SELECT 5,2,'Sourabh' SELECT t1.empname [Employee], t2.empname [Manager] FROM emp t1, emp t2 WHERE t1.mgrid = t2.empid 17. What is Cross Join?

Page 69 of 71

A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. The common example is when company wants to combine each product with a pricing table to analyze each product at each price. 18. How to display duplicate rows in a table ? select * from emp where EmpID in(select EmpID from emp group by EmpID having count(EmpID)>1) 19. How do you return the top-N results of a query in Oracle? SELECT * FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC) WHERE ROWNUM < 10; 20. How can you get Nth Highest value from a table? Ex: Get Nth Highest salary from emp table select sal from (select distinct(sal) from emp where sal is NOT NULL order by sal dsc) where rownum=n 21. Difference between a "where" clause and a "having" clause. HAVING clause is used when you want to specify a condition for a group function and it is written after GROUP BY clause. The WHERE clause is used when you want to specify a condition for columns, single row functions except group functions and it is written before GROUP BY clause if it is used. 22. What is difference between Rename and Alias? Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column which do not exist once the SQL statement is executed. 23. What are the advantages and disadvantages of primary key and foreign key in SQL? Primary key Advantages - It is a unique key on which all the other candidate keys are functionally dependent Disadvantage - There can be more than one keys on which all the other attributes are dependent on. Foreign Key Advantage - It allows refrencing another table using the primary key for the other table 24. What's the difference between a primary key and a unique key? Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. 25. How to get the results of a Query sorted in any order?

FAQs Using Order by clause we can sort results of a query. 26. How can you compare a part of the name rather than the entire name? The % and _ symbols can be used in any combination with literal characters. 27. why you need indexing and where that is stroed? . We can create indexes explicitly to speed up sql statement execution on a table 28. what you mean by schema object?

Page 70 of 71

A schema is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated 29. What the difference between UNION and UNIONALL? Union will remove the duplicate rows from the result set while Union all does'nt. 30. Explain normalization ? Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the rocess of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships. 31. What is diffrence between Co-related sub query and nested sub query? - Correlated subquery runs once for each row selected by the outer query. It contains a reference to a value from the row selected by the outer query. - Nested subquery runs only once for the entire nesting (outer) query. It does not contain any reference to the outer query row. 32. How can i hide a particular table name of our schema? you can hide the table name by creating synonyms. 33. Which date function is used to find the difference between two dates? DateDiff is the command used to get difference between dates 34. Which date function returns number value? months_between 35. How does one implement IF-Then-Else in select Statement Ex 1: Ex 2: select decode(sex, 'M', 'Male', 'F', 'Female', 'Unknown') from employees; select a, b, decode( abs(a-b), a-b, 'a > b', 0, 'a = b', 'a < b') from tableX;

36. How to use "CASE" keyword in SELECT statement? SELECT ename, CASE WHEN sal>1000 THEN 'Over paid' ELSE 'Under paid' END FROM emp; 37. can you create a foreign key between columns of two tables which are having different data types ? No 38. What is a sub query? Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in a set of parentheses. Sub-queries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword. A subquery SELECT statement can return any number of values, and can be found

FAQs

Page 71 of 71 in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T-SQL statement. Properties of Sub-Query A subquery must be enclosed in the parenthesis. A subquery must be put in the right hand of the comparison operator, and A subquery cannot contain a ORDER-BY clause. A query can contain more than one sub-queries. 39. How can you make a column as unused column in a table? To make a column as unused - ALTER TABLE table_name DROP UNUSED COLUMNS; To Drop Unused column - ALTER TABLE table_name SET UNUSED (column_name); 40. What is the purpose of Round()? Can you use it for dates? If so How can ? Rounds a numeric field to the number of decimals specified. Yes. We can also use Round function with dates.For more information refer 3.4 41. What is the difference between clustered and a non-clustered index? A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A nonclustered index is a special type of index in which the logical order of the index does not matchthe physical stored order of the rows on disk. The leaf node of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. 42. How to implement one-to-one, one-to-many and many-to-many relationships while esigning tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables
43. What is De-normalization? De-normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. De-normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access.

You might also like