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

......... ..................1 GROUP BY WITH ROLLUP AND CUBE OPERATORS ............. ......................................................................................................................................................6 COMMANDS TO CREATE AND MODIFY FILES....................................................................................2 HIERARCHICAL RETRIEVAL ............................ 55 QUESTIONS .... 62 9......................................... 63 9..................................... 56 8...... 56 8.................................8 FORMATTING QUERY RESULTS...........................4 USE THE FOLLOWING COMMAND TO ACCESS THE HELP SYSTEM..................... 56 8.................................................................................... 64 FAQS ................................. 67 ................................................................................................................................................. ..............2 SQL * PLUS FILE COMMANDS ................. 54 7............7 CREATE AND DISPLAY BIND VARIABLES...........................................................................................7...........................................................................................7 ROWID .......................................................................................................... 59 9.............................................................. 61 9...................... 60 9...................................................... 62 9.... 61 9...........................................................................8 ROWNUM ..1 EDITING COMMANDS ................................................................3 ORACLE9I E XTENSIONS TO DML AND DDL STATEMENTS .................................................................................................................................................................5 HOST OPERATING SYSTEM COMMANDS....................................................... ENHANCEMENTS TO “GROUP BY” CLAUSE.......................... 55 8......... 57 QUESTIONS ............................................................................................................ 60 9........................................................................................................................................................................................................................................................................................................................................................................................... 64 9.........3 RUN SQL STATEMENTS IN A BATCH ........................ SQL*PLUS .................................

A Foreign Key is a column or a set of Columns that refer to a primary key in the same table or another table. Examples are Departments. 1. you may want to know the location of the dept where an employee works. RELATIONSHIP A named Association between entities is called Relationship.Introduction to SQL Page 5 of 71 1. By combining the object oriented and relational concepts Oracle now offers the best of both worlds. investigate and analyze data. For example. which contains data about employees. ATTRIBUTE Something that describes or qualifies an Entity.3 REALTING MULTIPLE TABLES: Each table contains data that describes exactly one entity. A relationship may associate an entity with itself. and the Departments Table. Introduction 1. Several relationships may exist between the same entities. name. and Orders. while a relationship instance is an association of entity instances. data relationships and data constraints. job title.2 RELATIONAL DATABASE A Relational database is a collection of relations or two-dimensional tables. Dept number and so on. data relationships Application. 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. A structure once created can be reused-this is the fundamentals property Of the OOPs concepts. specify.The Object-based logical models can be defined as a collection of ideal tools for describing data. describe. Relationship among Data: A Relationship is defined as “ An Association among entities” A relationship type is an association of entity types.4 Database Models: The purpose of data models is to communicate.1 DATABASE A database is an organized collection of related information. categorize. which contains data about departments. for the employee entity the attributes would be the employee number. 1. For example. Because Data about different entities is stored in different tables you may need to combine two or more tables to answer a particular question. ENTITY A Thing of significance about which information needs to be known. Database Models are broadly classified into two categories: They are: Object-Based logical models. . In this scenario you may need information from Employees table. 1. Record-based logical models The Object-based logical models can be defined as a collection of ideal tools for describing data. With an RDBMS you can relate the data in one table to the data in another table by using the Foreign Keys. Employees.

The Rule of Guaranteed Access Every item of data must be logically addressable with the help of a table name. Integrity constraints. 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 Oracle server offers the options of retrieving data based on optimization techniques. Other features include consistency and protection of data through locking mechanisms . the system must support Data definition. Structures and the data contained within them can be manipulated by operations. The Systematic Treatment of null values The RDBMS must be able to support null values to represent missing or inapplicable Information.5 Codds Rules Certain good rules have to be followed for a DBMS to be relational. 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. 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. 1. indexes.Authorization. The Non_Subversion Rule: The nonsubveresion rule states that different levels of the language cannot subvert or Bypass the integrity rules and constraints.These are accessible to users with appropriate authority and are stored in the data dictionary. Integrity rules protect the data and the structures of a database. views. 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. these twelve rules are Listed below The information Rule All information is explicitly and logically represented in tables as data values. Data manipulation. view definition. and so on) that store or access the data of a database. The view updating Rule All the views must be updatable by the system.an engine that provides you with the ability to store and execute program units. If an RDBMS supports a lower level language then it should not bypass any integrity constraints defined in the higher level. The Database Description Rule A description of database is maintained using the same logical structures with which Data was specified by the RDBMS. Relational Database Management System Oracle provides a flexible RDBMS called oracle9i. Integrity rules are the laws that govern which operations are allowed on the data and structures of a database.6 The Relational Model The relational model has three major characteristics: Structures Operations Integrity rules Structures are well-defined objects (such as tables. It includes Security features that control how a database is accessed and used.Transaction management operations. Primary key value and column name.Using its features. you can store and manage data with all the advantages of relational structure plus PL/SQL. The change can be splitting the table into many more tables. Comprehensive Data Sub Language According to this rule.Introduction to SQL Page 6 of 71 1. The operations on a database must adhere to a predefined set of integrity rules. Operations are clearly defined actions that enable users to manipulate the data and structures of a database.

MERGE has new syntax that lets you: o o Specify either the update operation or the insert operation. Every object type has a constructor method that makes a new object according to the datatype's specification.8 The Object-Relational Model The object-relational model enables users to define object types. Methods implement specific operations that an application can perform on the data. which makes it possible to store complex business models in a relational database. Oracle extends the relational model to an object-relational model. Methods. 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). Whether directly or indirectly.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. Oracle Application may run on the same computer as the Oracle server. An object type has three kinds of components: A name.7 What is Oracle? Oracle consists of comprehensive set of application building and end-user products. The most widely accepted database model is the relational model. or written in a language such as C or Java and stored externally. and to use these datatypes within the relational model. 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. purchase orders--that application programs deal with. aimed at providing complete information technology solutions. this is achieved through the structured query language. DROP TABLE has a new PURGE clause that lets you drop the table without moving it to the recycle bin. Object types are abstractions of the real-world entities--for example. Attributes model the structure of the real world entity. or both Delete rows from the target table during the update operation . 1. specifying both the structure of the data and the methods of operating on the data. The Object-Relational Model for Database Management Database management systems have evolved from hierarchical to network to relational models. which are functions or procedures written in PL/SQL and stored in the database. which are built-in datatypes or other user-defined types. Among the many application development and end-user products available within the oracle Family there is a common ability to access the database. which serves to identify the object type uniquely. Object types are used to extend the modeling capabilities provided by the native datatypes.Introduction to SQL Page 7 of 71 1. Oracle applications are portable across a wide range of platforms and operating systems from PC’s to large parallel processors. Attributes.

scalability. Oracle Database now performs implicit conversion between CLOB and NCLOB data. systems management. SELECT has new syntax that lets you: o o Issue a versions query. Perform a query on a partitioned outer join. . UPDATE. with these benefits has come an increasing dependence on that infrastructure. A new category of collection functions lets you manipulate nested tables and varrays. View the results of a query as a multidimensional array and perform associated calculations. COLUMN_VALUE Pseudocolumn A new aggregate function COLLECT creates a nested table of the input type out of the rows selected. availability. 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. penalties can be owed. o All of the DML statements (INSERT. which returns all incarnations of the rows returned by the query within a specified SCN or time range. DELETE. increase productivity. Availability Enterprises have used their information technology (IT) infrastructure to provide competitive advantage. and bad press can have a lasting effect on customers and a company’s reputation. 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. and security. You can now specify a LOB column in the UPDATE OF clause when creating an update DML trigger. MERGE) now have an error logging clause "Model Expressions" have been enhanced to allow analytic functions and FOR loops. 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. and empower users to make faster and more informed decisions. New locale-independent format elements have been added to the tables in "Format Models" on page 254. including advancements in Real Application Clusters. The new syntax supports data densification. the entire business can be placed in risk. However. Should a critical application.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. Revenue and customers can be lost. server or data become unavailable. Building a high availability IT infrastructure is critical to the success and well being of all enterprises in today’s fast moving economy.

. and Data Mining built right into the data server where analysis takes place. From storage. to wireless location services and location-enabled e-business. to databases. Oracle Database 10 g . Oracle Application Server 10 g comes with built-in portal and services that allow easy development and delivery of customized intelligent information to all. Through Oracle Spatial and Oracle Locator . and procedural languages (e. Oracle Spatial is an option for Oracle Enterprise Edition that provides advanced spatial features to support high-end GIS and LBS solutions.g. querying. Oracle Database 10 g is an analysis-ready database with ETL. and to provide easy access and distribution of information across the enterprise. 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 Business Intelligence Oracle provides the technology foundation needed to build a complete and integrated solution for Business Intelligence and Data Warehousing. g stand for Grid Computing). 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. Oracle's new technology addresses the requirements of grid computing. Oracle provides many features that allow customers to synchronously and asynchronously integrate their their data including Oracle Streams. The Oracle Database 10 g. geographic and location data are managed in a native type within Oracle Database 10 g . Oracle Application Server 10 g . and distributed SQL. Grid Technology Center Oracle 10g allows companies to begin evolving their IT toward a grid computing model. and Oracle E-Business Suite include and make use of location features to deliver unique business advantages to users. OLAP.Introduction to SQL Page 9 of 71 Trends in computing technology are also enabling a new IT architecture. Oracle Information Integration Information integration is an important feature of Oracle Database. Oracle Database Application Development SQL. Java. and analytic capabilities. Oracle also provides gateways to non-Oracle database servers. Grid computing is a new computing architecture that effectively pools large numbers of servers and storage into a flexible. Oracle MapViewer is an Oracle Application Server Java . and Oracle Developer Suite allow users to rapidly develop and deploy data warehouses and data marts with a complete and integrated array of reporting. 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). application servers. XML. on-demand computing resource for all enterprise computing needs. The table below summarizes the core strengths and capabilities that each brings to the table. Oracle Application Server 10 g . providing seamless interoperation in heterogeneous environments. C/C++) are the core technologies used by application developers today. referred to as Grid computing(in 10g. to build applications. to be deployed. Java. PL/SQL. Any complete application solution must have elements of all three. Oracle Developer Suite comes with tools to build and manage the data warehouse. replication. 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. and applications. Oracle Advanced Queuing.

10. and government organizations worldwide. Application Server Security features. 1. greatly reduced configuration and intuitive day-to-day administration. a user must use a database application and attempt a connection with a valid username of the database. 1. Oracle Platform Security Oracle Platform Security is the set of security capabilities and services implemented in the Oracle Database and Oracle Applicaiton Server. 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 . monitors. The Oracle Database 10g manageability features allow DBAs to become more productive.2 Schema Objects A schema is a collection of logical structures of data. help their organizations reduce management costs. diagnoses and fixes itself. The new self-managing database reduces the costs of managing the IT environment with a simplified install. the XML Center provides you up-to-date content and guidance to develop all types of XML and Web Service applications. and the Oracle Identity Management infrastructure. or advanced XML user. Oracle Spatial and Oracle Locator have also been deployed by telecommunications. Combined. A schema is owned by a database user and has the same name as that user. These consist of Database Security features. To access a database. CPU processing time) for the user 1. 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. these capabilities and services enable the development and deployment of secure e-business applications. intermediate.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. or schema objects.10 Database Users and Schemas Each Oracle database has a list of usernames.10. and scale to manage the Enterprise Computing Grid. Each username has an associated password to prevent unauthorized use.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 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 Database Manageability Oracle10g introduces a sophisticated database that automatically adapts. XML Technology Centre Whether you are a beginner. utilities.

Java sources Materialized views Materialized view logs Object tables Object types Object views Operators Packages Sequences Stored functions.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 Indexes Indextypes Java classes.10. Java resources. stored procedures Synonyms Tables Views Page 11 of 71 1.

or rights. maintain. but powerful. It is physically stored on one of the disks of Disk Drive 1.11 Oracle Products include: SQL.select. It has its own command language for controlling the behavior of the product. 1.) to others allows them to perform operations within their(privilages) Purview. 1. It includes sub-set of SQL commands and is available in the Oracle Server itself. SQL*plus It is an Oracle Product with which SQL and PL/SQL languages may be used. say Tables.delete and update commands -grant and revoke commands -commit.It runs on the browser and access local and remote database. and deleting rows of a table are all DML operations.select. has the sole authority over them.4 Transaction Control Statements .2 Data Manipulation Language (DML) Statements Data manipulation language statements manipulate the database's data. The system tablespace contains several objects (tables and indexes). 1. 1. computer program or instruction.12.rename commands -insert.i SQL*plus and PL/SQL SQL: Structured Query Language is used to access a relational database including Oracle.The owner of database objects. It may be used with each of the Oracle tools where access to the database is required. DDL statements also include statements that permit a user to grant other users the privileges. updating. inserting.drop. These commands do not allow manipulation of values in the database PL/SQL It is the Oracle’s Procedural Language for writing application logic and for manipulating data out side the database. to access the database and specific objects within the database. SQL statements are divided into the following categories: 1.alter.truncate. Locking a table or view and examining the execution plan of an SQL statement are also DML operations.savepoint and rollback commands A SQL statement can be thought of as a very simple. indexes. querying. The data tablespace also contains several objects (tables.12. The datafiles are stored on two of the disks of Disk Drive 1. including the disk that the system tablespace is stored on.Granting privilages(insert. The data tablespace is stored in the DBFILE2 and DBFILE3 datafiles.12 SQL Supports The Following Catagories Of Comands:Data Definition Language Data Manipulation Language Data Control Language Transaction Control Language -create. For example.12.Privilages granted can also be withdrawn by the owner any time. and clusters).Introduction to SQL Page 12 of 71 The image above shows a system tablespace and a data tablespace.1 Data Definition Language (DDL) Statements Data definition language statements define.3 Data control laguage(DCL) statements Data Control Language provides users with privilage commands. and drop schema objects when they are no longer needed. 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.12. The oracle server supports ANSI standard SQL.Statements manipulate data and data definitions in the database. and for formatting the output from SQL Queries..The owner can allow other database users access to the objects as per his/her discretion. 1. The system tablespace is stored in the DBFILE1 datafile.

. multiplication and division are evaluated first . unassigned. Oracle must guarantee that all three SQL statements are performed to maintain the accounts in proper balance. Examples include COMMIT. 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. and record the transaction in the transaction journal. a transaction begins with the user's first executable SQL statement.14 SELECT Statement Select *|{[distinct] column|expression[alias]. 10*sal+300 from emp. If an arithmetic expression contains more than one operator. increase the checking account. According to the ANSI/ISO SQL standard. / divide SQL>select ename. unknown or inapplicable. Arithmetic Expression You can change the way the data is displayed. A select clause specifies the columns to be displayed. sal. the other statements of the transaction must be undone. A transaction ends when it is explicitly committed or rolled back by that user. with which Oracle is compatible. job. 1. Note: Arithmetic expressions containing a null value evaluated to null. SQL>select ename. ROLLBACK. A from clause specifies the table name *Selects all columns Distinct suppress duplicates Selecting all columns SQL> select * from emp.} from table.. and SAVEPOINT.If the operator within an expression are of same priority. A null is not same as zero or a blank space SQL>select ename. SQL>select ename. this is called rolling back. When something prevents one of the statements in the transaction from executing (such as a hardware failure). SQL> select * from dept. Selecting specific columns SQL>select empno. If an error occurs in making any of the updates. sal. then no updates are made. 1.13 Transactions A transaction is a logical unit of work that comprises one or more SQL statements executed by a single user. ename from emp. 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. Consider a banking database. sal*200 from emp. .we can create expressions with number and date data by using arithmetic operators + Add. SQL>select deptno. 10*(sal+300) from emp. *multiply. They enable the user or application developer to group changes into logical transactions. -subtract. dname from dept. comm from emp. sal. 10*(sal+comm) from emp.Introduction to SQL Page 13 of 71 Transaction control statements manage the changes made by DML statements. sal. SQL>select ename. perform calculations or look what if scenarios.

Concatenation operator A concatenation operator concatenates columns or character strings to other columns. 6. sal salary from emp. 7. 13. 9. job.DDL and DML with Examples ? How can you Alias name for a column in Result ? . Questions 1. It requires double quotation marks if it contains spaces or special characters or is case sensitive SQL>select ename "employee name”. 10.Introduction to SQL Page 14 of 71 Defining Column Alias A column alias renames the column heading. 4. 3. 8. 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. 2. 12. 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. 5. SQL>DESCRIBE emp. Two vertical bars represent it ( || ) SQL>select ename || job as "Employees info" from emp. 11. Eliminating Duplicate Rows Eliminate duplicate rows by using the distinct keyword in the Select Clause SQL>select distinct deptno from emp.

2.To arrange the displayed rows. < less than. 2.1.30).1.1.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.1 Comparison operators Comparison conditions are used in conditions that compare one expression to another value or expression = equal to. Restricting and Sorting Data Restrict the rows returned by using the ‘Where’ clause. We Can retrieve only the rows which satisfy the ‘Where’ condition. According to some pre-defined order we can usee the ‘order by’ clause. >= greater than equal to <= less than equal to. The Where clause follows the from clause.1 Between --. 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 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.3 Like condition Match a character pattern Ex: Display employees whose name starts with S SQL>select * from emp where ename like'S%'. <> not equal to Other comparison operators 2. 2. Ex: Display employees whose name contains M as second character . Ex: Display employees whose name ends with T SQL>select * from emp where ename like '%T'. > greater than.Restricting and Sorting Data Page 15 of 67 2.It is also used to arrange rows in the asecending and descending order.

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.Restricting and Sorting Data SQL>select * from emp where ename like'-M%' . This option specifies what the escape character is. Page 16 of 67 You can use the escape identifier to search for the actual % and _symbos. Combinig Wildcard Characters The % and _ symbols can be used in any combination with literal characters.If you Want to search for strings that contain ‘SA_’. Ex: Display the names of the employees who are not entitled to get a comm SQL>select * from emp where comm is null.use The ESCAPE option. EX: 1) SQL>select * from emp where emp_salary > ALL (select emp_salary from emp where emp_job = 'OPERATOR'). 2.ename.When you need to have an exact match for the actual % and _characters. 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 . ANY The ANY operator compares a value to any values in another value set.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. 2) SQL>select * from emp where emp_age <= ALL (select emp_age from emp where emp_state='CA'). Ex: 1) SQL>select * from emp where emp_salary > ANY (select emp_salary from emp where emp_job = 'PROGRAMMER'). It will compares age value to see whether it is less than or equal to all employee's age who is staying in CA.1. It will compares salary value to see whether it is greater than ANY salaries of the employee whose status is programmer.you can use the following Sql statement SQL>select empno.4 ALL and ANY ALL The ALL operator compares a value to all values in another value set. 2. It will compares salary value to see whether it is greater than all salaries of the employee whose status is operator.job from employees where job like ‘%SA\_%’ escape ‘\’.

This example will sample 5% of all formatted database blocks instead of rows. 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.'PRESIDENT').emp FROM (SELECT * FROM dept SAMPLE(5)) t1.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. In the above example. Ex: SELECT * FROM emp SAMPLE(5) BLOCKS.dept. use the ORDER BY clause to display the rows in a specific order. Examples: Ex: SELECT * FROM emp SAMPLE(10). This clause only works for single table queries on local tables. Example: SELECT t1. One way around this is to create an inline view on the driving table of the query with the SAMPLE clause. If you include the SAMPLE clause within a multi-table or remote query. you can order by a column which is not in the select list 2. the order of ORDER BY list is the order of sort. Ex: Display the names and salaries of employees in descending order SQL>select * from emp order by sal desc.Restricting and Sorting Data SQL> Select * from emp where job not in ('MANAGER'. emp t2 WHERE t1. If you examine the execution plan of a "Sample Table Scan". you should see a step like this: TABLE ACCESS (SAMPLE) OF 'EMP' (TABLE) .dep_id. Oracle is instructed to randomly return 10% of the rows in the table. Page 17 of 67 2.dep_id = t2. you will get a parse error or "ORA-30561: SAMPLE option not allowed in statement with multiple table references". the easiest way to randomly select rows from a table is to use the SAMPLE clause with a SELECT statement. t2.4 The SAMPLE Clause From Oracle 8i. we can Sort on multiple columns.

List names of employees who are not managers. 10.ename. 5. List all employees’ names along with their salaries from em table. 9. How To Select Some Rows from a Table? 11. List all the information about all the employees from emptable. List the empno. List the employees who are not eligible for commission 7.who does not report to body. List the names of analyst and salesmen. 3. What is the result of “select 1*NULL” 12. 2. List the employee details not belonging to the department 10 and 20.Restricting and Sorting Data Page 18 of 67 Questions 1. 4. What is the result of “select 'srinivas'+NULL” . 8. List the employee name and hiredate in descending order of hiredate.sal in ascending order of salary.Manager is null) 6. List the name of the employee and designation (job) of the employee.

with all lettters into uppercase.It can also format date and numbers for display. SQL>select LENGHT('SQLfunctions') from dual.15. LPAD:Pads the character value right_justified SQL>select LPAD(sal. DUMMY. INITCAP:converts the first letter of each word to uppercase and remaining letters to lowercase SQL>select INITCAP('SQL functions') from dual. SQL function sometimes take arguments and always return a value. LENGTH: Shows the length of a string as a numeric value.' functions') from dual.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.To manipulate output from groups of rows. INSTR:Finds numeric position of a named character SQL>select INSTR('SQLfunctions'.It can also be used for modifiying individual data items. It contains one columns.'*') from emp. 3.for instance.2 Character Functions: UPPER: This returns char.1. The DUAL table is useful when you want to return a value once only . pseudo_column or expressionthat is not derived from a table with 'user' data. LOWER:This converts the mixed case or uppercase character strings to lower case SQL>select LOWER('ORACLE') from dual.'f') from dual. SQL Functions SQL functions are used to perform calculations on data. the value of a constant. RPAD:pads the character value left_justified . SQL>Select upper('oracle') from dual.1 Types of functions Single Row functions Multiple Row Functions Single Row Functions operate on single rows only and return one result per row. and one row with a value 'X'.5) from dual. 3. CONCAT:Joins values together you are limited to two arguments with concat SQL>select CONCAT('sql '.SQL Functions Page 19 of 71 3. SUBSTR:This extracts a string of determined length SQL>select SUBSTR('SQLfunctions'.

expression. TRIM:Trims heading or trailing characters from a character string SQL>select TRIM('S' FROM 'SSMITHS') from dual. The format of the copy command is: create – If the destination table already exists.3 NUMBER FUNCTIONS ROUND: Rounds value to specified decimal SQL>select Round(35. Page 20 of 71 ASCII: Returns the decimal representation in the database character set of the first character of char. 1.'*') from emp. TRANSLATE: change a character to a new described character SQL>select translate(‘jack’.Round(35. copy will report an error. otherwise the table is created and the data is copied. Otherwise.-2) from dual. 3.2000) from emp where job='SALESMAN'.BL’) FROM DUAL. SQL>select ename. copy reports an error and aborts.823.’b’) from dual.823). otherwise it will create the table and then insert the data. · replace – If the destination table exists.Round(35. 1. MOD:The MOD function finds the remainder of value1 divided by value2. Otherwise. · insert – If the destination table exists.SQL Functions SQL>select RPAD(sal. Ex: SQL> copy from scott/tiger@ORCL92 to scott/tiger@ORCL92 create new_emp using select * from emp. 3.823. Oracle stores dates in an internal numeric format. copy inserts the new rows into the table. The copy command copies data from one Oracle instance to another.2).0). Copy : Oracle SQL*Plus copy command is useful for data transfer between oracle databases. copy will drop and recreate the table with the newly copied data. TRUNC:The TRUNC function truncates the column. SQL>SELECT last_name FROM employees WHERE ASCII(SUBSTR(last_name. REPLACE: to replace a set of characters SQL>SELECT REPLACE(‘JACK AND JUE’.sal.823. representing .-1) from dual.’J’.’j’.823. it will create the table and populate it with the data. The data is simply copied directly from a source to a target. All date functions return a value of DATE datatype except MONTHS_BETWEEN which returns a numeric value.2).4 Date Functions Date functions operate on Oracle dates. or value to n decimal places.TRUNC(35.mod(sal.TRUNC(35.15. SQL>select TRUNC(35.823.)) = 76. · append– Inserts the data into the table if it exists.

For example. it is possible to perform calculations with dates using arithmatic operators such as addition and substraction.next_day(hiredate.sysdate-hiredate From emp Where hiredate like ‘%jun%’. or a character.next_day(hiredate. adds a number of hours to a date producing a date. you can display the current date by selecting SYSDATE from a table.hiredate)>59. but 14 rows of the same SYSDATE would have been returned.hiredate).add_months(hiredate. SQL>select hiredate. Char may be a number representing a day. It is customary to select SYSDATE from a dummy table called DUAL.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.3). 'friday'). the result is negative. The(date1.hiredate+7. SQL>select months_between(sysdate. date2) result can be positive or negative. You can add and subtract number constants as well as other dates from dates. NEXT_DAY(date1. The operations you may perform are: date+number date-number date-date date+number/24 adds a number of days to a date. one for every row of the EMP table. you would have easily selected SYSDATE FROM EMP. Ex: SQL>select hiredate.’05-nov-88’) From emp Where months_between (sysdate. SQL>select hiredate. Using Arithmetic Operators Due to the fact that the date is stored as a number.6) from emp where . if date 1 is earlier than date2. producing a date subtracts number of days from a date. producing a date subtracts one date from another. DUAL is preferred because it conviniently returns one row only.-3) From emp where deptno=20. ADD_MONTHS(date.n) Adds n number of calender months to date n must be an integer and can be negative. producing a number of days. If date1 is later than date2. the result is positive. To display the current date: SQL> select sysdate from dual. MONTHS_BETWEEN finds the number of months between date1 and date2.add_months(hiredate. You can use SYSDATE just as you would use any other column name.months_between(‘01-jan-84’.hiredate-7. subtracting SYSDATE from the HIREDATE column of the EMP table returns the number of days since each employee was hired. char) date of the next specified day of the week(char) following date 1. SYSDATE Is a pseudo-column that returns the current date and time.

SQL>select sysdate. Ex: SQL>select sysdate. TRUNC(date1. then Oracle determines the argument with the highest numeric precedence.round(sysdate.'char') finds the date of first day of the month containing in date1 when char='MONTH'. 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). otherwise returns the first of the following month. This is useful when comparing dates that may have different times.last_day(hiredate).'year') from dual. otherwise returns the first of the following year. ROUND(date1. if char='YEAR'.last_day(‘15-feb-88’) from emp where deptno=20. Output Greatest -------HARRY LEAST returns the least of the list of exprs.'month').'YEAR') returns the first day of the year containing date1 if date1 is in the first half of the year.last_date(sysdate). All exprs after the first are implicitly converted to the datatype of the first expr . 3.'MONTH') returns the first to the month containing date1 if date1 is in the first half of the month. it finds first day of year containing date1.SQL Functions where deptno=10. ROUND(date1. If the first expr is numeric. Oracle Database uses the first expr to determine the return type. TRUNC is useful if you want to remove the time portion of the day.hiredate.round(sysdate. 'HAROLD') "Greatest" FROM DUAL. LAST_DAY(date1) Finds the date of the last day of the month thatcontains date1. and returns that datatype. implicitly converts the remaining arguments to that datatype before the comparison. The time component of the day is in fact removed by default. trunc(sysdate.5 General Comparison Functions GREATEST Returns the greatest of the list of one or more expressions. trunc(sysdate.'year') from dual. Ex: The following statement selects the string with the greatest value: SELECT GREATEST ('HARRY'.'month'). 'HARRIOT'. SQL>select sysdate.

converts the char value representing date. ['fmt']) TO_NUMBER(char) TO_DATE('char'. can include any of the formats listed below. the date is converted to a char value in ORACLE's default date format . . 'date picture') specifies that date is to be converted to a new format an output. To display the time of the day: SQL>select to_char(sysdate. then its datatype is always VARCHAR2. LEAST -----HAROLD 3.DD-MON-YY. FM can be used to suppress leading zeroes for the ddth format. The TO_CHAR function is also used to convert a value of NUMBER data type to a value of CHAR datatype. These conversion functions convert a value from one datatype to another. 3.'$9. If the value returned by this function is character data.SQL Functions Page 23 of 71 before the comparison.7 The RR Date format Element If you use the RR date format element instead of YY.'day. into a date value according to fmt specified.'HARRIOT'. which contains a number to a NUMBER.TO_CHAR can also be used to extract the time of day only.which must be embedded within single quotes. If the 'date picture' is omitted.'HAROLD') "LEAST" FROM DUAL.ddth month yyyy') from dual. 05TH is changed to 5th. If fmt is omitted. Converts number or date to character format fmt. TO_CHAR(number.'fmday. and display it in a specified format. to remove the blank padding use the FM(Fill Mode) prefix: SQL>select to_char(sysdate. the number is converted to a char value.g. Oracle Database compares the exprs using nonpadded comparison semantics.Also note that format models do not affect the actual internal representation of the column value. Day and Month in the output are automatically padded with blanksto a length of 9. The table summarizes the behaviour of the RR element. Note: The 'date picture'. The column and 'date picture' must be separated by a comma.'hh:mi:ss') from dual. ddth month yyyy') from dual.To convert the current date from the default format (DD-MON-YY) to a new 'date picture': SQL>select to_char(sysdate. T0_CHAR(number | date. format is DD-MON-YY.999') from emp. They only affect how the column value is displayed when retrieved with a SELECT statement. the century of the return value varies according to the specified two-digit year and the last two digits of the current year. Ex: The following statement selects the string with the least value: SELECT LEAST('HARRY'.The case in which the 'date picture' is entered is the case in which it will be displayed. converts char. The TO_CHAR function is freequently used to change a date format from the default to an alternative display format. e.'number picture') SQL>select to_char(sal.6 Conversion Functions SQL provides a number of functions to control date type conversions. If the 'number picture' is not specified.'fmt') TO_CHAR TO_CHAR( date.

SQL>select uid from dual. yyyy'). You cannot use USERENV in the condition of a CHECK constraint.to_date(‘19/08/90’.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>UPDATE emp SET hiredate = TO_DATE('1998 05 20'.'month dd. The values for the parameter argument are shown in following table. which return NUMBER. The current audit entry number. SQL>select user from dual. 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. TO_DATE To show all employees hired on June 4. 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. All calls to USERENV return VARCHAR2 data except for calls with the SESSIONID and ENTRYID parameters.which is in varchar2 datatype.hiredate) ] Values(7777. 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.deptno. You cannot use this attribute in distributed SQL statements.20.SQL Functions TO_NUMBER It is used to transform a number stored as a character to numberdatatype: SQL>select empno.’dd/mm/yy’). The audit entryid sequence is shared between fine-grained audit records and regular audit records. The constant is converted to a date and then compared to the HIREDATE value. .job.ename.hiredate from emp where hiredate=to_date('june 4. To enter a row into the EMP table with a non-standard date picture enter: SQL>insert into emp (empno.sal from emp where sal>to_number('1500'). 1984 (non-default format)we can use the TO_DATE function: Page 24 of 71 SQL>select empno.1984'. If you do not want to use the default date format. 3. USERENV Returns information about the current session.'YYYY MM DD') WHERE ename = 'smith'. you must use the TO_DATE function and the appropriate alterantive format mask. user This function returns the login's user name.ename.

LANG returns the ISO abbreviation for the language name. or DELETE operations. the following query returns the rank for a $15. You cannot specify this parameter in distributed SQL statements. this parameter is supported only for remote SELECT statements. In a distributed environment. this parameter returns the identifier for your local session. Rows with equal values for the ranking criteria receive the same rank.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. . This function is useful for top-N and bottom-N reporting. UPDATE.WE8ISO8859P1 Rank RANK calculates the rank of a value in a group of values.05) WITHIN GROUP (ORDER BY salary. LANGUAGE returns the language and territory used by the current session along with the database character set in this form: language_territory. Therefore. not for remote INSERT. As an aggregate function. 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. Aggregate Example The following example calculates the rank of a hypothetical employee in the sample table hr. Oracle Database then adds the number of tied rows to the tied rank to calculate the next rank.500 and a commission of 5%: SELECT RANK(15500.500 salary among the employee salaries: SELECT RANK(15500) WITHIN GROUP (ORDER BY salary DESC) "Rank of 15500" FROM employees. Rank ---------105 Similarly. TERMINAL returns the operating system identifier for the terminal of the current session. In distributed SQL statements. . RANK computes the rank of each row returned from a query with respect to the other rows returned by the query. commission_pct) "Rank" FROM employees. Ex:The following example returns the LANGUAGE parameter of the current session: SELECT USERENV('LANGUAGE') "Language" FROM DUAL.employees with a salary of $15. a shorter form than the existing 'LANGUAGE' parameter. As an analytic function. The return type is NUMBER. the ranks may not be consecutive numbers.characterset SESSIONID returns the auditing session identifier. Output Language ----------------------------------AMERICAN_AMERICA. based on the values of the value_exprs in the order_by_clause. Identical salary values receive the same rank and cause nonconsecutive ranks. RANK calculates the rank of a hypothetical row identified by the arguments of the function with respect to a given sort specification.

nvl(comm.then pairs meets this condition and an else clause exists. salary.result is returned. SQL>select ename.job.1. case CASE expression let you use IF-THEN-ELSE logic in SQL statements without having to invoke procedures.15*sal when 'SALESMAN' then 1.9 Group Functions (or) Multiple Row Functions .3 5 80 Zlotkey 10500 .3 3 80 Ozer 11500 .sal case job when 'CLERK' then 1.'CLERK'.1. SQL>select ename.THEN pair for which expr is equal to comparision_expr and return return_expr. vsize The function returns the number of bytes in the expression if expression is null it returns null SQL>select vsize('hello') from dual.20*sal else sal end from emp. commission_pct) "Rank" FROM employees WHERE department_id = 80. DEPARTMENT_ID LAST_NAME SALARY COMMISSION_PCT Rank ------------.20*sal. RANK() OVER (PARTITION BY department_id ORDER BY salary DESC. Page 26 of 71 In this query Oracle searches for the first WHEN. DECODE function The decode function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various languages.'MANAGER'. commission_pct.25 4 80 Cambrault 11000 .------------------------.job.1.15*sal. 'SALESMAN'. 3. some of these are just puerly mathematical functions.sal) "revised salary" from emp.A group function returns a result based on a group of rows.SQL Functions SELECT department_id.---------.3 5 80 Abel 11000 .. SQL>select ename. if the expression is same as search. last_name. .3 2 80 Errazuriz 12000 .10*sal when 'MANAGER' then 1.10*sal.2 7 nvi This function is used in case where we want to consider Null values as zero. then Oracle returns else_expr.----------------------------------------------80 Russell 14000 . DECODE(job.4 1 80 Partners 13500 .-------------. The DECODE function decodes expression after comparing it to each search valu.sal.If none of when. other wise oracle returns null.0) 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.sum(sal) . 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.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. SQL>select count(*) from emp.count(*) from emp group by job. 3. Ex: Display no of employees under each job catageory SQL>select job.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. Count It counts all rows.inclusive of duplicates and nulls.11 Use the HAVING clause to restrict groups: Rows are grouped The group function is applied Group matching the having clause are displayed.sum(sal) from emp group by deptno. 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. 3. Ex: Display sum of salaries department wise SQL> select deptno. Ex:Display the total salary of department 20 SQL>select deptno.

List the average salary and number mployees working in the department 20.---------. 8. 14.3 3 80 Ozer 11500 .25 4 80 Cambrault 11000 . 7. List the minimum salary from em table. RANK() OVER (PARTITION BY department_id ORDER BY salary DESC.3 5 80 Abel 11000 . SELECT department_id. last_name. commission_pct. 12.for department number 20 only. Example as shown below.maximum and minimum salary and the average salary of employees job Wise. List the department numbers and number of employees in each department. List the total salary. 2.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. List the number of jobs available in the em table. 10.------------------------. 3.3 5 80 Zlotkey 10500 .-----------------------------------------------------------80 Russell 14000 . you must have a GROUP BY clause as well as the HAVING clause.3 2 80 Errazuriz 12000 . 6. 4.-------------.SQL Functions Page 28 of 71 from emp group by deptno Having deptno=20. List the employee name ending with an ‘S’ List the employee names having ‘I’ as the second character. commission_pct) "Rank" FROM employees WHERE department_id = 80.4 1 80 Partners 13500 . DEPARTMENT_ID LAST_NAME SALARY COMMISSION_PCT Rank ------------. 9. 11. List the maximum salary of employee working as salesman. 5. List the average salary for all departments employing more than five people.2 7 Questions 1. 13.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. salary. List the number of employees working with the company. 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? . Ex:Display the deptno and average salaries of all departments whose maximum salary is greater than 3000 SQL>select deptno. 3.

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

ename. such a condition is called a join condition.Displaying data from Multiple Tables Page 30 of 71 4. Oracle performs a join whenever Multiple tables appear in the queries FROM clause. Join condition: Most join queries contain WHERE clause conditions that compare two columns. location and department of employees Whose salary is more than 1500 a month SQL>select ename.To execute a join of three or more tables. you must qualify all references to these columns throughout the query with table names to avoid ambiguity. dept where emp. Table aliases help to keep SQL code smaller. 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 (>.deptno=dept. <. dept Where emp.2 Relating data through join concept Join is a query that combines rows from two or more tables or views. The Columns in the join conditions need not also appear in the select list.sal. The query’s select list can select any columns from any of these tables. Oracle continues this process until all tables are joined into the result. dname from emp.3 Simple join It is the most common type of join. is called an equi-join. each containing one row from each table for which the join condition evaluates to TRUE. There are basically three different types of joins. It retrieves from two tables having a common column and is further classified into equi-join and non equi-join A join. loc location from emp. To execute a join Oracle combines pairs of rows. salgrade . 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. <=. therefore using less memory. >=.deptno Order by deptno desc Ex:Display the name. each from a different table.deptno and loc=’NEWYORK’ 4. If any two of these tables have a column name in common.deptno=dept. e. particularly if table names are lengthy. <>) other than equal to (=) Ex:Display the employee’s salary grade SQL>select e. e.deptno=dept. 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. Ex:Display all employee name and their department name in desc order of the department name SQL>select ename. dept Where emp. which is based on equalities. dname from emp. sal.grade from emp.deptno and sal>1500 Ex:Display all employees working in newyork SQL> select ename.

dname. Oracle combines each row of one table with each row of the other.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. . Ex:Display all information along with the departments that do not have employees SQL>select ename. Oracle returns their Cartesian product.sal > e2. 4. grade from emp. To perform a self join.000 rows. each with 100 rows.sal.salgrade where sal between losal and hisal grade =3. A Cartesian product always generates many rows and is rarely useful. For example.empno.sal.6 Self Joins A self join is a join of a table to itself.deptno(+) =dept.deptno from emp. has 10. The outer join operator can appear on only on one side of the expression . Ex:Display employees whose salary is greater than their boss salary SQL>select e1. Always include a join condition unless you specifically need a Cartesian product. the Cartesian product of two tables. sal.mgr=manager.deptno 4. Ex:Display all employees on grade 3 SQL>select ename.ename||’works for’||manager.ename from emp worker.emp e2 where e1.8 Cartesian Products If two tables in a join query have no join condition. Page 31 of 71 4. the optimizer may choose a join order that avoids producing an intermediate Cartesian product.job.mgr=e2. To find the name of each employee’s manager. job. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition. If a query joins three or more tables and you do not specify a join condition for a specific pair. Oracle combines and returns rows of the table that satisfy the join condition.the side that has information missing.emp manager where worker. It returns those rows from one table that have no direct match in the other table.you need to join the employees table to itself.or perform a selfjoin.ename from emp e1.Displaying data from Multiple Tables where sal between losal and hisal.7 Outer join The outer join extends the result of a simple join. Ex:Display the name and their manager name SQL>select worker.empno and e1.dept.

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

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. and DELETE statements To define a table to be operated on by a containing query.The From clause. 5.Subqueries are used to retrieve data from tables that depend on the values in the table itself.A statement containing a subquery is called a parent statement.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 . Outer references ("left-correlated subqueries") are allowed only in the FROM clause of a SELECT statement. or START WITH clause of SELECT. You do this by placing the subquery in the FROM clause of the containing query as you would a table name.and the results are returned into the having clause of the main query. and DELETE statements. not outer references. Using Having clause with subqueries You can use subqueries not only in the where clause. UPDATE. 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. SUB QUERIES A subquery is a form of select statement which appears inside another sql statement.job from emp where job=(select job from emp where ename='BLAKE'). UPDATE. HAVING clause. You may use subqueries in place of tables in this way as well in INSERT. Subqueries so used can employ correlation variables.The Oracle server executes the subquery . Ex: Display the employees who earns the minimum salary in the company SQL>select * from emp where sal=(select min(sal) from emp).job. 5. but only those defined within the subquery itself.3 Executing Single-Row Subqueries Ex: Display the employees whose job is same as that of 7788 SQL>select ename.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.Sub Queries Page 33 of 71 5. .but also in the having clause. 5. Note: the inner query returns a value that is used by the outer query or the main query.

Ex: Display the employees who are not managers and whose salary is less than that of any Manager SQL>select empno. returning values to be used by the main query.avg(sal) from emp group by job having avg(sal) = (select min(avg(sal))from emp group by job).instead of a single row operator.The multiple row operator expects one or more values.deptno from emp e where sal>(select avg(sal) from emp where deptno = e. .ALL Ex: Display employees who earn the lowest salary in each department SQL>select ename. A correlated subquery is identified by the use of an outer query's column in the inner query's predicate cluase. the inner select runs first and it executes once. With a normal nested subquery.sal from emp where sal<any(select sal from emp where job='MANAGER').sal. This causes the correlated subquery to be processed in a different way from the ordinary nested subquery. We can use a correlated subquery to find employees who earn a salary greater than the average salary for their department: SQL> select empno.deptno) order by deptno. Execute inner query using candidate row's value. 3. 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.deptno from emp where sal in(select min(sal) from emp group by deptno).sal. on the other hand. Note that the alias is necessary only to avoid ambiguity in column names.ename. Although the correlated subquery executes repeatedly. Now.job. Repeat until no candidate row remains. Page 34 of 71 5. there is no suggestion that correlated subqueries are less efficient than ordinary non-correlated subqueries. The multiple row comparision operators are IN. 5.with a multiple-row subquery. 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. 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.Sub Queries Ex: Find the job with the lowest average salary SQL>select job.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.ename.ANY. executes once for each row(candidate row) considered by the outer query. Use value(s) resulting from the inner query to qualify or disqualify candidate 4. once for each in the main query.4 Multiple-Row subqueries subqueries that return more than one row are called multiple-row subqueries you use multiple row operator. A correlated subquery.

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

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

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

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

You can then select the empty LOB attribute and populate it using the DBMS_LOB package or some other appropriate interface. 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.alter the structure of an object and also to drop the object created. BFILE Datatype The BFILE datatype enables access to binary file LOBs that are stored in file systems outside the Oracle database. piece-wise access to and manipulation of data. 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. 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. Both fixed-width and variable-width character sets are supported. to access and populate a LOB attribute that is part of an object type. The tables of a database hold all of the useraccessible data. random. or the OCI participate fully in the transaction. You can select LOB columns and LOB attributes. BLOBs have full transactional support. 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. Changes made through SQL. Note: Currently varchar is equivalent to varchar2 datatype. Changes made through SQL. the DBMS_LOB package. or NUMBER).2 Data Definition Language Data Definition Language is used to create an object. Each column is given a column name. and both use the CHAR database character set.SQL . empty. Every table is defined with a table name and set of columns. However. You can delete a row containing a LOB column or LOB attribute and thereby also delete the LOB value. a datatype (such as CHAR. Note that for BFILEs. Table Definition: A table is a unit of storage that hold data in the form of rows and columns. CLOB value manipulations can be committed and rolled back. BLOBs can store up to 4 gigabytes of binary data.Constraints Page 39 of 71 LOBs permit efficient. CLOB Datatype The CLOB datatype stores single-byte and multibyte character data. You can set the BFILE to NULL or make it point to a different file. However. and a width (which could be . CLOBs have full transactional support. BLOBs can be thought of as bitstreams with no character set semantics. You can define more than one LOB column in a table. you can define one or more LOB attributes in an object. Table data is stored in rows and columns. or the OCI participate fully in the transaction. the DBMS_LOB package. which serves as a pointer to a binary file on the server's file system. or replace the entire LOB with data. 6. you must first initialize the LOB attribute using the EMPTY_CLOB or EMPTY_BLOB function. CLOBs can store up to 4 gigabytes of character data. However. With the exception of NCLOB. BLOB value manipulations can be committed and rolled back. BLOB Datatype The BLOB datatype stores unstructured binary large objects. (You can set the internal LOB value to NULL. DATE.1 Create table command: A table is the basic unit of data storage in an Oracle database. You can declare LOB bind variables.) You can update a LOB row/column intersection or a LOB attribute with another LOB row/column intersection or LOB attribute. the actual operating system file is not deleted. A BFILE column or attribute stores a BFILE locator. The locator maintains the directory alias and the filename.2. 6.

you can define additional columns. Prior to this it was neccessary to drop the entire table and rebuild it.. and integrity constraints with the ADD clause of the ALTER TABLE statement. alter table <table name> add (column definition. course varchar2(10)).SQL .). 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.name varchar2(10). ALTER TABLE table_name SET UNUSED (column_name1. 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.).. The table's rows can then be queried. deleted.. partitions. valid rows of data can be inserted into it. 6.. as in DATE) or scale and precision (for the NUMBER datatype only). 6. or updated. Logical Delete Physical Delete Logical Delete On large tables the process of physically removing a column can be very time and resource consuming.. Tables are created with no data unless a query is specified. Once a table is created. You can add rows to a table with the INSERT statement.Constraints Page 40 of 71 predetermined by the datatype. Syntax Create table <table_name> (column definition1. .. column_name2).2.column definition2.3 Command to rename a column Syntax: Alter table <tablename> rename column <column name>. SQL>create table student(id number..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. You can change the definition of an existing column or partition with the MODIFY clause of the ALTER TABLE statement. For this reason you may decide to logically delete it: ALTER TABLE table_name SET UNUSED (column_name).2..numerals and letters are allowed but not blank space and single quotes.2 Command To alter a table alter table <table name> modify (column definition. Now you can mark a column as unused (logical delete) or delete it completely (physical delete).).. After creating a table.2.

Physical Delete To physically drop a column you can use one of the following syntaxes. Delete 6. It has no affect on the actual data. The DBA_UNUSED_COL_TABS view can be used to view the number of unused columns per table. 6. which resides outside of the database.we can use the drop table command supported by SQL.date. Syntax: drop table <table_name> Note: For an external table. 6. Use the DROP TABLE statement to remove a table or an object table and all its data from the database. this statement removes only the table metadata in the database. ALTER TABLE table_name DROP (column_name1.SQL . pdate.char.long are enclosed in single quotes. .While using this command the values are separated by commas and the datatypes varchar2.3.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. depending on whether you wish to drop a single or multiple columns: ALTER TABLE table_name DROP COLUMN column_name.Constraints Page 41 of 71 Once this is done the columns will no longer be visible to the user. 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.3 Data Manipulation Language Data manipulation Commands are the most frequently used SQL commands. Dropping a column from a table will cause all unused columns in that table to be dropped at the same time.1 Insert Command The insert command is used to add one or more rows to a table. 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.6 Command to Drop a table In order to drop a table. Syntax: Truncate table<table_name> 6. The DML commands are Insert. The values must be entered in the same order as they are defined in the table. column_name2).2.

. 6. syntax update table_name set field=value.4 Datacontrol Language Commands 6.3. 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).object_id.SQL .the appropriate privilages can be granted on that particular object to others.status.object_id) WHEN MATCHED THEN UPDATE SET t. one for insert and one for update. In 10g. 6. Using the MERGE command.the user wants to share an object with others.Specific rows could be updated based on a specific condition. we can write insert and update statement using single SQL statement rather than coding two separate sets of SQLs. Oracle made some enhancements to MERGE command. object_name.created WHEN NOT MATCHED THEN INSERT (t.there is no necessity for the user to be given Any privilages to use its being its creator.object_name.1 Grant privilage command If The user creates a table. status. Let us see that with example.4 Merge Command Oracle introduced MERGE command in version 9i.created) / 6. when we use MERGE command. both these clauses are optional and we can use any one of them to insert new records or to update the existing records.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.object_name. We can also specify ALL to grant all the privilages. created FROM user_objects) u ON (t. we have to use both these clauses.object_id. u. WHEN MATCHED THEN (used for updating existing records) and WHEN NOT MATCHED THEN (used for inserting new records). 6.Constraints Syntax: insert into <table_name> values (a list of values).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.In case.status. It is also known as UPSERT (Insert and Update statement together). t..4. u. Object privilages can be granted to others using the SQL command GRANT ..the user inherits authority over the table.A single column may be updated or more than one column could be updated .3.synonyms etc. t. Syntax: delete from <table_name> where conditions.sequences. Indexes. It contains two clauses.3.views. With the update command we can update rows in the table.CREATE_DATE = u.create_date) VALUES (u. Objects are logical data storage structures like tables. In 9i. In release 10g.object_id = u. MERGE INTO test t USING (SELECT object_id.where condition. t. u.

Normally. B. or DELETE statement.Only with the help of the commit command. In SQL. Page 43 of 71 6. For example.Constraints Syntax Grant privilages on <object_name> to <username>. then roll back to savepoint B. However.SQL . Commit: This command is used to end a transaction. the host environment determines what is rolled back. . An integrity Constraint is a mechanism used by Oracle to prevent invalid data entry into the table. Syntax: Revoke privilage on<object_name> from <username>.Commit and rollback controls the transaction with the database. Savepoint Savepoints are like markers to divide a very lengthy transaction to smaller ones. and D in that order. This command is closely similar to that of the grant command . PL/SQL does not support this clause.4. Rollback work. not the whole transaction. This integrity can be applied to different degrees of severity. Transaction changes can be made permanent to the database.(OR) COMMIT. UPDATE.They are used to identify a point in A transaction to which we cam latter rollback. An implicit savepoint is marked before executing an INSERT. Rollback A rollback command is used to undo the work done in the current transaction.2 Revoke privilage command To withdraw the privilage that has been granted to a user. In other words constraints are used for enforcing rules that the columns in a table have to conform with. However. All savepoints marked after the savepoint to which you roll back are erased. 6. a rollback to the implicit savepoint is done. If the statement fails.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. the savepoint to which you roll back is not erased. COMMIT WORK. if you mark savepoints A.5 Transaction Control Language A Transaction is a logical unit of work. This command also erases all savepoints in the transaction thus releasing the transaction locks. C. However. just the failed SQL statement is rolled back. To rollback to a particular stage in a transaction. For example.or rollback a transaction to a savepoint So that the SQL statements after the savepoint are rolled back.or Rollback.we use the revoke command.a savepoint Rollback to savepoint save_pt. if the statement raises an unhandled exception. only savepoints C and D are erased.Thus savepoints is used in conjuction with rollback portions of current transaction. the following statement is illegal: Savepoint savepoint_id. the FORCE clause manually rolls back an in-doubt distributed transaction.We can either rollback The entire transaction so that all changes mader by sql statements are undone.

When the demarcation specified in this range is violated Oracle rejects the record. Not null constraint Check constraint By default the tables can contain null values.6. After a constraint is defined. the table containing the foreign key is called the child table and the table containing the referenced key is called the parent table.SQL . . the constraint cannot be enforced. it need only be changed once at the database level and not many times for each application.6.3 Referential integrity constraint This enforces relationship between tables. Integrity constraints are defined with a table and are stored as part of the table's definition. the statement is rolled back and an error is returned. The primary key constraint just like the former avoids duplication of values. Page 44 of 71 6. Oracle will not validate the record until this is satisfied. . 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. This constraint allows only unique values to be stored in the column Oracle rejects duplication of records when the unique key constraint is used. In this relationship. The foreign key establishes a relationship with a specified primary or unique key in the another table.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.6 Integrity Constraints An integrity constraint is a declarative way to define a business rule for a column of a table. The enforcement of Not Null constraints in a table essures that the table contains values.6.1 Domain Integrity Constraints: These constraints set a range. It designates a column or combination of columns as a foreign key. centrally in the database's data dictionary. 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 primary key constraint is similar to the unique key constraint. Its need is best felt when a relation has to be set between tables. This can be defined to allow only a particular range of values.Constraints Where save_pt is the savepoint. so that all database applications must adhere to the same set of rules. If a rule changes. The other type of constraint available under this classification is the 'check' constraint. called the referenced key.A composite primary key is created by using the table level definition 6. The following are the various types of integrity constraints:• • • Domain integrity constraints Entity integrity constraints Referential integrity constraints 6. if any of the results of a DML statement violate the integrity constraint. 6. because in addition to preventing duplication it also does not allow null values.A unique index is automatically created for a primary key .

. let us look at how to impose all these constraints as per the need 6. Loc varcahr2(13)..SQL . deptno number(2) not null. ………….…. .] table (column datatype [default expr] [column_constraint]. We cannot define a Not null constraint at table level SQL>create table dept( Deptno number(2). Note: Identifies the table and column in the parent table.. column level constraint column [constraint constraint_name] constraint_type.4 Define Constriants Create table [schema. On delete cascade .deptno number(2). Ename varchar2(10)..Constraints Page 45 of 71 One can either enable or disable a constraint. [constraint constraint_name] constraint_type (column. On the other hand.6.. ………. Table level constraint Column.. Note: constraints are usually created at the same time as the table. deptno number(2) constraint emp_deptno_fk references dept(deptno). 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. Now. [table_constraint][. A single column can have multiple check constraints that reference the column in its definition . ……. Create table emp( Empno number(4). the constraint would be enabled. it holds good only for the column for which it is defined. SQL>create table emp(empno number.. Dname varchar2(14). Constraint dept_dname_uk unique(dname).Constraints can be added to a table after its creation and also temporarily disabled.….). ……. ). The foreign key constraint SQL>create table emp (…. Constraint dept_deptno_pk primary key(deptno)).]). if it is defined at the column level. Further we can define a constraint either at table or column level.There is no limit to the number of check constraints CHECK constraint can be defined at the column level or table level.….. By default. constraint emp_empno_pk primary key(empno)).allows deletion in the parent table and deletion of the Dependent rows in the child table.

Disabling Constraints Execute the disable clause of the alter table statement to deactivate an integrity constraint ALTER TABLE table DISABLE CONSTRAINT constraint CASCADE. Dropping A Constraint remove the manager constraint from the emp table SQL> alter table emp drop constraint emp_mgr_fk.SQL . Enabling Constraint Activating an integrity constraint currently disabled in the table definition by using The ENABLE clause.but we cannot modify a constraint.deptno column. . Note: 1.… Page 46 of 71 6. SQL>alter table dept drop primary key cascade. 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. we can add or drop a constraint. 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). ALTER TABLE table_name ENABLE CONSTRAINT constraint_name. 2. Remove the primary key constraint on the dept table and drop the associated foreign key Constraint on the emp.Constraints constraint emp_deptno_ck check(deptno between 10 and 99).7 Adding a Constriant by using Alter Command Alter table table_name add [constraint constraint_name] constraint_type (column). This constraint ensures that a manager exists as a valid employee in the emp table. We can enable or disable a constraint 3.

Why does the primary key constraint automatically enforces a NOT NULL constraint. Modify the emp table. Write the command to change the department of king to 40. 8. 4. 5. 9. 2.Do a couple COMMIT and ROLLBACK operations and Record your observations. Write a statement to grant INSERT privilage on the empno column of the emp Table to SCOTT. Write the syntax for inserting the selective columns in a table. Differentiate Drop. What is referential integrity? 16. 11. How many columns can be set as primary key in sql? 17. Write a command to Delete the table .add constraint CHECK for SAL of TABLE EMP(condition will be salary should be greater than 2500) 13. 3. Modify the sal column of the emp table to not null and increase its size to 10 10. Write the command to give everybody a commision of 500.set appropriate save points.Constraints Page 47 of 71 Questions 1. While working . 7.which will hold the grades for each employee 14.SQL . Add a column to the existing table emp.Delete and Truncate commands ? . 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. Display a columns and constriants of table emp. Delete the records of clerk. 12. 15. 6.

1 Synonyms A synonym is a database object. it requires no storage other than its definition in the data dictionary. including its location in a distributed system.A sequence can be either in an ascending or a descending order.sequential integer values. It can be used to automatically generate primary key or unique key values. . or package.which is available only to that person whereas the latter is created by DBA . then only the synonym needs to be redefined.2 Sequences: Asequence is a database object.which we use for selecting the tables owned by the user. 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. DATABASE OBJECTS The various database objects are Synonym Sequences views Indexes 7.delete. syntax: create [public] synonym <synonym_name> for <table_name>. procedure.which is used as an alias(alternative name) for a table.views or sequence. Note: To get the details of the sequences that the user has created we use USER__SYNONYMS 7. SQL>create synonym e for emp. A private synonym is in the schema of a specific user who has control over its availability to others. Public synonyms are created by database administrator to hide the identity of the base table and reduce the complexity of SQL statements. Because a synonym is simply an alias. view. The synonym is just an alias of the table and all the manipulations on it actually effect the table. materialized view.which can generate unique. function. Synonym can be private or public.These public synonyms are owned by user group PUBLIC. Applications based on the synonym continue to function without modification. Synonyms are often used for security and convenience. A public synonym is owned by the special user group named PUBLIC and every user in a database can access it. A synonym is an alias for any table. Synonyms are very useful in both distributed and nondistributed database environments because they hide the identity of the underlying object. sequence.SQL – Enhancements to Group by Clause Page 48 of 71 7. For example.which can be availed by any database user.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.One such public synonym is TAB. When a grant is given to a other user on this synonym he can perform DML operations such as insert. This is advantageous because if the underlying object must be renamed or moved.The former is created by normal user.

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.

7.job_id. We cn even insert rows into the view.then we cannot insert tows. Performing “Top_N” Analysis Syntax: select [column_list].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. which are not selected in view query were assigned as not null.sal from emp Order by sal desc) Where rownum<=3.last_name.sal From (select ename. To display the four most senior employees of a company SQL>select rownum as senior .ename. .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. Note: USER_VIEWS will provide details on VIEWS that the user has created.If any of the table columns.provided other columns in the base table accept null vaules.department_id from emp where deptno=10 with check option.hiredate from emp order by hiredate) E Where rownum<=4.e.SQL – Enhancements to Group by Clause Page 52 of 71 SQL>Create or replace view vemp as select employee_id.e.hiredate From (select ename. Output The following command creates a view with specific columns and we try to update any other columns it gives a error.ename.manager_id.

all applications continue to work.5.We create an index on a column or combinations of columns. Given a data value that has been indexed. Just as the index in this manual helps you locate information faster than if there were no index. The index points directly to the location of the rows containg the value. Oracle recommends that unique indexes be created explicitly.5 INDEX Indexs are optional structures associated with tables. the presence of many indexes on a table decreases the performance of updates. Oracle automatically reflects changes to data. the following statements specify valid combinations: SQL>create index emp_idx1 on emp (ename. job). access of previously indexed data can be slower. updating rows. ename). and inserts.an Oracle index provides a faster access path to table data. Retrieval performance of indexed data remains almost constant. This results in a much faster index build. However. 7. You can create more than one index using the same columns if you specify distinctly different combinations of the columns. The optimizer can use an existing index to build another index. Indexes are optional structures associated with tables and clusters. Similar to the indexes in books that help us to locate information faster. as independent structures.SQL – Enhancements to Group by Clause Page 53 of 71 7. require storage space. Unique indexes guarantee that no two rows of a table have duplicate values in the key column (or columns). . Oracle automatically maintains and uses indexes after they are created. an Oracle index provides a faster access path to table data. and not through enabling a unique constraint on a table. However. the index points directly to the location of the rows containing that value.Indexes are the primary means of reducing disk I/O when properly used appropriately. You can create or drop an index at any time without affecting the base tables or other indexes. Indexes. SQL>create index emp_idx2 on emp (job. deletes. If you drop an index. 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. or deleting rows. We can create indexes explicitly to speed up sql statement execution on a table. even as new rows are inserted. Nonunique indexes do not impose this restriction on the column values. You can create indexes on one or more columns of a table to speed SQL statement execution on that table. because Oracle must also update the indexes associated with the table. Oracle provides several indexing schemes. You cannot create an index that references only one column in a table if another such index already exists. It affects only the speed of execution. For example.1 Unique and Nonunique Indexes Indexes can be unique or nonunique. You can create many indexes for a table as long as the combination of columns differs for each index. The absence or presence of an index does not require a change in the wording of any SQL statement. in all relevant indexes with no additional action by users. such as adding new rows. Indexes are the primary means of reducing disk I/O when properly used. An index is merely a fast access path to the data. Indexes are logically and physically independent of the data in the associated table.

Oracle enforces UNIQUE integrity constraints by automatically defining a unique index on the unique key. Usually. or delete a value of the ROWID pseudocolumn. . Oracle reads the data dictionary to verify that schema objects exist and that users have proper access to them. This statement selects the address of all rows that contain data for employees in department 20: Ex: 1. However. For example. SQL>select rowid. update. An Oracle data dictionary is a set of tables and views that are used as a read-only reference about the database.0) IN (SELECT ROWID. a data dictionary stores information about both the logical and physical structure of the database. If you delete a row. To accurately reflect the status of the database at all times. rows in different tables that are stored together in the same cluster can have the same rowid. You cannot insert. Oracle may reassign its rowid to a new row inserted later. For example. the ROWID pseudocolumn returns a row's address. it is advisable that any index that exists for query performance. The file number is relative to the tablespace. They can show you how a table's rows are stored. 7. for example. during database operation. and conduct ongoing work.7 ROWID For each row in the database.6 Data Dictionary Each Oracle database has a data dictionary. 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). Although you can use the ROWID pseudocolumn in the SELECT and WHERE clause of a query. The data dictionary is critical to the operation of the database. a rowid value uniquely identifies a row in the database. In addition to this valuable information.select Every 4th row from emp table SELECT * FROM emp WHERE (ROWID. you can define UNIQUE integrity constraints on the desired columns. Ename from emp where deptno = 20. If you delete and reinsert a row with the Import and Export utilities. including unique indexes. 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. verify. 7.SQL – Enhancements to Group by Clause Page 54 of 71 Alternatively. You should not use ROWID as a table's primary key. MOD(ROWNUM. which relies on the data dictionary to record. be created explicitly. these pseudocolumn values are not actually stored in the database. its rowid may change.4) FROM emp). the data dictionary is automatically updated by Oracle in response to specific actions (such as when the structure of the database is altered). However. They are unique identifiers for rows in a table. 2. 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.

6. Questions 1.8 ROWNUM For each row returned by a query. the following statement will not have the same effect as the preceding example: SQL>select * from emp where rownum < 4 order by sal. For example.sal.ename. How can you retrive Rows from 10 to 20 of Emp Table ? 11. the second has 2. as in this example: SQL>select * from emp where rownum < 10. This is sometimes referred to as a "top-N query": SQL>select * from(select * from emp order by sal) where rownum < 4. 5. the following query returns the top 3 earners in a company. Delete the indexes that are no longer needed.deptno and dname. Create index on ename column of emp table. 3. you can force the ROWNUM condition to be applied after the ordering of the rows. 8. 4. 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. the rows will be reordered by the ORDER BY clause. 7. How does a view differ from a table Create a view empview.which will contain the empno. the ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. If an ORDER BY clause follows ROWNUM in the same query.SQL – Enhancements to Group by Clause Page 55 of 71 7. In what situation must a sequence be used. Therefore. Oracle may retrieve the rows in a different order than without the index. For example. What is the data dictionary view to see the sequence. How can you eliminate a Column from a Table ? . You can use ROWNUM to limit the number of rows returned by a query. 2. The first row selected has a ROWNUM of 1. so they are generated after the rows have already been ordered by sal in the subquery. if the ORDER BY clause causes Oracle to use an index to access the data. In the preceding example. and so on. The results can vary depending on the way the rows are accessed. 9. the ROWNUM values are those of the top-level SELECT statement. If you embed the ORDER BY clause in a subquery and place the ROWNUM condition in the top-level query.

job). ROLLUP operator Select [column.a process called treewalking Enables the hierarchy to be construted.you can retrieve data based on a natural hierarchical relationship between Rows in a table..where A hierarchical relationship exists between the rows of a single table.2 Hierarchical Retrieval Using hierarchical queries .SQL – Enhancements to Group by Clause Page 56 of 71 8. From table [where condition] [group by [Rollup] group_by_expression] [having having_expression]. 8. The number of extra groups in the result set is determined by the number of columns included in the GROUP BY clause. From table_name [Where condition] [Group by [CUBE] group_by_expression] [HAVING having_expression] [ORDER BY column].However .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 CUBE operator is used with an aggregate function to generate additional rows in a result set. SQL>select deptno.A hierarchical query is a method of reporting. [order by column]. Select [LEVEL].] group_function(column)….sum(sal) from emp Where deptno<30 group by rollup(deptno.pseudocolumn .1 Group by with ROLLUP and CUBE operators Use ROLLUP and GROUP BY to produce superaggregate rows by cross-referencing columns. Enhancements to “GROUP BY” Clause 8. The ROLLUP and CUBE operators are available only in Oracle8i and later releases. CUBE grouping produces a results set containing the rows from ROLLUP and cross-tabulation rows. SQL>select deptno. the branches of a tree.] group_function (COLUMN)….job.in order. ROLLUP grouping produces a result set containing the regular grouped rows and the subtotal values.job.the LEVEL. Rollup is an extension to group by clause.A relational database does not store records in a hierarchical way.sum(sal) From emp where deptno<30 Group by cube(deptno.column. CUBE operator Select [column.job).

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). 1. and so on specifies the table. With Oracle9i multitable INSERT statements is one of the techniques for implementing SQL data transformations. Note: Hierarchical trees are used in various fields such as corporate management(management hierarchies).3 Oracle9i Extensions To DML AND DDL Statements Overview of multitable INSERT Statements The INSERT…SELECCT 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.or snapshot containing the columns. They provide significant performance improvement over Single DML versus multiple INSERT…SELECT statements Single DML versus a procedure to do multiple inserts using IF…THEN syntax.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.mgr From emp Start with empno=7788 Connect by prior mgr=empno. Once the data is loaded into a oracle9i.job.This clause is Required for a true hierarchical query Specifies the columns in which the relationship between parent and child Rows exist.2 for a child of a root. 8. data transformations can be executed using SQL operations. Manaufacturing (product assembly).database. 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 . and scientific research The SELECT statement cannot contain a join or query from a view that contains a join.This clause is required for a hierarchical query.Walking the tree:From the Bottom Up SQL>select empno.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.ename.view.

hiredate) Else Into hire_tab values(deptno.sales_source_data. Tables using a multitable insert SQL>insert all into salary values(empno.hiredate.sum(sal). sales_tue.sal) select empno.mgr.sales_thur.sales_fri You would want to store these records in the sales_info table in a more typical relational format Employee_id. Pivoting Insert Suppose you receive a set of sales records from a nonrelational database table Sales_source_data in the following format Employee_id. is converted into five records for the data warehouses sales_info table.sal) when mgr >7500 then into mgr values(empno.sal) into manager values(empno.2) .hiredate.week.sales Using pivoting insert .hiredate) Select deptno. Note:make sure hire_tab_00. You need to build a transformation such that each record from the original nonrelational database table.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.hire_tab_99.mgr from emp where sal >3000.mgr from emp where empno >7700.sal) select empno.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.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.hiredate.hire_tab tables exists with proper structure before executing this statement.max(hiredate) from emp group by deptno. Page 58 of 71 If the sum(sal) is greater than 25000 then insert these values into the special sal.hiredate) When hiredate like (‘%99%’) then Into hire_tab_99 values(deptno.sal.mgr.hiredate sal and mgr values from the emp table for those employees whose SAL >3000 insert these values into two tables salary and manager.hiredate. conditional insert all SQL>insert all when sal>4000 then into salary values(empno.convert the set of sales records from the nonrelational database tables to Relational format.sal.sales_mon.week_id.sales_wed.

week_id.sales_mon.SQL – Enhancements to Group by Clause Page 59 of 71 Pivoting insert command SQL>insert all into sales_info values(employee_id. Create a report that shows the hierarchy of the managers for the employee scott. 2.week_id. Give alias names to the columns .sales_tue.Print the employees ename.sales_tue) into sales_info values(employee_id.mgr and deptno. Create an indented report showing the management hierarchy starting from the employee whose Ename is Smith. .week_id.week_id. 3.week_id.sales_fri) select empno. Display his Immediate manager first.sales_wed) into sales_info values(employee_id. Questions 1.sales_wed sales_thu. 4.week_id.sales_mon) into sales_info values(employee_id.sales_thur) into sales_info values(employee_id.sales_fri from sales_source_data.

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. Besides sending SQL statements to the server.SQL * Plus Page 60 of 71 9. you can use a host operating system editor to edit the buffer contents. SQL*Plus also saves them into a local buffer and allow users to view and change the statements.1 Editing Commands SQL*Plus does not store commands in the buffer. indexes. alter. update. you edit a SQL*Plus command entered directly to the command prompt by using [Backspace] or by re-entering the command. Users type in SQL statements in SQL*Plus that send statements to Oracle server. With SQL*Plus. 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 . you can do the following: Issue a SELECT query and view the results Insert. or drop database objects such as tables. SQL*Plus SQL*Plus is a client terminal software allowing users to interact with Oracle server to manipulate data and data structures. The query results are returned to SQL*Plus and displayed to the user. and users Execute SQL*Plus script files Write output to a file Execute procedures and functions that are stored in a database 9. The following figure illustrates the process. Alternatively. You can use a number of SQL*Plus commands to edit the SQL command or PL/SQL block currently stored in the buffer. Oracle server then validates and executes the statements on its databases.

sal REAL NOT NULL. GET filename . primary key (empno)). 6000).sql DROP TABLE employee / commit / CREATE TABLE employee ( empno INTEGER NOT NULL. / INSERT INTO employee VALUES (1. .calls up contents of previously saved file into the buffer START filename – Runs a prvoiusly saved command file @ filename .3 Run SQL statements in a batch To run SQL commands in a batch. 6000). INSERT INTO employee VALUES (2. For example.Runs a prvoiusly saved command file(same as start) EDIT filename .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. 'Jack'. 'Tom'.buf Exit – Leaves SQL * Plus 9.Invokes the editor and saves the buffer content to a file named afiedit. wanghao@sf3:~/cs6203[513]$ more table. you can put all your SQL commands into a text file and execute these commands in this file in SQL*PLUS. name VARCHAR2(50) NOT NULL.Saves current Content of SQL buffer to the file. Use your favorite editor to type in your SQL queries into a text file.2 Sql * Plus File Commands SAVE filename .

sql. use the following command: SQL> SPOOL OFF. 'John'. 9. All SQL commands and their outputs after this command are written into the file myoutput. 6000). SQL> SPOOL myoutput. instead of using SPOOL OFF. You could also find out all commands by entering: SQL> HELP menu. Then. and run the batch of commands.SQL * Plus INSERT INTO employee VALUES (3. Output results to a file You can record your SQL command outputs to a file for output or editing purpose. For example.5 Host operating system commands. SQL> SPOOL <your file name> . For example.sql. Sometimes when you get something fuzzy. 9.4 Use the following command to access the help system.out . / 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. If you forget a specific SQL command you could enter SQL> HELP <the SQL command>. assume that you name the SQL file as table. spool them to a file as described in the previous section. SQL> START table. 'Jane'. 6000). INSERT INTO employee VALUES (4. you can try the following SQL> SET SERVEROUTPUT ON SQL> SET ARRAYSIZE 1 Sending Results to a Printer To print query results. HO[ST] [command] . To end recording. SPOOL OUT does not delete the spool file after printing. 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.out that by default is stored in the current working directory where you invoked SQL*Plus.

@@ 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. you can use another character instead of HOST such as "$" (VMS). and the comment ends at the end of the line (a line cannot contain both a comment and a command). 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). uri is only supported on Windows platforms in this release.SQL * Plus Executes a host operating system command without leaving SQL*Plus. 9.ext] [LIS[T]|NOL[IST]] Loads a host operating system file into the SQL buffer. This command is identical to the @ ("at" sign) command. See the Oracle installation and user's manuals provided for your operating system for details. Page 63 of 71 Note: With some operating systems.. GET file_name[. "!" (UNIX) and "$" (Windows). The REMARK command must appear at the beginning of a line. . ED[IT] [file_name[. @ { uri | file_name[.ext] } [arg .. The command file can be called from the local file system or from a web server.] Runs the SQL*Plus statements in the specified command file.ext] [CRE[ATE]|REP[LACE]|APP[END]] Saves the contents of the SQL buffer into a host operating system file (a command file). 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. uri is only supported on Windows platforms in this release. STA[RT] { uri | file_name[. omit the file name. SAV[E] file_name[. REM[ARK] Begins a comment in a command file. To edit the buffer contents.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). You can pass values to script variables in the usual way. You can pass values to script variables in the usual way. The command file can be called from the local file system or from a web server.. 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.ext] Runs the specified command file.] Runs the SQL*Plus statements in the specified command file. STORE SET file_name[.ext] } [arg .6 commands to create and modify files. SQL*Plus does not interpret the comment as a command..

] Displays the current values of bind variables. Alternatively. SQL*Plus prompts you for a value each time an "&" variable is found. DEF[INE] [variable]|[variable = text] Page 64 of 71 Specifies a user variable and assigns it a CHAR value.. START substitutes values you list after the command file name as follows: the first for &1. Use the following symbols to create substitution variables and parameters for use in command files. Deletes given user variables that you defined either explicitly (with the DEFINE command) or implicitly (with an argument to the START command).7 Create and display bind variables. &n Specifies a parameter in a command file you run using the START command. 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..]] .. Alternatively. then waits for the user to press [Return]. If no arguments are supplied. lists the value and variable type of a single variable or all variables. store and print your query results. &&user_variable Indicates a substitution variable in a SQL or SQL*Plus command. UNDEF[INE] variable . VARIABLE lists all declared bind variables. 9.SQL * Plus Use the following commands to write interactive commands. If the user variable is undefined. &user_variable. SQL*Plus substitutes the value of the specified user variable for each substitution variable it encounters. . 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. PAU[SE] [text] Displays an empty line followed by a line containing text. PRI[NT] [variable .attribute_name [option.8 Formatting Query Results Use the following commands to format. the second for &2. 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. and so on. 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. 9.. ATTRIBUTE [type_name...

NCHAR. CLOB. LONG.]|[ON|OFF] Places and formats the specified title at the bottom of each report page.... or lists the current display attributes for a single attribute or for all attributes. such as text for the column heading. VARCHAR2 (VARCHAR). Resets or erases the current value or setting for the specified option..attribute_name|alias} ON|OFF BRE[AK] [ON report_element [action [action]]] .. or formats for CHAR. NCLOB and NUMBER data..SQL * Plus Page 65 of 71 Specifies display attributes for a given object attribute. CL[EAR] option .. Specifies where and how formatting will change in a report (for example.. See TITLE for additional information on valid printspec clauses. 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] . 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 . NVARCHAR2 (NCHAR VARYING).]] Specifies the display attributes for a given column. or lists the current BTITLE definition. skipping a line each time a given column value changes). 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] . Enter BREAK with no clauses to list the current BREAK definition. option represents one of the following clauses: ALI[AS] alias CLE[AR] FOR[MAT] format LIKE {type_name.

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

CROSS JOINs. 15. What is an index? What are the types of indexes? indexes helps to retrieve the data quicker. . 16.Indexes are of two types. 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). but it won't log the deletion of each row. you need a self join. Clustered indexes and nonclustered indexes. with the leaf level nodes having the index key and it's row locater. except that two instances of the same table will be joined in the query. there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. What is a join and explain different types of joins Joins are used in queries to explain how different tables are related. Non-clustered indexes are stored as B-tree structures (so do clustered indexes). How can you Change SQL prompt name SQL> set sqlprompt “Manimara > “ 10. OUTER JOINs. without needing you to create triggers. Here is an example: Employees table which contains rows for normal employees as well as managers. TRUNCATE TABLE also deletes all the rows in a table. Types of constraints: NOT NULL. CHECK. OUTER JOINs are further classified as LEFT OUTER JOINS. Joins also let you select data from a table depending upon data from another table. depending up on the absence or presence of clustered index on the table. which makes it faster. 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. 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. TRUNCATE TABLE can be rolled back. UNIQUE. DROP and TRUNCATE commands? Page 68 of 71 DELETE TABLE is a logged operation. Types of joins: INNER JOINs. Yes we can have nested Transactions. which makes it slow. FOREIGN KEY 12.FAQs 9. 13. so the deletion of each row gets logged in the transaction log. rule or defaults. PRIMARY KEY. What's the difference between DELETE. all the rows in the table are stored in the order of the clustered index key. The row located could be the RID or the Clustered index key. RIGHT OUTER JOINS and FULL OUTER JOINS. What is a self join? Explain it with an example Self join is just like any other join. instead it logs the deallocation of the data pages of the table. What are constraints? Explain different types of constraints? Constraints enable the RDBMS enforce the integrity of the database automatically. 11.When you craete a clustered index on a table. So. to find out the managers of all the employees. Of course. So.

Foreign Key Advantage . The common example is when company wants to combine each product with a pricing table to analyze each product at each price. where are unique creates a nonclustered index by default. HAVING clause is used when you want to specify a condition for a group function and it is written after GROUP BY clause. 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.There can be more than one keys on which all the other attributes are dependent on. Another major difference is that. The WHERE clause is used when you want to specify a condition for columns. mgrid int.'Shobha' INSERT emp SELECT 4.empname [Manager] FROM emp t1.2.It allows refrencing another table using the primary key for the other table 24. t2.mgrid = t2.'Vyas' INSERT emp SELECT 2.'Sourabh' SELECT t1. 23. 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.2.empid 17. 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. 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. How to get the results of a Query sorted in any order? . 20. 22.'Shridhar' INSERT emp SELECT 5.2. 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. single row functions except group functions and it is written before GROUP BY clause if it is used.empname [Employee]. emp t2 WHERE t1. 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. empname char(10) ) INSERT emp SELECT 1. primary key doesn't allow NULLs.3. But by default primary key creates a clustered index on the column.FAQs CREATE TABLE emp ( empid int. Difference between a "where" clause and a "having" clause. but unique key allows one NULL only. 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. 18. 25.It is a unique key on which all the other candidate keys are functionally dependent Disadvantage . What are the advantages and disadvantages of primary key and foreign key in SQL? Primary key Advantages .'Mohan' INSERT emp SELECT 3.NULL.

'Unknown') from employees. Explain normalization ? Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. What is diffrence between Co-related sub query and nested sub query? .FAQs Using ‘Order by’ clause we can sort results of a query. 37. 0. 33. Schema objects can be created and manipulated 29. 'Female'. How does one implement IF-Then-Else in select Statement Ex 1: Ex 2: select decode(sex. . Which date function returns number value? months_between 35. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. 30. the rocess of organizing data to minimize redundancy. 31. 'Male'.Nested subquery runs only once for the entire nesting (outer) query. 'a < b') from tableX. Each user owns a single schema. A subquery SELECT statement can return any number of values. 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. Which date function is used to find the difference between two dates? DateDiff is the command used to get difference between dates 34. can you create a foreign key between columns of two tables which are having different data types ? No 38. what you mean by schema object? Page 70 of 71 A schema is a collection of logical structures of data.Correlated subquery runs once for each row selected by the outer query. What the difference between UNION and UNIONALL? Union will remove the duplicate rows from the result set while Union all does'nt. It contains a reference to a value from the row selected by the outer query. deletions. What is a sub query? Sub-queries are often referred to as sub-selects. why you need indexing and where that is stroed? . Sub-queries are generally used to return a single row as an atomic value. How to use "CASE" keyword in SELECT statement? SELECT ename. b. It does not contain any reference to the outer query row. In relational database design. 'M'. a-b. 32. The objective is to isolate data so that additions. or schema objects. 'a > b'. A sub-query is executed by enclosing it in a set of parentheses. as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. 'a = b'. though they may be used to compare values against multiple rows with the IN keyword. and can be found . How can i hide a particular table name of our schema? you can hide the table name by creating synonyms. 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. 'F'. 36. We can create indexes explicitly to speed up sql statement execution on a table 28. 27. decode( abs(a-b). CASE WHEN sal>1000 THEN 'Over paid' ELSE 'Under paid' END FROM emp. 26. select a. A schema is owned by a database user and has the same name as that user.

For more information refer 3. How to implement one-to-one. The leaf nodes of a clustered index contain the data pages. A query can contain more than one sub-queries.ALTER TABLE table_name DROP UNUSED COLUMNS.ALTER TABLE table_name SET UNUSED (column_name). One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Instead.FAQs Page 71 of 71 in. The leaf node of a nonclustered index does not consist of the data pages. 42. We can also use Round function with dates. HAVING. . 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. a FROM. 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. GROUP BY. It is sometimes necessary because current DBMSs implement the relational model poorly. 39. 40. Properties of Sub-Query A subquery must be enclosed in the parenthesis. 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. A subquery must be put in the right hand of the comparison operator. and/or ORDER BY clauses of a T-SQL statement. 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. 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. To Drop Unused column . the leaf nodes contain index rows. How can you make a column as unused column in a table? To make a column as unused . and A subquery cannot contain a ORDER-BY clause. 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. Therefore table can have only one clustered index. the column list of a SELECT statement. Yes.4 41. A true relational DBMS would allow for a fully normalized database at the logical level.

Sign up to vote on this title
UsefulNot useful