Document

Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 97

What are the various types of queries ?

Answer: The types of queries are:

•Normal Queries

•Sub Queries

•Co-related queries

•Nested queries

•Compound queries
What is a transaction ?
Answer: A transaction is a set of SQL statements between any two COMMIT and
ROLLBACK statements.
What is implicit cursor and how is it used by Oracle ?
Answer: An implicit cursor is a cursor which is internally created by Oracle.It is created
by Oracle for each individual SQL.
Which of the following is not a schema object : Indexes, tables, public synonyms,
triggers and packages ?
Answer: Public synonyms
What is PL/SQL?
Answer: PL/SQL is Oracle's Procedural Language extension to SQL.The language
includes object oriented programming techniques such as encapsulation, function
overloading, information hiding (all but inheritance), and so, brings state-of-the-art
programming to the Oracle database server and a variety of Oracle tools.
Is there a PL/SQL Engine in SQL*Plus?
Answer: No.Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine.Thus, all
your PL/SQL are send directly to the database engine for execution.This makes it much
more efficient as SQL statements are not stripped off and send to the database
individually.
Is there a limit on the size of a PL/SQL block?
Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and
the maximum code size is 100K.You can run the following select statement to query the
size of an existing package or procedure. SQL> select * from dba_object_size where
name = 'procedure_name'
Can one read/write files from PL/SQL?
Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write files.The
directory you intend writing to has to be in your INIT.ORA file (see
UTL_FILE_DIR=...parameter).Before Oracle 7.3 the only means of writing a file was to
use DBMS_OUTPUT with the SQL*Plus SPOOL command.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W');
UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));
UTL_FILE.FCLOSE(fileHandler);
END;
How can I protect my PL/SQL source code?
Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for
PL/SQL programs to protect the source code.This is done via a standalone utility that
transforms the PL/SQL source code into portable binary object code (somewhat larger
than the original).This way you can distribute software without having to worry about
exposing your proprietary algorithms and methods.SQL*Plus and SQL*DBA will still
understand and know how to execute such scripts.Just be careful, there is no "decode"
command available. The syntax is: wrap iname=myscript.sql oname=xxxx.yyy
Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ?
How ?
Answer: From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic
SQL statements.
Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
What are the various types of queries ?
Answer: The types of queries are:

•Normal Queries

•Sub Queries

•Co-related queries

•Nested queries
•Compound queries
What is a transaction ?
Answer: A transaction is a set of SQL statements between any two COMMIT and
ROLLBACK statements.
What is implicit cursor and how is it used by Oracle ?
Answer: An implicit cursor is a cursor which is internally created by Oracle.It is created
by Oracle for each individual SQL.
Which of the following is not a schema object : Indexes, tables, public synonyms,
triggers and packages ?
Answer: Public synonyms
What is PL/SQL?
Answer: PL/SQL is Oracle's Procedural Language extension to SQL.The language
includes object oriented programming techniques such as encapsulation, function
overloading, information hiding (all but inheritance), and so, brings state-of-the-art
programming to the Oracle database server and a variety of Oracle tools.
Is there a PL/SQL Engine in SQL*Plus?
Answer: No.Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine.Thus, all
your PL/SQL are send directly to the database engine for execution.This makes it much
more efficient as SQL statements are not stripped off and send to the database
individually.
Is there a limit on the size of a PL/SQL block?
Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and
the maximum code size is 100K.You can run the following select statement to query the
size of an existing package or procedure. SQL> select * from dba_object_size where
name = 'procedure_name'
Can one read/write files from PL/SQL?
Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write files.The
directory you intend writing to has to be in your INIT.ORA file (see
UTL_FILE_DIR=...parameter).Before Oracle 7.3 the only means of writing a file was to
use DBMS_OUTPUT with the SQL*Plus SPOOL command.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W');
UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));
UTL_FILE.FCLOSE(fileHandler);
END;
How can I protect my PL/SQL source code?
Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for
PL/SQL programs to protect the source code.This is done via a standalone utility that
transforms the PL/SQL source code into portable binary object code (somewhat larger
than the original).This way you can distribute software without having to worry about
exposing your proprietary algorithms and methods.SQL*Plus and SQL*DBA will still
understand and know how to execute such scripts.Just be careful, there is no "decode"
command available. The syntax is: wrap iname=myscript.sql oname=xxxx.yyy
Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ?
How ?
Answer: From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic
SQL statements.
Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
What are the various types of Exceptions ?
Answer: User defined and Predefined Exceptions.
Can we define exceptions twice in same block ?
Answer: No.
What is the difference between a procedure and a function ?
Answer: Functions return a single variable by value whereas procedures do not return any
variable by value.Rather they return multiple variables by passing variables by reference
through their OUT parameter.
Can you have two functions with the same name in a PL/SQL block ?
Answer: Yes.
Can you have two stored functions with the same name ?
Answer: Yes.
Can you call a stored function in the constraint of a table ?
Answer: No.
What are the various types of parameter modes in a procedure ?
Answer: IN, OUT AND INOUT.
What is Over Loading and what are its restrictions ?
Answer: OverLoading means an object performing different functions depending upon
the no.of parameters or the data type of the parameters passed to it.
Can functions be overloaded ?
Answer: Yes.
Can 2 functions have same name & input parameters but differ only by return datatype
Answer: No.
What are the constructs of a procedure, function or a package ?
Answer: The constructs of a procedure, function or a package are :

•variables and constants

•cursors

•exceptions
Why Create or Replace and not Drop and recreate procedures ?
Answer: So that Grants are not dropped.
Can you pass parameters in packages ? How ?
Answer: Yes.You can pass parameters to procedures or functions in a package.
What are the parts of a database trigger ?
Answer: The parts of a trigger are:

•A triggering event or statement

•A trigger restriction

•A trigger action
What are the various types of database triggers ?
Answer: There are 12 types of triggers, they are combination of :

•Insert, Delete and Update Triggers.


•Before and After Triggers.

•Row and Statement Triggers.


What is the advantage of a stored procedure over a database trigger ?
Answer: We have control over the firing of a stored procedure but we have no control
over the firing of a trigger.
What is the maximum no.of statements that can be specified in a trigger statement ?
Answer: One.
Can views be specified in a trigger statement ?
Answer: No
What are the values of :new and :old in Insert/Delete/Update Triggers ?
Answer: INSERT : new = new value, old = NULL
DELETE : new = NULL, old = old value
UPDATE : new = new value, old = old value
What are cascading triggers? What is the maximum no of cascading triggers at a time?
Answer: When a statement in a trigger body causes another trigger to be fired, the
triggers are said to be cascading.Max = 32.
What are mutating triggers ?
Answer: A trigger giving a SELECT on the table on which the trigger is written.
What are constraining triggers ?
Answer: A trigger giving an Insert/Updat e on a table having referential integrity
constraint on the triggering table.
Describe Oracle database's physical and logical structure ?
Answer:

•Physical : Data files, Redo Log files, Control file.

•Logical : Tables, Views, Tablespaces, etc.


Can you increase the size of a tablespace ? How ?
Answer: Yes, by adding datafiles to it.
Can you increase the size of datafiles ? How ?
Answer: No (for Oracle 7.0)
Yes (for Oracle 7.3 by using the Resize clause )
What is the use of Control files ?
Answer: Contains pointers to locations of various data files, redo log files, etc.
What is the use of Data Dictionary ?
Answer: It Used by Oracle to store information about various physical and logical Oracle
structures e.g.Tables, Tablespaces, datafiles, etc
What are the advantages of clusters ?
Answer: Access time reduced for joins.
What are the disadvantages of clusters ?
Answer: The time for Insert increases.
Can Long/Long RAW be clustered ?
Answer: No.
Can null keys be entered in cluster index, normal index ?
Answer: Yes.
Can Check constraint be used for self referential integrity ? How ?
Answer: Yes.In the CHECK condition for a column of a table, we can reference some
other column of the same table and thus enforce self referential integrity.
What are the min.extents allocated to a rollback extent ?
Answer: Two
What are the states of a rollback segment ? What is the difference between partly
available and needs recovery ?
Answer: The various states of a rollback segment are :

•ONLINE

•OFFLINE

•PARTLY AVAILABLE

•NEEDS RECOVERY

•INVALID.
What is the difference between unique key and primary key ?
Answer: Unique key can be null; Primary key cannot be null.
An insert statement followed by a create table statement followed by rollback ? Will the
rows be inserted ?
Answer: No.
Can you define multiple savepoints ?
Answer: Yes.
Can you Rollback to any savepoint ?
Answer: Yes.
What is the maximum no.of columns a table can have ?
Answer: 254.
What is the significance of the & and && operators in PL SQL ?
Answer: The & operator means that the PL SQL block requires user input for a variable.
The && operator means that the value of this variable should be the same as inputted by
the user previously for this same variable
Can you pass a parameter to a cursor ?
Answer: Explicit cursors can take parameters, as the example below shows.A cursor
parameter can appear in a query wherever a constant can appear.
CURSOR c1 (median IN NUMBER) IS
SELECT job, ename FROM emp WHERE sal > median;
What are the various types of RollBack Segments ?
Answer: The types of Rollback sagments are as follows :

•Public Available to all instances

•Private Available to specific instance


Can you use %RowCount as a parameter to a cursor ?
Answer: Yes
Is the query below allowed :
Select sal, ename Into x From emp Where ename = 'KING' (Where x is a record of
Number(4) and Char(15))
Answer: Yes
Is the assignment given below allowed :
ABC = PQR (Where ABC and PQR are records)
Answer: Yes
Is this for loop allowed :
For x in &Start..&End Loop
Answer: Yes
How many rows will the following SQL return :
Select * from emp Where rownum < 10;
Answer: 9 rows
How many rows will the following SQL return :
Select * from emp Where rownum = 10;
Answer: No rows
Which symbol preceeds the path to the table in the remote database ?
Answer: @
Are views automatically updated when base tables are updated ?
Answer: Yes
Can a trigger written for a view ?
Answer: No
If all the values from a cursor have been fetched and another fetch is issued, the output
will be : error, last record or first record ?
Answer: Last Record
A table has the following data : [[5, Null, 10]].What will the average function return ?
Answer: 7.5
Is Sysdate a system variable or a system function?
Answer: System Function
Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval
reference we get the next number 2.Suppose at this point we issue an rollback and
again issue a nextval.What will the output be ?
Answer: 3
Definition of relational DataBase by Dr.Codd (IBM)?
Answer: A Relational Database is a database where all data visible to the user is
organized strictly as tables of data values and where all database operations work on
these tables.
What is Multi Threaded Server (MTA) ?
Answer: In a Single Threaded Architecture (or a dedicated server configuration) the
database manager creates a separate process for each database user.But in MTA the
database manager can assign multiple users (multiple user processes) to a single
dispatcher (server process), a controlling process that queues request for work thus
reducing the databases memory requirement and resources.
Which are initial RDBMS, Hierarchical & N/w database ?
Answer:

•RDBMS - R system

•Hierarchical - IMS

•N/W - DBTG
Difference between Oracle 6 and Oracle 7
Answer:
ORACLE 7 ORACLE 6
Cost based optimizer Rule based optimizer

Shared SQL Area SQL area allocated for each user

Multi Threaded Server Single Threaded Server

Hash Clusters Only B-Tree indexing

Roll back Size Adjustment No provision

Truncate command No provision

Distributed Database Distributed Query

Table replication & snapshots No provision

Client/Server Tech No provision

What is Functional Dependency


Answer: Given a relation R, attribute Y of R is functionally dependent on attribute X of R
if and only if each X-value has associated with it precisely one -Y value in R
What is Auditing ?
Answer: The database has the ability to audit all actions that take place within it. a) Login
attempts, b) Object Accesss, c) Database Action Result of Greatest(1,NULL) or
Least(1,NULL) NULL
While designing in client/server what are the 2 imp.things to be considered ?
Answer: Network Overhead (traffic), Speed and Load of client server
What are the disadvantages of SQL ?
Answer: Disadvantages of SQL are :

•Cannot drop a field

•Cannot rename a field

•Cannot manage memory

•Procedural Language option not provided

•Index on view or index on index not provided

•View updation problem


When to create indexes ?
Answer: To be created when table is queried for less than 2% or 4% to 25% of the table
rows.
How can you avoid indexes ?
Answer: To make index access path unavailable

•Use FULL hint to optimizer for full table scan

•Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes
instead of another.

•Use an expression in the Where Clause of the SQL.


What is the result of the following SQL :
Select 1 from dual UNION Select 'A' from dual;
Answer: Error
Can database trigger written on synonym of a table and if it can be then what would be
the effect if original table is accessed.
Answer: Yes, database trigger would fire.
Can you alter synonym of view or view ?
Answer: No
Can you create index on view
Answer: No.
What is the difference between a view and a synonym ?
Answer: Synonym is just a second name of table used for multiple link of database.View
can be created with many tables, and with virtual columns and with conditions.But
synonym can be on view.
What's the length of SQL integer ?
Answer: 32 bit length
What is the difference between foreign key and reference key ?
Answer: Foreign key is the key i.e.attribute which refers to another table primary key.
Reference key is the primary key of table referred by another table.
Can dual table be deleted, dropped or altered or updated or inserted ?
Answer: Yes
If content of dual is updated to some value computation takes place or not ?
Answer: Yes
If any other table same as dual is created would it act similar to dual?
Answer: Yes
For which relational operators in where clause, index is not used ?
Answer: <> , like '%...' is NOT functions, field +constant, field||''
.Assume that there are multiple databases running on one machine.How can you switch
from one to another ?
Answer: Changing the ORACLE_SID
What are the advantages of Oracle ?
Answer: Portability : Oracle is ported to more platforms than any of its competitors,
running on more than 100 hardware platforms and 20 networking protocols. Market
Presence : Oracle is by far the largest RDBMS vendor and spends more on R & D than
most of its competitors earn in total revenue.This market clout means that you are
unlikely to be left in the lurch by Oracle and there are always lots of third party interfaces
available. Backup and Recovery : Oracle provides industrial strength support for on-line
backup and recovery and good software fault tolerence to disk failure.You can also do
point-in-time recovery. Performance : Speed of a 'tuned' Oracle Database and application
is quite good, even with large databases.Oracle can manage > 100GB databases. Multiple
database support : Oracle has a superior ability to manage multiple databases within the
same transaction using a two-phase commit protocol.
What is a forward declaration ? What is its use ?
Answer: PL/SQL requires that you declare an identifier before using it.Therefore, you
must declare a subprogram before calling it.This declaration at the start of a subprogram
is called forward declaration.A forward declaration consists of a subprogram
specification terminated by a semicolon.
What are actual and formal parameters ?
Answer: Actual Parameters : Subprograms pass information using parameters.The
variables or expressions referenced in the parameter list of a subprogram call are actual
parameters.For example, the following procedure call lists two actual parameters named
emp_num and amount:
Eg.raise_salary(emp_num, amount);
Formal Parameters : The variables declared in a subprogram specification and referenced
in the subprogram body are formal parameters.For example, the following procedure
declares two formal parameters named emp_id and increase:
Eg.PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary
REAL;
What are the types of Notation ?
Answer: Position, Named, Mixed and Restrictions.
What all important parameters of the init.ora are supposed to be increased if you want
to increase the SGA size ?
Answer: In our case, db_block_buffers was changed from 60 to 1000 (std values are 60,
550 & 3500) shared_pool_size was changed from 3.5MB to 9MB (std values are 3.5, 5 &
9MB) open_cursors was changed from 200 to 300 (std values are 200 & 300)
db_block_size was changed from 2048 (2K) to 4096 (4K) {at the time of database
creation}. The initial SGA was around 4MB when the server RAM was 32MB and The
new SGA was around 13MB when the server RAM was increased to 128MB.
.If I have an execute privilege on a procedure in another users schema, can I execute his
procedure even though I do not have privileges on the tables within the procedure ?
Answer: Yes
What are various types of joins ?
Answer: Types of joins are:

•Equijoins

•Non-equijoins

•self join
•outer join
What is a package cursor ?
Answer: A package cursor is a cursor which you declare in the package specification
without an SQL statement.The SQL statement for the cursor is attached dynamically at
runtime from calling procedures.
If you insert a row in a table, then create another table and then say Rollback.In this
case will the row be inserted ?
Answer: Yes.Because Create table is a DDL which commits automatically as soon as it is
executed.The DDL commits the transaction even if the create statement fails internally
(eg table already exists error) and not syntactically.
2) What do you know about normalization? Explain in detail?
3) Explain the difference between a procedure and a function? What do you understand by those
terms?
4) Explain about functional dependency and its relation with table design?
5) Explain the different normalization forms?
Remember how you answer shortens your technical interview you are trying to convince the
interviewer that you are a suitable candidate for the job.
6) What are the different types of trigger and explain its various uses and functions?
7) Are truncate and delete commands same? If so why?
8) Compare and contrast between SQL and SQL server and explain its various functions?
9) What is a query and state the different types of queries and their uses?
10) Explain about your project and its relation the current job position you are applying to?
11) How different is MS Access and Oracle?
12) What is a cluster and non cluster index?
13) State the difference between a primary key and foreign key?
14) State all possible different index configurations a table can possibly have?
15) What is a cursor and what are the steps need to be taken?
If possible while answering this question try to explain him the various steps in an order.
16) Why do you use stored procedures and state some of its disadvantages?
17) State the various uses of DBCC command?
18) What is a collation and state the different types of collation sensitivity?
19) What are the uses of linked server and explain it in detail?
20) State and explain about the different types of data models?
21) State and explain about oracle instance?
22) Explain about achiever in SQL?
23) What are the different Pseudo commands? Explain in general?
24) State some uses of redo log files?
These are some of the most important questions and there are chances of it being asked in an
interview which is: -
1) Explain what you understand of a primary key and a unique key and explain the differences
between them?
2) Explain about the commands Truncate and Delete?
3) Which operating system you are comfortable to use for databases?
4) Do you like command language or GUI?
5) State and explain some of the properties of Sub-Query?
6) What are the different types of user defined functions you can create?
7) What do you understand by log shipping explain the process?
8) State and explain the different types of replication?
9) Explain the cases or situations where you use de-normalization?
1) Explain about SQL related to RDBMS?
SQL is known as structured query language. It is especially designed to retrieve and store
information of data in relational database management systems. It creates, modifies and makes
the data base object user access the control system. It is primarily specialized software for
RDBMS.
2) Explain about SQL?
It is an interactive and programming language which is used to modify, manage, and to pass
queries. It is an ANSI and ISO compliant language. SQL entirely depends upon its command
language for modifications, changes, updating, etc to the database. Databases can also be
accessible remotely with the help of Call level interface.
3) Explain about the original design and basics which gave life to SQL?
SQL was originally designed to be a declarative and data manipulation language. Additions to
the language occurred because of addition of new features from vendors such as constructs, data
types, extensions and control flow statements. Important extensions were added to SQL. Cross
platform compatibility has been the main issue for SQL.
4) Explain about Call level interface present in SQL?
In depth explanation of this interface is present in ISO/IEC 9075-3:2003. This extension defines
components which can be used to execute SQL statements written in other programming
languages. This extension is defined in such a way that the statements and procedure calls from
SQL be different from the applications source code.
5) Explain about the object language binding’s extension?
This extension is very useful if you are planning to use SQL in Java. This extension defines the
syntax and procedure to follow for SQL embedded in Java. It also makes sure of the syntax and
procedures to follow which ensures the portability of SQL embedded Java in binary applications.
6) Explain about XML related specifications?
XML is a very powerful DOM language. Often this language is used with many database
applications as a front end, SQL acts as a backend to support the Database queries. This
specification has several extensions which defines routines, functions, data type mappings,
storage, etc.
7) Explain about the information and definition schemas?
This information and definition schema helps the user by giving necessary information about the
tools and functions of SQL. It describes several tools and extensions some of them are object
identifier, security, features provided by DBMS, authorization, values, sizing items, etc. This is
defined by ISO specification.
8) State the several languages into which SQL is divided into?
SQL is divided into several sub divisions such as
• Statements
• Queries
• Expressions
• Predicates
• Clauses
• White space
• Statement terminator
9) Explain about predicates and statements?
Statements have a prolonged effect on the functioning and behavior of the data, care should be
taken before defining a statement to the data. It may control transactions, query, sessions,
connections and program flow
Predicates specified conditions which can be evaluated to three valued logic. Boolean truth
values can limit the effect of the statements, program functioning, queries, etc.
10) Explain the ORDER BY clause?
Orderby clause identifies the columns which are used to sort the data and the order in which they
should be sorted out. SQL query needs to specify orderby clause of they want the data to be
returned in a defined manner of rows and columns.
11) Explain the where clause?
Where clause has a comparison predicate which restricts the number of rows as per the user
generated query. This clause should be applied before the GROUP BY clause. This clause
functions with the help of comparison predicate, when a comparison predicate does not evaluate
a result to be true, all rows from the end result are deleted.
12) Explain about data retrieval?
Data retrieval syntax is often used in combination with data projection. This mechanism is used
when there is a need for calculated result. This is used when there is a special need for calculated
data and not the verbatim data, which is different from the way it was stored in the database.
13) Explain about the MERGE field?
MERGE is used when you need to combine more than one table for a user generated query. This
field can be aptly said as a combination of INSERT and UPDATE elements. This field is also
given a different name (upsert) in some versions of SQL
14) Explain about COMMIT and ROLLBACK?
COMMIT command is used if you are satisfied with the database and you don’t want any
changes to be done to the database. Changes are permanent when you use COMMIT.
ROLLBACK changes or discards all the data prior to COMMIT command. Database changes are
discarded when this command is used but it cannot change the COMMIT command.
15) Explain about Data definition?
Data definition Language is used to define new tables and elements associated with it. Some of
the basic data definition language elements are CREATE, TRUNCATE, ALTER, RENAME,
etc. These are used to control the non standard features of the database.
16) State about some criticisms of SQL?
These are some of the criticisms of SQL
1) Implementation features vary from vendor to vendor. There are many features such as data,
time, comparison sensitivity, etc
2) All possible combinations can be implemented in the language which can give a result
mislead.
3) Grammer of SQL is very complex
17) State some reasons for lack of portability?
There are several reasons for the lack of portability some of them are
1) Main reason is the DATE and TIME variation between databases.
2) Database is free to have its own style of implementation.
3) Ambiguity and less defined semantics of language.
4) Conflict of SQL standards between different vendors and in general specified rules and
regulations.
1) Explain about what a database is?
Database is an important constituent for collection and storage of data. A computer database uses
software for managing its huge pool of database. It also uses software to make changes
automatically to the database without any outside interference.
2) Explain about the database management systems.
Database management systems use specialized software to store the database, make necessary
changes, securing the database, etc. These DBMS are categorized according to the work they do.
Much of the DBMS and its applications are primarily not designed for data they are designed for
concurrency, performance, integrity, and failure troubleshooting.
3) Explain about object oriented databases?
Object oriented databases are used to store much more complex data. They were designed to
store information related to multimedia, spatial and engineering databases. Some of the databases
even stored data about software’s repositories. This was adopted in late ninety`s and new
features were added.
4) Explain about XML databases?
XML databases came into existence in 2000. Many of the new startups were also started. This
database lets you organize data irrespective of whether it is organized or not. Arranging and
complexity for storing data is significantly got reduced with the language.
5) Explain about the hierarchical model of database?
If you can imagine a tree with branches then you know to work with this database. It has a
downward link to describe the nesting and they are arranged in a particular order down the same
level of the list. With this database model you can form a logical relationship among different
types of data.
6) Explain about Network model?
Network is complex, time consuming and costly. This model of storing database has many
parents and finding a logical relationship between them is extremely difficult. This model
provides greater flexibility and easy access to data. Navigating through links is a easy way to
search for data.
7) What are the three basic rules which are to be followed for relational model of database?
There are three basic rules to follow for relational database they are
1) It least bothers about order of the columns
2) No clones or identical rows allowed.
3) Each and every row will have a value for each column.
8) Explain about relational database?
This is the basic structure representation of the data it is represented in the form of rows and
columns. Columns represent the attributes and rows represent the instances of a data. This form
of model came into existence from mathematical concept of relations.
9) Explain about primary key?
A primary holds a unique key for each row designated in the table. Keys are often used to
combine more than two tables, columns, or rows. Keys should be defined in advance before and
it will be too late to define them later.
10) Explain about relational operator join?
Often when a user generates a query data is sent to the requested user by combining data from
many pages. This data is represented in a non orderly fashion which is made into order by the
relational operator join. There are many other operators other than join.
11) Explain about the process of user request and data generating?
Users request information and this request is transformed into a special language usually that
would be the dialect in sql. This dialect would be given to the appropriate software for
culminating the database for appropriate presentation to the end user. Usually sql queries are
increasingly being embedded into software.
12) Explain about normal forms?
Databases are categorized into different forms based upon the anomalies to which they are
vulnerable. Lowest rung of database is known as normal form of first order. A first order normal
form is subjected to many types of vulnerabilities. A higher database cannot be subjected to any
vulnerability. You can get more info about Databases at Database Guides.
13) Explain about relational database management systems?
Relational database systems take the model and form of relational model. Data is represented in
the form of columns and rows which are later represented by relation operators. Explicit pointers
will not interfere between tables.
14) Explain about post relational databases?
Post relational databases are similar to relational database management systems but they have
pre dated relational model of data representation. This model doesn`t require representation of
data with relationship. A perfect example can be a tree with nodes represented in a directed
graph.
15) Explain about the Storage and physical database design?
Databases can be stored in many forms. They are usually stored on hard disks in many different
forms in the form of flat files, hash buckets, ISAM, etc. Data can be stores by partitioning the
data. Normalization and de normalization is generally used for efficient storage of database and
also for memory management.
16) Explain the role of indexing in databases?
Many of the databases take advantage of indexing to increase the speed. This technology has
increased immensely since it`s inception stages. During indexing if a row matches the query it is
automatically generated and given to the user. In RDBMS indexes can be created and dropped
without changing the existing application.
17) State the ACID rules?
Some of the acid rules stated are described as follows.
1) Atomicity: -Either transactions should be done or they should be stopped
2) Consistency: - Data should never be in a contradictory state
3) Isolation: - Two simultaneous or preceding results should never interfere with each other.
4) Durability: -Results or Data shouldn`t be discarded even during a crash of the system.
1) Explain about VB Script?
VB script is a Microsoft programming language and it resembles a lower version of the VB. It is
an Active Scripting language. This scripting language is included in windows operating system
by default. With the use of msscript.ocx you can install VB Script.
2) Give examples where VB script can directly run on users system with Windows as OS?
A simple example detailing the running of VB Script is by utilizing Windows Script host
environment. Visual basic is a stand alone application which has a .vbs as extension. Input can
be provided through graphical user interface and output can be obtained by Wscript.exe from
dialog and input boxes. From command line it can be invoked by Cscript.exe.
3) Explain about .wsf files?
.wsf files are modeled in similar to XML. They can be executed with the help of Wscript.exe and
it can be done from the command line also. This .wsf file can have multiple visual basic files.
Reuse functionality is present with this extension file.
4) Explain about the extension .hta?
.hta extension is used whenever you want to include a VB script in HTML. Here HTML acts as
an interface and VB Script as the programming language. .hta extension files do run in the safe
and trusted zone of Internet explorer. Although they run in the trusted zone querying is restricted
as it has to pass the guidelines of internet explorer.
5) Explain some uses of VB Script?
If functionality aspect is considered VB Script acts similar to Java Script but it is compatible
only on internet explorer. They interact with Document object model. Visual basic script can also
be used for server side processing with ASP.
6) Compare Java Script and VB Script?
VB and Java Script are much similar in functionality. They both interact with the document
object model of the page. Many browsers have compatibility with Java Script but they are not
compatible with VB script as such. For client side scripting developers using VB Script should
always make sure of cross browser compatibility which is not the case when working with VB
script.
7) Explain about the support of ASP for VB Script functionality?
Visual Basic should rely on ASP for sever side processing. Asp.dll is used to make VB Script
run on ASP engine and it invokes vbscript.dll. VB Script should be embedded within context
switches. ASP can provide varied functionality to VB Script.
8) Explain about the functionality of VB Script?
Active X technology can be used to give much more functionality to VB Script. VB provides sub
routines, functions, string manipulation, data/time, error handling, etc. VB can have more
functionality added to it by working with languages such as ASP.
9) Explain about scrrun.dll?
Scripting Runtime library is very important for the functioning of Visual basic script because it
gives much more functionality such as File management, text operations and file modification
features. Scrrun.dll is used very much in programming VB.
10) Explain about ADODB.Stream class?
ADODB.Stream class can be used as string builder. VBScript string concatenation can be very
costly because of frequent memory allocation features. Binary file and memory I/O operation is
provided by ADODB.Stream class. This is widely used to convert bytes into string, etc.
11) Explain about arrays in VB Script?
Arrays in VB Script should be assigned within the variant separated by a comma. If arguments
are not specified then the string is regarded as empty. After specifying the elements in an array
an index number should be used indicating the desired element.
12) Explain about the Asc function?
According to the first letter in a string it returns the ANSI code relevant to that first letter. If
string is not present then a runtime error occurs. Asc function returns the first byte used. It is
used only with elements containing byte data in a string.
13) Explain about filter expression?
Filter expression returns an array based on a specific filter search condition and it returns a zero
based array. Arguments included in the filter array are Input strings, value, include and compare.
If there is no match for the value it returns an empty string.
14) Explain about constants in VB Script?
There are many useful constants present in Visual basic script which you can use in your code.
They ease your work load by remembering value and implementing in the code. Maintenance is
easy with VB Script because it can easily change the feature of constants.
15) Explain about Tristate constants?
Tristate constants can be used with functions which allow formatting of numbers. These
constants can be used with VB Script without defining them. It can be used anywhere in the code
to reflect and represent the values.
16) Explain about operator precedence in VB Script?
In operator precedence expressions are evaluated and resolved in a predetermined order. The
order of evaluation can be modulated if you use parenthesis. Expressions present in parenthesis
are evaluated first.
17) What are the different types of operators and their order of precedence?
Order of evaluation of operators is, first arithmetic operators are evaluated, and comparison
operators are evaluated next and at the last logical operators are evaluated at the last. In
arithmetic operators negation, Exponentiation, multiplication and division, integer division,
modulus arithmetic, addition and subtraction and string concatenation are provided.
coolinterview.com
geekinterview.com

SQL> select * from sample;

PID PNAME QTY

---------- ---------- ----------

1000 camera 20

1001 laptop 10

1002 desktop 15

SQL> truncate table sample;

Table truncated.

SQL> desc sample;

Name Null? Type

----------------------------------------------------------------- -------- ------------------------

PID NUMBER(4)

PNAME NOT NULL VARCHAR2(10)

QTY NUMBER(4)

SQL> select * from sample;

no rows selected

SQL> drop table sample;

Table dropped.
SQL> desc sample;

ERROR:

ORA-04043: object sample does not exist

SQL> rollback;

Rollback complete.

SQL> desc sample;

ERROR:

ORA-04043: object sample does not exist

SQL> select * from tab;

TNAME TABTYPE CLUSTERID

------------------------------ ------- ----------

DEPT TABLE

EMP TABLE

BONUS TABLE

SALGRADE TABLE

PRODUCTS TABLE

ORDERS TABLE

SKILLS TABLE

BIN$DOC2aYDTQCCTgp0Y3TsHRA==$0 TABLE

8 rows selected.

SQL> create table ex as select * from products;

Table created.

SQL> desc ex;

Name Null? Type


----------------------------------------- -------- -------------------------

PID NUMBER(4)

PNAME NOT NULL VARCHAR2(10)

QTY NUMBER(4)

SQL> select * from ex;

PID PNAME QTY

---------- ---------- ----------

1000 camera 20

1001 laptop 10

1002 desktop 15

SQL> drop table ex;

Table dropped.

SQL> desc ex;

ERROR:

ORA-04043: object ex does not exist

SQL> table ex to before drop;

SP2-0734: unknown command beginning "table ex t..." - rest of line ignored.

.What is the purpose of database links in Oracle?

Database links are created to establish communication between different databases or different
environments such as development, test and production of the same database. The database links are
usually designed to be read-only to access other database information . They are also useful when you
want to copy production data into test environment for testing.

Display Odd/ Even number of records


Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6

1. To see current user name


Sql> show user;
2. Change SQL prompt name
SQL> set sqlprompt “Manimara > “
Manimara >
Manimara >
3. Switch to DOS prompt
SQL> host
4. How do I eliminate the duplicate rows ?
SQL> delete from table_name where rowid not in (select max(rowid) from table group by
duplicate_values_field_name);
or
SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select
min(rowid) from table_name tb where ta.dv=tb.dv);
Example.
Table Emp
Empno Ename
101 Scott
102 Jiyo
103 Millor
104 Jiyo
105 Smith
delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename =
b.ename);
The output like,
Empno Ename
101 Scott
102 Millor
103 Jiyo
104 Smith
5. How do I display row number with records?
To achive this use rownum pseudocolumn with query, like SQL> SQL> select rownum, ename
from emp;
Output:
1 Scott
2 Millor
3 Jiyo
4 Smith
6. Display the records between two range
select rownum, empno, ename from emp where rowid in
(select rowid from emp where rownum <=&upto
minus
select rowid from emp where rownum<&Start);
Enter value for upto: 10
Enter value for Start: 7
ROWNUM EMPNO ENAME
--------- --------- ----------
1 7782 CLARK
2 7788 SCOTT
3 7839 KING
4 7844 TURNER
7. I know the nvl function only allows the same data type(ie. number or char or date
Nvl(comm, 0)), if commission is null then the text “Not Applicable” want to display,
instead of blank space. How do I write the query?
SQL> select nvl(to_char(comm.),'NA') from emp;
Output :
NVL(TO_CHAR(COMM),'NA')
-----------------------
NA
300
500
NA
1400
NA
NA
8. Oracle cursor : Implicit & Explicit cursors
Oracle uses work areas called private SQL areas to create SQL statements.
PL/SQL construct to identify each and every work are used, is called as Cursor.
For SQL queries returning a single row, PL/SQL declares all implicit cursors.
For queries that returning more than one row, the cursor needs to be explicitly declared.
9. Explicit Cursor attributes
There are four cursor attributes used in Oracle
cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name
%ISOPEN
10. Implicit Cursor attributes
Same as explicit cursor but prefixed by the word SQL
SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN
Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor
after executing SQL statements.
: 2. All are Boolean attributes.
11. Find out nth highest salary from emp table
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT
(b.sal)) FROM EMP B WHERE a.sal<=b.sal);
Enter value for n: 2
SAL
---------
3700
12. To view installed Oracle version information
SQL> select banner from v$version;
13. Display the number value in Words
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like,
Rs. Three Thousand only.
SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
14. Display Odd/ Even number of records
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6
15. Which date function returns number value?
months_between
16. Any three PL/SQL Exceptions?
Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others
17. What are PL/SQL Cursor Exceptions?
Cursor_Already_Open, Invalid_Cursor
18. Other way to replace query result null value with a text
SQL> Set NULL ‘N/A’
to reset SQL> Set NULL ‘’
19. What are the more common pseudo-columns?
SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM
20. What is the output of SIGN function?
1 for positive value,
0 for Zero,
-1 for Negative value.
21. What is the maximum number of triggers, can apply to a single table?
12 triggers.

SQL and PL/SQL Interview questions-I

1. The most important DDL statements in SQL are:

CREATE TABLE - creates a new database table


ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

2. Operators used in SELECT statements.


= Equal
<> or != Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
BETWEEN Between an inclusive range
LIKE Search for a pattern

3. SELECT statements:

SELECT column_name(s) FROM table_name


SELECT DISTINCT column_name(s) FROM table_name
SELECT column FROM table WHERE column operator value
SELECT column FROM table WHERE column LIKE pattern
SELECT column,SUM(column) FROM table GROUP BY column
SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column)
condition value
Note that single quotes around text values and numeric values should not be enclosed in
quotes. Double quotes may be acceptable in some databases.

4. The SELECT INTO Statement is most often used to create backup copies of
tables or for archiving records.

SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source


SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE
column_name operator value

5. The INSERT INTO Statements:

INSERT INTO table_name VALUES (value1, value2,....)


INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

6. The Update Statement:

UPDATE table_name SET column_name = new_value WHERE column_name = some_value

7. The Delete Statements:

DELETE FROM table_name WHERE column_name = some_value


Delete All Rows:
DELETE FROM table_name or DELETE * FROM table_name

8. Sort the Rows:

SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, ..


SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC
SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC

9. The IN operator may be used if you know the exact value you want to return for
at least one of the columns.

SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)

10. BETWEEN ... AND

SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND


value2 The values can be numbers, text, or dates.

11. What is the use of CASCADE CONSTRAINTS?

When this clause is used with the DROP command, a parent table can be dropped even
when a child table exists.

12. Why does the following command give a compilation error?

DROP TABLE &TABLE_NAME; Variable names should start with an alphabet. Here the table
name starts with an '&' symbol.

13. Which system tables contain information on privileges granted and privileges
obtained?

USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD

14. Which system table contains information on constraints on all the tables
created?obtained?

USER_CONSTRAINTS.
15. What is the difference between TRUNCATE and DELETE commands?

< TRUNCATE. with and DELETE used be can clause WHERE back. rolled cannot operation
TRUNCATE but back, Hence command. DML a is whereas command DDL>

16. State true or false. !=, <>, ^= all denote the same operation?

True.

17. State true or false. EXISTS, SOME, ANY are operators in SQL?

True.

18. What will be the output of the following query?

SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE')


FROM DUAL;?

19. What does the following query do?

SELECT SAL + NVL(COMM,0) FROM EMP;?


This displays the total salary of all employees. The null values in the commission column will
be replaced by 0 and added to salary.

20. What is the advantage of specifying WITH GRANT OPTION in the GRANT
command?

The privilege receiver can further grant the privileges he/she has obtained from the owner
to any other user.

21. Which command executes the contents of a specified file?

START or @.

22. What is the value of comm and sal after executing the following query if the
initial value of ‘sal’ is 10000
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;?
sal = 11000, comm = 1000.

23. Which command displays the SQL command in the SQL buffer, and then
executes it?

RUN.

24. What command is used to get back the privileges offered by the GRANT
command?

REVOKE.

25. What will be the output of the following query? SELECT


DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );? NO.

Explanation : The query checks whether a given string is a numerical digit.

26. Which date function is used to find the difference between two dates?

MONTHS_BETWEEN.

27. What operator performs pattern matching?

LIKE operator.

28. What is the use of the DROP option in the ALTER TABLE command?

It is used to drop constraints specified on the table.

29. What operator tests column for the absence of data?

IS NULL operator.

30. What are the privileges that can be granted on a table by a user to others?

Insert, update, delete, select, references, index, execute, alter, all.

31. Which function is used to find the largest integer less than or equal to a
specific value?

FLOOR.

32. Which is the subset of SQL commands used to manipulate Oracle Database
structures, including tables?

Data Definition Language (DDL).

33. What is the use of DESC in SQL?

DESC has two purposes. It is used to describe a schema as well as to retrieve rows from
table in descending order.
Explanation :
The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on
ENAME in descending order.

34. What command is used to create a table by copying the structure of another
table?

CREATE TABLE .. AS SELECT command


Explanation:
To copy only the structure, the WHERE clause of the SELECT command should contain a
FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be
copied to the new table.

35. TRUNCATE TABLE EMP;


DELETE FROM EMP;
Will the outputs of the above two commands differ?

Both will result in deleting all the rows in the table EMP..

36. What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM
DUAL;?

1200.

37. What are the wildcards used for pattern matching.?


_ for single character substitution and % for multi-character substitution.

38. What is the parameter substitution symbol used with INSERT INTO command?

&

39. What is the sub-query?

Sub-query is a query whose return values are used in filtering conditions of the main query.

40. What is correlated sub-query?

Correlated sub-query is a sub-query, which has reference to the main query.

41. Explain CONNECT BY PRIOR?

Retrieves rows in hierarchical order eg.


select empno, ename from emp where.

42. Difference between SUBSTR and INSTR?

INSTR (String1, String2 (n, (m)),


INSTR returns the position of the m-th occurrence of the string 2 in string1. The search
begins from nth position of string1.
SUBSTR (String1 n, m)
SUBSTR returns a character string of size m in string1, starting from n-th position of
string1.

43. Explain UNION, MINUS, UNION ALL and INTERSECT?

INTERSECT - returns all distinct rows selected by both queries. MINUS - returns all distinct
rows selected by the first query but not by the second. UNION - returns all distinct rows
selected by either query UNION ALL - returns all rows selected by either query, including all
duplicates.

44. What is ROWID?

ROWID is a pseudo column attached to each row of a table. It is 18 characters long,


blockno, rownumber are the components of ROWID.
45. What is the fastest way of accessing a row in a table?

Using ROWID.
CONSTRAINTS

46. What is an integrity constraint?

Integrity constraint is a rule that restricts values to a column in a table.

47. What is referential integrity constraint?

Maintaining data integrity through a set of rules that restrict the values of one or more
columns of the tables based on the values of primary key or unique key of the referenced
table.

48. What is the usage of SAVEPOINTS?

SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back
part of a transaction. Maximum of five save points are allowed.

49. What is ON DELETE CASCADE?

When ON DELETE CASCADE is specified Oracle maintains referential integrity by


automatically removing dependent foreign key values if a referenced primary or unique key
value is removed.

50. What are the data types allowed in a table?

CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

SQL and PL/SQL Interview questions-II


54. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for
each type?
CHAR pads blank spaces to the maximum length.
VARCHAR2 does not pad blank spaces.
For CHAR the maximum length is 255 and 2000 for VARCHAR2.
55. How many LONG columns are allowed in a table? Is it possible to use LONG columns in
WHERE clause or ORDER BY?
Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY
clause.

56. What are the pre-requisites to modify datatype of a column and to add a column with NOT
NULL constraint?
- To modify the datatype of a column the column must be empty.
- To add a column with NOT NULL constrain, the table must be empty.

57. Where the integrity constraints are stored in data dictionary?


The integrity constraints are stored in USER_CONSTRAINTS.

58. How will you activate/deactivate integrity constraints?


The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT /
DISABLE CONSTRAINT.
59. If unique key constraint on DATE column is created, will it validate the rows that are inserted
with SYSDATE?
It won't, Because SYSDATE format contains time attached with it.

60. What is a database link?


Database link is a named path through which a remote database can be accessed.

60. How to access the current value and next value from a sequence? Is it possible to access the
current value in a session before accessing next value?
Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you access next value
in the session, current value can be accessed.

60.What is CYCLE/NO CYCLE in a Sequence?


CYCLE specifies that the sequence continue to generate values after reaching either maximum or
minimum value. After pan-ascending sequence reaches its maximum value, it generates its minimum
value. After a descending sequence reaches its minimum, it generates its maximum.
NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or
minimum value.

61. What are the advantages of VIEW?


- To protect some of the columns of a table from other users.
- To hide complexity of a query.
- To hide complexity of calculations.

62. Can a view be updated/inserted/deleted? If Yes - under what conditions?


A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from
one or more tables then insert, update and delete is not possible.

63. If a view on a single base table is manipulated will the changes be reflected on the base table?
If changes are made to the tables and these tables are the base tables of a view, then the changes will be
reference on the view.
64. Which of the following statements is true about implicit cursors?
1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.
3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.

65. Which of the following is not a feature of a cursor FOR loop?


1. Record type declaration.
2. Opening and parsing of SQL statements.
3. Fetches records from cursor.
4. Requires exit condition to be defined.

66. A developer would like to use referential datatype declaration on a variable. The variable name
is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME,
respectively. How would the developer define this variable using referential datatypes?
1. Use employee.lname%type.
2. Use employee.lname%rowtype.
3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
4. Declare it to be type LONG.

67. Which three of the following are implicit cursor attributes?


1. %found
2. %too_many_rows
3. %notfound
4. %rowcount
5. %rowtype

68. If left out, which of the following would cause an infinite loop to occur in a simple loop?
1. LOOP
2. END LOOP
3. IF-THEN
4. EXIT
69. Which line in the following statement will produce an error?
1. cursor action_cursor is
2. select name, rate, action
3. into action_record
4. from action_table;
5. There are no errors in this statement.

70. The command used to open a CURSOR FOR loop is


1. open
2. fetch
3. parse
4. None, cursor for loops handle cursor opening implicitly.

71. What happens when rows are found using a FETCH statement
1. It causes the cursor to close
2. It causes the cursor to open
3. It loads the current row values into variables
4. It creates the variables to hold the current row values

72. Read the following code:


10. CREATE OR REPLACE PROCEDURE find_cpt
11. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)
12. IS
13. BEGIN
14. IF v_cost_per_ticket > 8.5 THEN
15. SELECT cost_per_ticket
16. INTO v_cost_per_ticket
17. FROM gross_receipt
18. WHERE movie_id = v_movie_id;
19. END IF;
20. END;
Which mode should be used for V_COST_PER_TICKET?
1. IN
2. OUT
3. RETURN
4. IN OUT
73. Read the following code:
22. CREATE OR REPLACE TRIGGER update_show_gross
23. {trigger information}
24. BEGIN
25. {additional code}
26. END;

The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which
trigger information will you add?

1. WHEN (new.cost_per_ticket > 3.75)


2. WHEN (:new.cost_per_ticket > 3.75
3. WHERE (new.cost_per_ticket > 3.75)
4. WHERE (:new.cost_per_ticket > 3.75)

74. What is the maximum number of handlers processed before the PL/SQL block is exited when
an exception occurs?
1. Only one
2. All that apply
3. All referenced
4. None

77. For which trigger timing can you reference the NEW and OLD qualifiers?
1. Statement and Row 2. Statement only 3. Row only 4. Oracle Forms trigger

78. Read the following code:


CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
RETURN number IS

v_yearly_budget NUMBER;

BEGIN
SELECT yearly_budget
INTO v_yearly_budget
FROM studio
WHERE id = v_studio_id;

RETURN v_yearly_budget;
END;
Which set of statements will successfully invoke this function within SQL*Plus?
1. VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget := GET_BUDGET(11);
2. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
3. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
4. VARIABLE g_yearly_budget NUMBER
31. CREATE OR REPLACE PROCEDURE update_theater
32. (v_name IN VARCHAR v_theater_id IN NUMBER) IS
33. BEGIN
34. UPDATE theater
35. SET name = v_name
36. WHERE id = v_theater_id;
37. END update_theater;
79. When invoking this procedure, you encounter the error:
ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How should you modify the function to handle this error?
1. An user defined exception must be declared and associated with the error code and handled in the
EXCEPTION section.
2. Handle the error in EXCEPTION section by referencing the error code directly.
3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined
exception.
4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.

80. Read the following code:


40. CREATE OR REPLACE PROCEDURE calculate_budget IS
41. v_budget studio.yearly_budget%TYPE;
42. BEGIN
43. v_budget := get_budget(11);
44. IF v_budget < 30000
45. THEN
46. set_budget(11,30000000);
47. END IF;
48. END;

You are about to add an argument to CALCULATE_BUDGET. What effect will this have?
1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.
2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution.
3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
4. All three procedures are marked invalid and must be recompiled.

81. Which procedure can be used to create a customized error message?


1. RAISE_ERROR
2. SQLERRM
3. RAISE_APPLICATION_ERROR
4. RAISE_SERVER_ERROR

82. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can
you issue to enable this trigger?
1. ALTER TRIGGER check_theater ENABLE;
2. ENABLE TRIGGER check_theater;
3. ALTER TABLE check_theater ENABLE check_theater;
4. ENABLE check_theater;

83. Examine this database trigger


52. CREATE OR REPLACE TRIGGER prevent_gross_modification
53. {additional trigger information}
54. BEGIN
55. IF TO_CHAR(sysdate, DY) = MON
56. THEN
57. RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);
58. END IF;
59. END;

This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the
entire DELETE statement. What additional information must you add?
1. BEFORE DELETE ON gross_receipt
2. AFTER DELETE ON gross_receipt
3. BEFORE (gross_receipt DELETE)
4. FOR EACH ROW DELETED FROM gross_receipt

SQL and PL/SQL Interview questions-III

85. Under which circumstance must you recompile the package body after
recompiling the package specification?
1. Altering the argument list of one of the package constructs
2. Any change made to one of the package constructs
3. Any SQL statement change made to one of the package constructs
4. Removing a local variable from the DECLARE section of one of the package constructs

86. Procedure and Functions are explicitly executed. This is different from a
database trigger. When is a database trigger executed?
1. When the transaction is committed
2. During the data manipulation statement
3. When an Oracle supplied package references the trigger
4. During a data manipulation statement and when the transaction is committed

87. Which Oracle supplied package can you use to output values and messages
from database triggers, stored procedures and functions within SQL*Plus?
1. DBMS_DISPLAY 2. DBMS_OUTPUT 3. DBMS_LIST 4. DBMS_DESCRIBE
88. What occurs if a procedure or function terminates with failure without being
handled?
1. Any DML statements issued by the construct are still pending and can be committed or
rolled back.
2. Any DML statements issued by the construct are committed
3. Unless a GOTO statement is used to continue processing within the BEGIN section, the
construct terminates.
4. The construct rolls back any DML statements issued and returns the unhandled exception
to the calling environment.
89. Examine this code
71. BEGIN
72. theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;
73. END;

For this code to be successful, what must be true?


1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR
function must exist only in the body of the THEATER_PCK package.
2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the
THEATER_PCK package.
3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the
THEATER_PCK package.
4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR
function must exist in the specification of the THEATER_PCK package.

90 A stored function must return a value based on conditions that are determined
at runtime. Therefore, the SELECT statement cannot be hard-coded and must be
created dynamically when the function is executed. Which Oracle supplied
package will enable this feature?
1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN
4. DBMS_SQL

90 A stored function must return a value based on conditions that are determined
at runtime. Therefore, the SELECT statement cannot be hard-coded and must be
created dynamically when the function is executed. Which Oracle supplied
package will enable this feature?
1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN
4. DBMS_SQL
91 How to implement ISNUMERIC function in SQL *Plus ?
Method 1:

Select length (translate (trim (column_name),' +-.0123456789',' ')) from dual ;

Will give you a zero if it is a number or greater than zero if not numeric (actually gives the
count of non numeric characters)

Method 2:

select instr(translate('wwww',
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'),'X')
FROM dual;

It returns 0 if it is a number, 1 if it is not.


92 How to Select last N records from a Table?
select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm)
where a > ( select (max(rownum)-10) from clm)

Here N = 10

The following query has a Problem of performance in the execution of the following query
where the table ter.ter_master have 22231 records. So the results are obtained after hours.

Cursor rem_master(brepno VARCHAR2) IS


select a.* from ter.ter_master a
where NOT a.repno in (select repno from ermast) and
(brepno = 'ALL' or a.repno > brepno)
Order by a.repno

What are steps required tuning this query to improve its performance?

-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO

-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution path
that Oracle takes. If you are using Cost Based Optimizer mode, then be sure that your
statistics on TER_MASTER are up-to-date. -Also, you can change your SQL to:

SELECT a.*
FROM ter.ter_master a
WHERE NOT EXISTS (SELECT b.repno FROM ermast b
WHERE a.repno=b.repno) AND
(a.brepno = 'ALL' or a.repno > a.brepno)
ORDER BY a.repno;

93 What is the difference between Truncate and Delete interms of Referential


Integrity?
DELETE removes one or more records in a table, checking referential Constraints (to see if
there are dependent child records) and firing any DELETE triggers. In the order you are
deleting (child first then parent) There will be no problems.
TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it only
checks for the existence (and status) of another foreign key Pointing to the table. If one
exists and is enabled, then you will get The following error. This is true even if you do the
child tables first.
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
You should disable the foreign key constraints in the child tables before issuing the
TRUNCATE command, then re-enable them afterwards.
CLIENT/SERVER

94. What does preemptive in preemptive multitasking mean ?


Preemptive refers to the fact that each task is alloted fixed time slots and at the end of that
time slot the next task is started.

95. What does the OLTP stands for ?


OLTP stands for On Line Transaction Processing

96. What is the most important requirement for OLTP ?


OLTP requires real time response.

97. In a client server environment, what would be the major work that the client
deals with ?
The client deals with the user interface part of the system.

98. Why is the most of the processing done at the sever ?


To reduce the network traffic and for application sharing and implementing business rules.

99. What does teh term upsizing refer to ?


Applications that have outgrown their environment are re-engineered to run in a larger
environment. This is upsizing.

100. What does one do when one is rightsizing ?


With rightsizing, one would move applications to the most appropriate server platforms.

101. What does the term downsizing refer to ?


A host based application is re-engineered to run in smaller or LAN based environment.

102. What is event trigger ?


An event trigger, a segment of code which is associated with each event and is fired when
the event occurs.

103. Why do stored procedures reduce network traffic ?


When a stored procedure is called, only the procedure call is sent to the server and not the
statements that the procedure contains.
104. What are the types of processes that a server runs ?
Foreground process and Background process.

105. What is a event handler ?


An event handler is a routine that is written to respond to a particular event.

106. What is an integrity constraint ?


An integrity constraint allows the definition of certain restrictions, at the table level, on the
data that is entered into a table.

107. What are the various uses of database triggers ?


Database triggers can be used to enforce business rules, to maintain derived values and
perform value-based auditing.

108. What is a transaction ?


A transaction is a set of operations that begin when the first DML is issued and end when a
commit or rollback is issued. BEGIN COMMIT/ROLLBACK are the boundries of a transaction.
109. Why are the integrity constraints preferred to database triggers ?
Because it is easier to define an integrity constraint than a database trigger.

110. Why is it better to use an integrity constraint to validate data in a table than
to use a stored procedure ?
Because an integrity constraint is automatically checked while data is inserted into a table.
A stored has to be specifically invoked.

111. What are the three components of a client server model ?


A Client,
A Server and
A Network/Communication software.

112. What are the advantages of client/server model ?


Flexibility of the system, scalability, cost saving, centralised control and implementation of
business rules, increase of developers productivity, portability, improved network and
resource utilization.

113. What are the disadvantages of the client/server model ?


Heterogeneity of the system results in reduced reliablity. May not be suitable for all
applications. Managing and tuning networks becomes difficult.

114. What are the different topologies available for network ?


Star,
Bus,
Ring.

115. What is the first work of Client process ?


A client process at first establishes connection with the Server.
115. What are the responsibilities of a Server ?
1. Manage resources optimally across multiple clients.
2. Controlling database access and security.
3. Protecting the databse and recovering it from crashes.
4. Enforcing integrity rules globally.
116. In a Client/Server context, what does API (Application Programming
Interface) refer to ?
An API, in a Client/Server context, is a specification of a set of functions for communication
between the client and the server.

117. Give some examples of standard API??s ?


Open Database Connectivity (ODBC),
Integrated Database Application Programming Interface (IDAPI),
XOpen
SQL/CLI

118. What is the main advantage of developing an application using an API ?


The application can be connected to any back end server that is supported by the API.

119. What is the main disadvantage of developing an application using an API ?


The application cannot use any special features of the backend server.

120. Why is an event driven program referred to a passive program ?


Because an event driven program is always waiting for something to happen before
processing.

120. What are the four types of events ?


1. System Events.
2. Control Events
3. User Events
4. Other Events.

121. What is the difference between file server and a database server ?
A file server just transfers all the data requested by all its client and the client processes the
data while a database server runs the query and sends only the query output.

122. What is inheritance ?


Inheritance is a method by which properties and methods of an existing object are
automatically passed to any object derived from it.

123. What are the two components of ODBC ?


1. An ODBC manager/administrator and
2. ODBC driver.
124. What is the function of a ODBC manager ?
The ODBC Manager manages all the data sources that exists in the system.

125. What is the function of a ODBC Driver ?


The ODBC Driver allows the developer to talk to the back end database.

126. What description of a data source is required for ODBC ?


The name of the DBMS, the location of the source and the database dependent information.

127. How is a connection establised by ODBC ?


ODBC uses the description of the datasource available in the ODBC.INI file to load the
required drivers to access that particular back end database.

SQL Queries
Create the following Tables:

LOCATION
Location_ID Regional_Group
122 NEW YORK
DALLAS
123
CHICAGO
124
167 BOSTON

DEPARTMENT
Department_ID Name Location_ID
10 ACCOUNTING 122
124
20 RESEARCH
123
30 SALES
40 OPERATIONS 167
JOB
Job_ID Function
667 CLERK
STAFF
668
ANALYST
669
670 SALESPERSON
MANAGER
671
PRESIDENT
672

EMPLOYEE
EMPLOYEE_ID LAST_NAME FIRST_NAME MIDDLE_NAME JOB_ID MANAGER_ID HIREDATE SALAR

7369 SMITH JOHN Q 667 7902 17-DEC-84 800


7499 ALLEN KEVIN J 670 7698 20-FEB-85 1600

7505 DOYLE JEAN K 671 7839 04-APR-85 2850

7506 DENNIS LYNN S 671 7839 15-MAY-85 2750

7507 BAKER LESLIE D 671 7839 10-JUN-85 2200

7521 WARK CYNTHIA D 670 7698 22-FEB-85 1250

Queries based on the above tables:

Simple Queries:

1. List all the employee details

2. List all the department details

3. List all job details

4. List all the locations

5. List out first name,last name,salary, commission for all employees

6. List out employee_id,last name,department id for all employees and rename employee
id as “ID of the employee”, last name as “Name of the employee”, department id as
“department ID”

7. List out the employees anuual salary with their names only.

Where Conditions:

8. List the details about “SMITH”

9. List out the employees who are working in department 20

10. List out the employees who are earning salary between 3000 and 4500

11. List out the employees who are working in department 10 or 20

12. Find out the employees who are not working in department 10 or 30

13. List out the employees whose name starts with “S”

14. List out the employees whose name start with “S” and end with “H”

15. List out the employees whose name length is 4 and start with “S”

16. List out the employees who are working in department 10 and draw the salaries more
than 3500

17. list out the employees who are not receiving commission.

Order By Clause:

18. List out the employee id, last name in ascending order based on the employee id.

19. List out the employee id, name in descending order based on salary column

20. list out the employee details according to their last_name in ascending order and
salaries in descending order

21. list out the employee details according to their last_name in ascending order and then
on department_id in descending order.

Group By & Having Clause:

22. How many employees who are working in different departments wise in the
organization

23. List out the department wise maximum salary, minimum salary, average salary of the
employees

24. List out the job wise maximum salary, minimum salary, average salaries of the
employees.
25. List out the no.of employees joined in every month in ascending order.

26. List out the no.of employees for each month and year, in the ascending order based on
the year, month.

27. List out the department id having atleast four employees.

28. How many employees in January month.

29. How many employees who are joined in January or September month.

30. How many employees who are joined in 1985.

31. How many employees joined each month in 1985.

32. How many employees who are joined in March 1985.

33. Which is the department id, having greater than or equal to 3 employees joined in April
1985.

Sub-Queries

34. Display the employee who got the maximum salary.

35. Display the employees who are working in Sales department

36. Display the employees who are working as “Clerk”.

37. Display the employees who are working in “New York”

38. Find out no.of employees working in “Sales” department.

39. Update the employees salaries, who are working as Clerk on the basis of 10%.

40. Delete the employees who are working in accounting department.

41. Display the second highest salary drawing employee details.

42. Display the Nth highest salary drawing employee details

Sub-Query operators: (ALL,ANY,SOME,EXISTS)

43. List out the employees who earn more than every employee in department 30.

44. List out the employees who earn more than the lowest salary in department 30.

45. Find out whose department has not employees.

46. Find out which department does not have any employees.
Co-Related Sub Queries:

47.Find out the employees who earn greater than the average salary for their department.

JOINS
Simple join

48.List our employees with their department names


49.Display employees with their designations (jobs)
50.Display the employees with their department name and regional groups.
51.How many employees who are working in different departments and display with
department name.
52.How many employees who are working in sales department.
53.Which is the department having greater than or equal to 5 employees and display the
department names in ascending order.
54.How many jobs in the organization with designations.
55.How many employees working in “New York”.

Non – Equi Join:

56.Display employee details with salary grades.


57.List out the no. of employees on grade wise.
58.Display the employ salary grades and no. of employees between 2000 to 5000 range of
salary.

Self Join:

59.Display the employee details with their manager names.


60.Display the employee details who earn more than their managers salaries.
61.Show the no. of employees working under every manager.

Outer Join:

61.Display employee details with all departments.


62.Display all employees in sales or operation departments.

Set Operators:

63.List out the distinct jobs in Sales and Accounting Departments.


64.List out the ALL jobs in Sales and Accounting Departments.
65.List out the common jobs in Research and Accounting Departments in ascending order.
Answers
1. SQL > Select * from employee;

2. SQL > Select * from department;

3. SQL > Select * from job;

4. SQL > Select * from loc;

5. SQL > Select first_name, last_name, salary, commission from employee;

6. SQL > Select employee_id “id of the employee”, last_name “name", department id as
“department id” from employee;

7. SQL > Select last_name, salary*12 “annual salary” from employee

8. SQL > Select * from employee where last_name=’SMITH’;

9. SQL > Select * from employee where department_id=20

10. SQL > Select * from employee where salary between 3000 and 4500

11. SQL > Select * from employee where department_id in (20,30)

12. SQL > Select last_name, salary, commission, department_id from employee where
department_id not in (10,30)

13. SQL > Select * from employee where last_name like ‘S%’

14. SQL > Select * from employee where last_name like ‘S%H’

15. SQL > Select * from employee where last_name like ‘S___’

16. SQL > Select * from employee where department_id=10 and salary>3500

17. SQL > Select * from employee where commission is Null

18. SQL > Select employee_id, last_name from employee order by employee_id

19. SQL > Select employee_id, last_name, salary from employee order by salary desc

20. SQL > Select employee_id, last_name, salary from employee order by last_name,
salary desc

21. SQL > Select employee_id, last_name, salary from employee order by last_name,
department_id desc

22. SQL > Select department_id, count(*), from employee group by department_id
23. SQL > Select department_id, count(*), max(salary), min(salary), avg(salary) from
employee group by department_id

24. SQL > Select job_id, count(*), max(salary), min(salary), avg(salary) from employee
group by job_id

25. SQL > Select to_char(hire_date,’month’)month, count(*) from employee group by


to_char(hire_date,’month’) order by month

26. SQL > Select to_char(hire_date,’yyyy’) Year, to_char(hire_date,’mon’) Month, count(*)


“No. of employees” from employee group by to_char(hire_date,’yyyy’),
to_char(hire_date,’mon’)

27. SQL > Select department_id, count(*) from employee group by department_id having
count(*)>=4

28. SQL > Select to_char(hire_date,’mon’) month, count(*) from employee group by
to_char(hire_date,’mon’) having to_char(hire_date,’mon’)=’jan’

29. SQL > Select to_char(hire_date,’mon’) month, count(*) from employee group by
to_char(hire_date,’mon’) having to_char(hire_date,’mon’) in (‘jan’,’sep’)

30. SQL > Select to_char(hire_date,’yyyy’) Year, count(*) from employee group by
to_char(hire_date,’yyyy’) having to_char(hire_date,’yyyy’)=1985

31. SQL > Select to_char(hire_date,’yyyy’)Year, to_char(hire_date,’mon’) Month, count(*)


“No. of employees” from employee where to_char(hire_date,’yyyy’)=1985 group by
to_char(hire_date,’yyyy’),to_char(hire_date,’mon’)

32. SQL > Select to_char(hire_date,’yyyy’)Year, to_char(hire_date,’mon’) Month, count(*)


“No. of employees” from employee where to_char(hire_date,’yyyy’)=1985 and
to_char(hire_date,’mon’)=’mar’ group by
to_char(hire_date,’yyyy’),to_char(hire_date,’mon’)

33. SQL > Select department_id, count(*) “No. of employees” from employee where
to_char(hire_date,’yyyy’)=1985 and to_char(hire_date,’mon’)=’apr’ group by
to_char(hire_date,’yyyy’), to_char(hire_date,’mon’), department_id having
count(*)>=3

34. SQL > Select * from employee where salary=(select max(salary) from employee)

35. SQL > Select * from employee where department_id IN (select department_id from
department where name=’SALES’)

36. SQL > Select * from employee where job_id in (select job_id from job where
function=’CLERK’

37. SQL > Select * from employee where department_id=(select department_id from
department where location_id=(select location_id from location where
regional_group=’New York’))

38. SQL > Select * from employee where department_id=(select department_id from
department where name=’SALES’ group by department_id)

39. SQL > Update employee set salary=salary*10/100 wehre job_id=(select job_id from
job where function=’CLERK’)

40. SQL > delete from employee where department_id=(select department_id from
department where name=’ACCOUNTING’)

41. SQL > Select * from employee where salary=(select max(salary) from employee where
salary <(select max(salary) from employee))

42. SQL > Select distinct e.salary from employee where & no-1=(select count(distinct
salary) from employee where sal>e.salary)

43. SQL > Select * from employee where salary > all (Select salary from employee where
department_id=30)

44. SQL > Select * from employee where salary > any (Select salary from employee where
department_id=30)

45. SQL > Select employee_id, last_name, department_id from employee e where not
exists (select department_id from department d where
d.department_id=e.department_id)

46. SQL > Select name from department d where not exists (select last_name from
employee e where d.department_id=e.department_id)

47. SQL > Select employee_id, last_name, salary, department_id from employee e where
salary > (select avg(salary) from employee where department_id=e.department_id)

48. SQL > Select employee_id, last_name, name from employee e, department d where
e.department_id=d.department_id

49. SQL > Select employee_id, last_name, function from employee e, job j where
e.job_id=j.job_id

50. SQL > Select employee_id, last_name, name, regional_group from employee e,
department d, location l where e.department_id=d.department_id and
d.location_id=l.location_id

51. SQL > Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name

52. SQL > Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name having name=’SALES’

53. SQL > Select name, count(*) from employee e, department d where
d.department_id=e.department_id group by name having count (*)>=5 order by name

54. SQL > Select function, count(*) from employee e, job j where j.job_id=e.job_id group
by function
55. SQL > Select regional_group, count(*) from employee e, department d, location l
where e.department_id=d.department_id and d.location_id=l.location_id and
regional_group=’NEW YORK’ group by regional_group

56. SQL > Select employee_id, last_name, grade_id from employee e, salary_grade s
where salary between lower_bound and upper_bound order by last_name

57. SQL > Select grade_id, count(*) from employee e, salary_grade s where salary
between lower_bound and upper_bound group by grade_id order by grade_id desc

58. SQL > Select grade_id, count(*) from employee e, salary_grade s where salary
between lower_bound and upper_bound and lower_bound>=2000 and
lower_bound<=5000 group by grade_id order by grade_id desc

59. SQL > Select e.last_name emp_name, m.last_name, mgr_name from employee e,
employee m where e.manager_id=m.employee_id

60. SQL > Select e.last_name emp_name, e.salary emp_salary, m.last_name, mgr_name,
m.salary mgr_salary from employee e, employee m where
e.manager_id=m.employee_id and m.salary

61. SQL > Select m.manager_id, count(*) from employee e, employee m where
e.employee_id=m.manager_id group by m.manager_id

62. SQL > Select last_name, d.department_id, d.name from employee e, department d
where e.department_id(+)=d.department_id

63. SQL > Select last_name, d.department_id, d.name from employee e, department d
where e.department_id(+)=d.department_id and d.department_idin (select
department_id from department where name IN (‘SALES’,’OPERATIONS’))

64. SQL > Select function from job where job_id in (Select job_id from employee where
department_id=(select department_id from department where name=’SALES’)) union
Select function from job where job_id in (Select job_id from employee where
department_id=(select department_id from department where name=’ACCOUNTING’))

65. SQL > Select function from job where job_id in (Select job_id from employee where
department_id=(select department_id from department where name=’SALES’)) union
all Select function from job where job_id in (Select job_id from employee where
department_id=(select department_id from department where name=’ACCOUNTING’))

66. SQL > Select function from job where job_id in (Select job_id from employee where
department_id=(select department_id from department where name=’RESEARCH’))
intersect Select function from job where job_id in (Select job_id from employee where
department_id=(select department_id from department where name=’ACCOUNTING’))
order by function

SQL Concepts
Basics of the SELECT Statement
In a relational database, data is stored in tables. An example table would relate Social Security Number,
Name, and Address:

EmployeeAddressTable

SSN FirstName LastName Address City State

512687458 Joe Smith 83 First Street Howard Ohio

758420012 Mary Scott 842 Vine Ave. Losantiville Ohio

102254896 Sam Jones 33 Elm St. Paris New York

876512563 Sarah Ackerman 440 U.S. 110 Upton Michigan

Now, let's say you want to see the address of each employee. Use the SELECT statement, like so:
SELECT FirstName, LastName, Address, City, State
FROM EmployeeAddressTable;
The following is the results of your query of the database:

First Name Last Name Address City State

Joe Smith 83 First Street Howard Ohio

Mary Scott 842 Vine Ave. Losantiville Ohio

Sam Jones 33 Elm St. Paris New York

Sarah Ackerman 440 U.S. 110 Upton Michigan

To explain what you just did, you asked for the all of data in the EmployeeAddressTable, and specifically,
you asked for the columns called FirstName, LastName, Address, City, and State. Note that column
names and table names do not have spaces...they must be typed as one word; and that the statement
ends with a semicolon (;). The general form for a SELECT statement, retrieving all of the rows in the table
is:
SELECT ColumnName, ColumnName, ...
FROM TableName;
To get all columns of a table without typing all column names, use:
SELECT * FROM TableName;
Each database management system (DBMS) and database software has different methods for logging in
to the database and entering SQL commands; see the local computer "guru" to help you get onto the
system, so that you can use SQL.

Conditional Selection
To further discuss the SELECT statement, let's look at a new example table (for hypothetical purposes
only):
EmployeeStatisticsTable

EmployeeIDNo Salary Benefits Position

010 75000 15000 Manager

105 65000 15000 Manager

152 60000 15000 Manager

215 60000 12500 Manager

244 50000 12000 Staff

300 45000 10000 Staff

335 40000 10000 Staff

400 32000 7500 Entry-Level

441 28000 7500 Entry-Level

a) Relational Operators
There are six Relational Operators in SQL, and after introducing them, we'll see how they're used:

= Equal

< or != (see
Not Equal
manual)

< Less Than

> Greater Than

<= Less Than or Equal To

>= Greater Than or Equal To

The WHERE clause is used to specify that only certain rows of the table are displayed, based on the
criteria described in that WHERE clause. It is most easily understood by looking at a couple of examples.

If you wanted to see the EMPLOYEEIDNO's of those making at or over $50,000, use the following:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY >= 50000;

Notice that the >= (greater than or equal to) sign is used, as we wanted to see those who made greater
than $50,000, or equal to $50,000, listed together. This displays:
EMPLOYEEIDNO
------------
010
105
152
215
244

The WHERE description, SALARY >= 50000, is known as a condition (an operation which evaluates to
True or False). The same can be done for text columns:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE POSITION = 'Manager';

This displays the ID Numbers of all Managers. Generally, with text columns, stick to equal to or not equal
to, and make sure that any text that appears in the statement is surrounded by single quotes ('). Note:
Position is now an illegal identifier because it is now an unused, but reserved, keyword in the SQL-92
standard.

More Complex Conditions: Compound Conditions / Logical Operators

The AND operator joins two or more conditions, and displays a row only if that row's data satisfies ALL
conditions listed (i.e. all conditions hold true). For example, to display all staff making over $40,000, use:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY > 40000 AND POSITION = 'Staff'; z

The OR operator joins two or more conditions, but returns a row if ANY of the conditions listed hold true.
To see all those who make less than $40,000 or have less than $10,000 in benefits, listed together, use
the following query:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY < 40000 OR BENEFITS < 10000;

AND & OR can be combined, for example:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE POSITION = 'Manager' AND SALARY > 60000 OR BENEFITS > 12000;

First, SQL finds the rows where the salary is greater than $60,000 and the position column is equal to
Manager, then taking this new list of rows, SQL then sees if any of these rows satisfies the previous AND
condition or the condition that the Benefits column is greater than $12,000. Subsequently, SQL only
displays this second new list of rows, keeping in mind that anyone with Benefits over $12,000 will be
included as the OR operator includes a row if either resulting condition is True. Also note that the AND
operation is done first.

To generalize this process, SQL performs the AND operation(s) to determine the rows where the AND
operation(s) hold true (remember: all of the conditions are true), then these results are used to compare
with the OR conditions, and only display those remaining rows where any of the conditions joined by the
OR operator hold true (where a condition or result from an AND is paired with another condition or AND
result to use to evaluate the OR, which evaluates to true if either value is true). Mathematically, SQL
evaluates all of the conditions, then evaluates the AND "pairs", and then evaluates the OR's (where both
operators evaluate left to right).

To look at an example, for a given row for which the DBMS is evaluating the SQL statement Where
clause to determine whether to include the row in the query result (the whole Where clause evaluates to
True), the DBMS has evaluated all of the conditions, and is ready to do the logical comparisons on this
result:

True AND False OR True AND True OR False AND False

First simplify the AND pairs:

False OR True OR False

Now do the OR's, left to right:

True OR False
True

The result is True, and the row passes the query conditions. Be sure to see the next section on NOT's,
and the order of logical operations. I hope that this section has helped you understand AND's or OR's, as
it's a difficult subject to explain briefly.

To perform OR's before AND's, like if you wanted to see a list of employees making a large salary
($50,000) or have a large benefit package ($10,000), and that happen to be a manager, use parentheses:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE POSITION = 'Manager' AND (SALARY > 50000 OR BENEFITS > 10000);

IN & BETWEEN

An easier method of using compound conditions uses IN or BETWEEN. For example, if you wanted to list
all managers and staff:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE POSITION IN ('Manager', 'Staff');

or to list those making greater than or equal to $30,000, but less than or equal to $50,000, use:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY BETWEEN 30000 AND 50000;

To list everyone not in this range, try:

SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY NOT BETWEEN 30000 AND 50000;

Similarly, NOT IN lists all rows excluded from the IN list.

Additionally, NOT's can be thrown in with AND's & OR's, except that NOT is a unary operator (evaluates
one condition, reversing its value, whereas, AND's & OR's evaluate two conditions), and that all NOT's
are performed before any AND's or OR's.

SQL Order of Logical Operations (each operates from left to right)

1. NOT

2. AND

3. OR

Using LIKE

Look at the EmployeeStatisticsTable, and say you wanted to see all people whose last names started
with "S"; try:

SELECT EMPLOYEEIDNO
FROM EMPLOYEEADDRESSTABLE
WHERE LASTNAME LIKE 'S%';

The percent sign (%) is used to represent any possible character (number, letter, or punctuation) or set of
characters that might appear after the "S". To find those people with LastName's ending in "S", use '%S',
or if you wanted the "S" in the middle of the word, try '%S%'. The '%' can be used for any characters in
the same position relative to the given characters. NOT LIKE displays rows not fitting the given
description. Other possibilities of using LIKE, or any of these discussed conditionals, are available, though
it depends on what DBMS you are using; as usual, consult a manual or your system manager or
administrator for the available features on your system, or just to make sure that what you are trying to do
is available and allowed. This disclaimer holds for the features of SQL that will be discussed below. This
section is just to give you an idea of the possibilities of queries that can be written in SQL.

Joins
In this section, we will only discuss inner joins, and equijoins, as in general, they are the most useful. For
more information, try the SQL links at the bottom of the page.
Good database design suggests that each table lists data only about a single entity, and detailed
information can be obtained in a relational database, by using additional tables, and by using a join.

First, take a look at these example tables:

AntiqueOwners

OwnerID OwnerLastName OwnerFirstName

01 Jones Bill

02 Smith Bob

15 Lawson Patricia

21 Akins Jane

50 Fowler Sam

Orders

OwnerID ItemDesired

02 Table

02 Desk

21 Chair

15 Mirror

Antiques

SellerID BuyerID Item

01 50 Bed

02 15 Table

15 02 Chair

21 50 Mirror

50 01 Desk

01 21 Cabinet

02 21 Coffee Table
15 50 Chair

01 15 Jewelry Box

02 21 Pottery

21 02 Bookcase

50 01 Plant Stand

Keys

First, let's discuss the concept of keys. A primary key is a column or set of columns that uniquely
identifies the rest of the data in any given row. For example, in the AntiqueOwners table, the OwnerID
column uniquely identifies that row. This means two things: no two rows can have the same OwnerID,
and, even if two owners have the same first and last names, the OwnerID column ensures that the two
owners will not be confused with each other, because the unique OwnerID column will be used
throughout the database to track the owners, rather than the names.

A foreign key is a column in a table where that column is a primary key of another table, which means that
any data in a foreign key column must have corresponding data in the other table where that column is
the primary key. In DBMS-speak, this correspondence is known as referential integrity. For example, in
the Antiques table, both the BuyerID and SellerID are foreign keys to the primary key of the
AntiqueOwners table (OwnerID; for purposes of argument, one has to be an Antique Owner before one
can buy or sell any items), as, in both tables, the ID rows are used to identify the owners or buyers and
sellers, and that the OwnerID is the primary key of the AntiqueOwners table. In other words, all of this "ID"
data is used to refer to the owners, buyers, or sellers of antiques, themselves, without having to use the
actual names.

Performing a Join

The purpose of these keys is so that data can be related across tables, without having to repeat data in
every table--this is the power of relational databases. For example, you can find the names of those who
bought a chair without having to list the full name of the buyer in the Antiques table...you can get the
name by relating those who bought a chair with the names in the AntiqueOwners table through the use of
the OwnerID, which relates the data in the two tables. To find the names of those who bought a chair, use
the following query:

SELECT OWNERLASTNAME, OWNERFIRSTNAME


FROM ANTIQUEOWNERS, ANTIQUES
WHERE BUYERID = OWNERID AND ITEM = 'Chair';

Note the following about this query...notice that both tables involved in the relation are listed in the FROM
clause of the statement. In the WHERE clause, first notice that the ITEM = 'Chair' part restricts the listing
to those who have bought (and in this example, thereby own) a chair. Secondly, notice how the ID
columns are related from one table to the next by use of the BUYERID = OWNERID clause. Only where
ID's match across tables and the item purchased is a chair (because of the AND), will the names from the
AntiqueOwners table be listed. Because the joining condition used an equal sign, this join is called an
equijoin. The result of this query is two names: Smith, Bob & Fowler, Sam.

Dot notation refers to prefixing the table names to column names, to avoid ambiguity, as follows:

SELECT ANTIQUEOWNERS.OWNERLASTNAME, ANTIQUEOWNERS.OWNERFIRSTNAME


FROM ANTIQUEOWNERS, ANTIQUES
WHERE ANTIQUES.BUYERID = ANTIQUEOWNERS.OWNERID AND ANTIQUES.ITEM = 'Chair';

As the column names are different in each table, however, this wasn't necessary.

DISTINCT and Eliminating Duplicates

Let's say that you want to list the ID and names of only those people who have sold an antique.
Obviously, you want a list where each seller is only listed once--you don't want to know how many
antiques a person sold, just the fact that this person sold one (for counts, see the Aggregate Function
section below). This means that you will need to tell SQL to eliminate duplicate sales rows, and just list
each person only once. To do this, use the DISTINCT keyword.

First, we will need an equijoin to the AntiqueOwners table to get the detail data of the person's LastName
and FirstName. However, keep in mind that since the SellerID column in the Antiques table is a foreign
key to the AntiqueOwners table, a seller will only be listed if there is a row in the AntiqueOwners table
listing the ID and names. We also want to eliminate multiple occurrences of the SellerID in our listing, so
we use DISTINCT on the column where the repeats may occur (however, it is generally not necessary to
strictly put the Distinct in front of the column name).

To throw in one more twist, we will also want the list alphabetized by LastName, then by FirstName (on a
LastName tie). Thus, we will use the ORDER BY clause:

SELECT DISTINCT SELLERID, OWNERLASTNAME, OWNERFIRSTNAME


FROM ANTIQUES, ANTIQUEOWNERS
WHERE SELLERID = OWNERID
ORDER BY OWNERLASTNAME, OWNERFIRSTNAME;

In this example, since everyone has sold an item, we will get a listing of all of the owners, in alphabetical
order by last name. For future reference (and in case anyone asks), this type of join is considered to be in
the category of inner joins.

Aliases & In/Subqueries

In this section, we will talk about Aliases, In and the use of subqueries, and how these can be used in a 3-
table example. First, look at this query which prints the last name of those owners who have placed an
order and what the order is, only listing those orders which can be filled (that is, there is a buyer who
owns that ordered item):

SELECT OWN.OWNERLASTNAME Last Name, ORD.ITEMDESIRED Item Ordered


FROM ORDERS ORD, ANTIQUEOWNERS OWN
WHERE ORD.OWNERID = OWN.OWNERID
AND ORD.ITEMDESIRED IN

(SELECT ITEM
FROM ANTIQUES);

This gives:

Last Name Item Ordered


--------- ------------
Smith Table
Smith Desk
Akins Chair
Lawson Mirror

There are several things to note about this query:

1. First, the "Last Name" and "Item Ordered" in the Select lines gives the headers on the report.

2. The OWN & ORD are aliases; these are new names for the two tables listed in the FROM clause
that are used as prefixes for all dot notations of column names in the query (see above). This
eliminates ambiguity, especially in the equijoin WHERE clause where both tables have the
column named OwnerID, and the dot notation tells SQL that we are talking about two different
OwnerID's from the two different tables.

3. Note that the Orders table is listed first in the FROM clause; this makes sure listing is done off of
that table, and the AntiqueOwners table is only used for the detail information (Last Name).

4. Most importantly, the AND in the WHERE clause forces the In Subquery to be invoked ("= ANY"
or "= SOME" are two equivalent uses of IN). What this does is, the subquery is performed,
returning all of the Items owned from the Antiques table, as there is no WHERE clause. Then, for
a row from the Orders table to be listed, the ItemDesired must be in that returned list of Items
owned from the Antiques table, thus listing an item only if the order can be filled from another
owner. You can think of it this way: the subquery returns a set of Items from which each
ItemDesired in the Orders table is compared; the In condition is true only if the ItemDesired is in
that returned set from the Antiques table.

5. Also notice, that in this case, that there happened to be an antique available for each one
desired...obviously, that won't always be the case. In addition, notice that when the IN, "= ANY",
or "= SOME" is used, that these keywords refer to any possible row matches, not column
matches...that is, you cannot put multiple columns in the subquery Select clause, in an attempt to
match the column in the outer Where clause to one of multiple possible column values in the
subquery; only one column can be listed in the subquery, and the possible match comes from
multiple row values in that one column, not vice-versa.
Whew! That's enough on the topic of complex SELECT queries for now. Now on to other SQL
statements.
Miscellaneous SQL Statements
Aggregate Functions

I will discuss five important aggregate functions: SUM, AVG, MAX, MIN, and COUNT. They are called
aggregate functions because they summarize the results of a query, rather than listing all of the rows.

• SUM () gives the total of all the rows, satisfying any conditions, of the given column, where the
given column is numeric.

• AVG () gives the average of the given column.

• MAX () gives the largest figure in the given column.

• MIN () gives the smallest figure in the given column.

• COUNT(*) gives the number of rows satisfying the conditions.


Looking at the tables at the top of the document, let's look at three examples:
SELECT SUM(SALARY), AVG(SALARY)
FROM EMPLOYEESTATISTICSTABLE;

This query shows the total of all salaries in the table, and the average salary of all of the entries in the
table.

SELECT MIN(BENEFITS)
FROM EMPLOYEESTATISTICSTABLE
WHERE POSITION = 'Manager';

This query gives the smallest figure of the Benefits column, of the employees who are Managers, which is
12500.

SELECT COUNT(*)
FROM EMPLOYEESTATISTICSTABLE
WHERE POSITION = 'Staff';

This query tells you how many employees have Staff status (3).

Views

In SQL, you might (check your DBA) have access to create views for yourself. What a view does is to
allow you to assign the results of a query to a new, personal table, that you can use in other queries,
where this new table is given the view name in your FROM clause. When you access a view, the query
that is defined in your view creation statement is performed (generally), and the results of that query look
just like another table in the query that you wrote invoking the view. For example, to create a view:

CREATE VIEW ANTVIEW AS SELECT ITEMDESIRED FROM ORDERS;

Now, write a query using this view as a table, where the table is just a listing of all Items Desired from the
Orders table:

SELECT SELLERID
FROM ANTIQUES, ANTVIEW
WHERE ITEMDESIRED = ITEM;

This query shows all SellerID's from the Antiques table where the Item in that table happens to appear in
the Antview view, which is just all of the Items Desired in the Orders table. The listing is generated by
going through the Antique Items one-by-one until there's a match with the Antview view. Views can be
used to restrict database access, as well as, in this case, simplify a complex query.

Creating New Tables

All tables within a database must be created at some point in time...let's see how we would create the
Orders table:

CREATE TABLE ORDERS


(OWNERID INTEGER NOT NULL,
ITEMDESIRED CHAR(40) NOT NULL);

This statement gives the table name and tells the DBMS about each column in the table. Please note
that this statement uses generic data types, and that the data types might be different, depending on what
DBMS you are using. As usual, check local listings. Some common generic data types are:

• Char(x) - A column of characters, where x is a number designating the maximum number of


characters allowed (maximum length) in the column.

• Integer - A column of whole numbers, positive or negative.

• Decimal(x, y) - A column of decimal numbers, where x is the maximum length in digits of the
decimal numbers in this column, and y is the maximum number of digits allowed after the decimal
point. The maximum (4,2) number would be 99.99.

• Date - A date column in a DBMS-specific format.

• Logical - A column that can hold only two values: TRUE or FALSE.
One other note, the NOT NULL means that the column must have a value in each row. If NULL was used,
that column may be left empty in a given row.

Altering Tables

Let's add a column to the Antiques table to allow the entry of the price of a given Item (Parentheses
optional):

ALTER TABLE ANTIQUES ADD (PRICE DECIMAL(8,2) NULL);

The data for this new column can be updated or inserted as shown later.
Adding Data

To insert rows into a table, do the following:

INSERT INTO ANTIQUES VALUES (21, 01, 'Ottoman', 200.00);

This inserts the data into the table, as a new row, column-by-column, in the pre-defined order. Instead,
let's change the order and leave Price blank:

INSERT INTO ANTIQUES (BUYERID, SELLERID, ITEM)


VALUES (01, 21, 'Ottoman');

Deleting Data

Let's delete this new row back out of the database:

DELETE FROM ANTIQUES


WHERE ITEM = 'Ottoman';

But if there is another row that contains 'Ottoman', that row will be deleted also. Let's delete all rows (one,
in this case) that contain the specific data we added before:

DELETE FROM ANTIQUES


WHERE ITEM = 'Ottoman' AND BUYERID = 01 AND SELLERID = 21;

Updating Data

Let's update a Price into a row that doesn't have a price listed yet:

UPDATE ANTIQUES SET PRICE = 500.00 WHERE ITEM = 'Chair';

This sets all Chair's Prices to 500.00. As shown above, more WHERE conditionals, using AND, must be
used to limit the updating to more specific rows. Also, additional columns may be set by separating equal
statements with commas.

Miscellaneous Topics
Indexes
Indexes allow a DBMS to access data quicker (please note: this feature is nonstandard/not available on
all systems). The system creates this internal data structure (the index) which causes selection of rows,
when the selection is based on indexed columns, to occur faster. This index tells the DBMS where a
certain row is in the table given an indexed-column value, much like a book index tells you what page a
given word appears. Let's create an index for the OwnerID in the AntiqueOwners table:

CREATE INDEX OID_IDX ON ANTIQUEOWNERS (OWNERID);

Now on the names:

CREATE INDEX NAME_IDX ON ANTIQUEOWNERS (OWNERLASTNAME, OWNERFIRSTNAME);

To get rid of an index, drop it:

DROP INDEX OID_IDX;

By the way, you can also "drop" a table, as well (careful!--that means that your table is deleted). In the
second example, the index is kept on the two columns, aggregated together--strange behavior might
occur in this situation...check the manual before performing such an operation.

Some DBMS's do not enforce primary keys; in other words, the uniqueness of a column is not enforced
automatically. What that means is, if, for example, I tried to insert another row into the AntiqueOwners
table with an OwnerID of 02, some systems will allow me to do that, even though we do not, as that
column is supposed to be unique to that table (every row value is supposed to be different). One way to
get around that is to create a unique index on the column that we want to be a primary key, to force the
system to enforce prohibition of duplicates:

CREATE UNIQUE INDEX OID_IDX ON ANTIQUEOWNERS (OWNERID);

GROUP BY & HAVING

One special use of GROUP BY is to associate an aggregate function (especially COUNT; counting the
number of rows in each group) with groups of rows. First, assume that the Antiques table has the Price
column, and each row has a value for that column. We want to see the price of the most expensive item
bought by each owner. We have to tell SQL to group each owner's purchases, and tell us the maximum
purchase price:

SELECT BUYERID, MAX(PRICE)


FROM ANTIQUES
GROUP BY BUYERID;

Now, say we only want to see the maximum purchase price if the purchase is over $1000, so we use the
HAVING clause:

SELECT BUYERID, MAX(PRICE)


FROM ANTIQUES
GROUP BY BUYERID
HAVING PRICE > 1000;
More Subqueries

Another common usage of subqueries involves the use of operators to allow a Where condition to include
the Select output of a subquery. First, list the buyers who purchased an expensive item (the Price of the
item is $100 greater than the average price of all items purchased):

SELECT BUYERID
FROM ANTIQUES
WHERE PRICE >

(SELECT AVG(PRICE) + 100


FROM ANTIQUES);

The subquery calculates the average Price, plus $100, and using that figure, an OwnerID is printed for
every item costing over that figure. One could use DISTINCT BUYERID, to eliminate duplicates.

List the Last Names of those in the AntiqueOwners table, ONLY if they have bought an item:

SELECT OWNERLASTNAME
FROM ANTIQUEOWNERS
WHERE OWNERID IN

(SELECT DISTINCT BUYERID


FROM ANTIQUES);

The subquery returns a list of buyers, and the Last Name is printed for an Antique Owner if and only if the
Owner's ID appears in the subquery list (sometimes called a candidate list). Note: on some DBMS's,
equals can be used instead of IN, but for clarity's sake, since a set is returned from the subquery, IN is
the better choice.

For an Update example, we know that the gentleman who bought the bookcase has the wrong First
Name in the database...it should be John:

UPDATE ANTIQUEOWNERS
SET OWNERFIRSTNAME = 'John'
WHERE OWNERID =

(SELECT BUYERID
FROM ANTIQUES
WHERE ITEM = 'Bookcase');

First, the subquery finds the BuyerID for the person(s) who bought the Bookcase, then the outer query
updates his First Name.

Remember this rule about subqueries: when you have a subquery as part of a WHERE condition, the
Select clause in the subquery must have columns that match in number and type to those in the Where
clause of the outer query. In other words, if you have "WHERE ColumnName = (SELECT...);", the
Select must have only one column in it, to match the ColumnName in the outer Where clause, and they
must match in type (both being integers, both being character strings, etc.).
EXISTS & ALL

EXISTS uses a subquery as a condition, where the condition is True if the subquery returns any rows,
and False if the subquery does not return any rows; this is a nonintuitive feature with few unique uses.
However, if a prospective customer wanted to see the list of Owners only if the shop dealt in Chairs, try:

SELECT OWNERFIRSTNAME, OWNERLASTNAME


FROM ANTIQUEOWNERS
WHERE EXISTS

(SELECT *
FROM ANTIQUES
WHERE ITEM = 'Chair');

If there are any Chairs in the Antiques column, the subquery would return a row or rows, making the
EXISTS clause true, causing SQL to list the Antique Owners. If there had been no Chairs, no rows would
have been returned by the outside query.

ALL is another unusual feature, as ALL queries can usually be done with different, and possibly simpler
methods; let's take a look at an example query:

SELECT BUYERID, ITEM


FROM ANTIQUES
WHERE PRICE >= ALL

(SELECT PRICE
FROM ANTIQUES);

This will return the largest priced item (or more than one item if there is a tie), and its buyer. The subquery
returns a list of all Prices in the Antiques table, and the outer query goes through each row of the
Antiques table, and if its Price is greater than or equal to every (or ALL) Prices in the list, it is listed, giving
the highest priced Item. The reason "=" must be used is that the highest priced item will be equal to the
highest price on the list, because this Item is in the Price list.

UNION & Outer Joins (briefly explained)

There are occasions where you might want to see the results of multiple queries together, combining their
output; use UNION. To merge the output of the following two queries, displaying the ID's of all Buyers,
plus all those who have an Order placed:

SELECT BUYERID
FROM ANTIQUES
UNION
SELECT OWNERID
FROM ORDERS;
Notice that SQL requires that the Select list (of columns) must match, column-by-column, in data type. In
this case BuyerID and OwnerID are of the same data type (integer). Also notice that SQL does automatic
duplicate elimination when using UNION (as if they were two "sets"); in single queries, you have to use
DISTINCT.

The outer join is used when a join query is "united" with the rows not included in the join, and are
especially useful if constant text "flags" are included. First, look at the query:

SELECT OWNERID, 'is in both Orders & Antiques'


FROM ORDERS, ANTIQUES
WHERE OWNERID = BUYERID
UNION
SELECT BUYERID, 'is in Antiques only'
FROM ANTIQUES
WHERE BUYERID NOT IN

(SELECT OWNERID
FROM ORDERS);

The first query does a join to list any owners who are in both tables, and putting a tag line after the ID
repeating the quote. The UNION merges this list with the next list. The second list is generated by first
listing those ID's not in the Orders table, thus generating a list of ID's excluded from the join query. Then,
each row in the Antiques table is scanned, and if the BuyerID is not in this exclusion list, it is listed with its
quoted tag. There might be an easier way to make this list, but it's difficult to generate the informational
quoted strings of text.

This concept is useful in situations where a primary key is related to a foreign key, but the foreign key
value for some primary keys is NULL. For example, in one table, the primary key is a salesperson, and in
another table is customers, with their salesperson listed in the same row. However, if a salesperson has
no customers, that person's name won't appear in the customer table. The outer join is used if the listing
of all salespersons is to be printed, listed with their customers, whether the salesperson has a customer
or not--that is, no customer is printed (a logical NULL value) if the salesperson has no customers, but is in
the salespersons table. Otherwise, the salesperson will be listed with each customer.

Another important related point about Nulls having to do with joins: the order of tables listed in the From
clause is very important. The rule states that SQL "adds" the second table to the first; the first table listed
has any rows where there is a null on the join column displayed; if the second table has a row with a null
on the join column, that row from the table listed second does not get joined, and thus included with the
first table's row data. This is another occasion (should you wish that data included in the result) where an
outer join is commonly used. The concept of nulls is important, and it may be worth your time to
investigate them further.

ENOUGH QUERIES!!! you say?...now on to something completely different...

- NaYaN -

SQL SYNTAX
Select SELECT "column_name" FROM "table_name"

Distinct SELECT DISTINCT "column_name" FROM "table_name"


Where SELECT "column_name" FROM "table_name" WHERE "condition"

And/Or SELECT "column_name" FROM "table_name" WHERE "simple condition" {[AND|OR] "simple
condition"}+

In SELECT "column_name" FROM "table_name" WHERE "column_name" IN ('value1', 'value2', ...)

Between SELECT "column_name" FROM "table_name" WHERE "column_name" BETWEEN 'value1' AND
'value2'

Like SELECT "column_name" FROM "table_name" WHERE "column_name" LIKE {PATTERN}

Order By SELECT "column_name" FROM "table_name" [WHERE "condition"] ORDER BY "column_name"


[ASC, DESC]

Count SELECT COUNT("column_name") FROM "table_name"

Group By SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY


"column_name1" - NaYaN -
Having SELECT "column_name1", SUM("column_name2") FROM "table_name" GROUP BY "column_name1"
HAVING (arithematic function condition)

Create Table CREATE TABLE "table_name" ("column 1" "data_type_for_column_1", "column 2"
"data_type_for_column_2", ... )

Drop Table DROP TABLE "table_name"

Truncate Table TRUNCATE TABLE "table_name"

Insert Into INSERT INTO "table_name" ("column1", "column2", ...) VALUES ("value1", "value2", ...)

Update UPDATE "table_name" SET "column_1" = [new value] WHERE {condition}

Delete From DELETE FROM "table_name" WHERE {condition} - NaYaN –

Scribd.com:
1 .
Display the dept information from department table.
select * from dept;
2 .
Display the details of all employees.
select * from emp;
3 .
Display the name and job for all employees.
select ename, job from emp;
4 .
Display name and salary for all employees.
select ename, sal from emp;
5 .
Display employee number and total salary for each employee.
select empno, sal+comm from emp;
6 .
Display employee name and annual salary for all employees.
select empno, empname, 12*sal+nvl(comm,0) annualsal from emp;
7 .
Display the names of all employees who are working in department
number 10.
select ename from emp where deptno=10;
8 .
Display the names of all employees working as clerks and drawing a
salary
more than 3000.
select ename from emp where job=’CLERK’ and sal>3000;
9 .
Display employee number and names for employees who earn
commission.
select empno, ename from emp where comm is not null and comm>0;
1 0 . Display names of employees who do not earn any commission.
Select empno, ename from emp where comm is null and comm=0;
1 1 . Display the names of employees who are working as clerk, salesman
or analyst
and drawing a salary more than 3000.
select ename from emp where (job=’CLERK’ or job=’SALESMAN’ or
job=’ANALYST’) and sal>3000;
(or)
select ename from emp where job in(‘CLERK’,’SALESMAN’,’ANALYST’)
and sal>3000;
1 2 . Display the names of employees who are working in the company
for the past
5 years.
select ename from emp where sysdate-hiredate>5*365;
1 3 . Display the list of employees who have joined the company before
30th June 90
or after 31st dec 90.
select * from emp where hiredate between ‘30-jun-1990’ and ‘31-dec-
1990’;
1 4 . Display current date.
select sysdate from dual;
1 5 . Display the list of users in your database (using log table).
select * from dba_users;
1 6 . Display the names of all tables from the current user.
select * from tab;
1 7 . Display the name of the current user.
show user;
1 8 . Display the names of employees working in department number 10 or 20
or 40
or employees working as clerks, salesman or analyst.
select ename from emp where deptno in (10,20,40) or job in
(‘CLERK’,’SALESMAN’,’ANALYST’);
1 9 . Display the names of employees whose name starts with alphabet S.
select ename from emp where ename like ‘S%’;
2 0 . Display employee names for employees whose name ends with alphabet.
select ename from emp where ename like ‘%S’;
2 1 . Display the names of employees whose names have second alphabet A in
their
names.
select ename from emp where ename like ‘_S%’;
2 2 . Display the names of employees whose name is exactly five characters in
length.
select ename from emp where length(ename)=5;
(or)
select ename from emp where ename like '_____';
2 3 . Display the names of employees who are not working as managers.
select * from emp minus (select * from emp where empno in (select
mgr from emp));
(or)
select * from emp where empno not in (select mgr from emp where
mgr is not null);
(or)
select * from emp e where empno not in (select mgr from emp where
e.empno=mgr)
2 4 . Display the names of employees who are not working as SALESMAN or
CLERK
or ANALYST.
select ename from emp where job not in
(‘CLERK’,’SALESMAN’,’ANALYST’);
2 5 . Display all rows from EMP table. The system should wait after every screen
full
of information.
set pause on;
2 6 . Display the total number of employees working in the company.
select count(*) from emp;
2 7 . Display the total salary being paid to all employees.
select sum(sal)+sum(nvl(comm,0)) from emp;
2 8 . Display the maximum salary from emp table.
select max(sal) from emp;

2 9 . Display the minimum salary from emp table.


select min(sal) from emp;
3 0 . Display the average salary from emp table.
select avg(sal) from emp;
3 1 . Display the maximum salary being paid to CLERK.
select max(sal) from emp where job=’CLERK’;
3 2 . Display the maximum salary being paid in dept no 20.
select max(sal) from emp where deptno=20;
3 3 . Display the min Sal being paid to any SALESMAN.
select min(sal) from emp where job=’SALESMAN’;
3 4 . Display the average salary drawn by managers.
select avg(sal) from emp where job=’MANAGER’;
3 5 . Display the total salary drawn by analyst working in dept no 40.
select sum(sal)+sum(nvl(comm,0)) from emp where deptno=40;
3 6 . Display the names of employees in order of salary i.e. the name of the
employee earning lowest salary should appear first.
select ename from emp order by sal;
3 7 . Display the names of employees in descending order of salary.
select ename from emp order by sal desc;
3 8 . Display the details from emp table in order of emp name.
select ename from emp order by ename;
3 9 . Display empno, ename, deptno, and sal. Sort the output first based on
name
and within name by deptno and within deptno by Sal;
select * from emp order by ename,deptno,sal;
4 0 . Display the name of the employee along with their annual salary (Sal * 12).
The name of the employee earning highest annual salary should appear first.
select ename, 12*(sal+nvl(comm,0)) Annual from emp order by
12*(sal+nvl(comm,0)) desc;
4 1 . Display name, Sal, hra, pf, da, total Sal for each employee. The output
should
be in the order of total Sal, hra 15% of Sal, da 10% of sal, pf 5% of sal total
salary will be (sal*hra*da)-pf.
select ename,sal,sal*15/100 HRA, sal*5/100 PF, sal*10/100
DA,sal+sal*15/100-sal*5/100+sal*10/100 TOTAL_SALARY from emp
42. Display dept numbers and total number of employees within each group.
select deptno,count(*) from emp group by deptno;
4 3 . Display the various jobs and total number of employees with each job
group.
select job, count(*) from emp group by job;
4 4 . Display department numbers and total salary for each department.

select deptno, sum(sal) from emp group by deptno;


4 5 . Display department numbers and maximum salary for each department.

select deptno, max(sal),min(sal) from emp group by deptno;

4 6 . Display the various jobs and total salary for each job.

select job, sum(sal) from emp group by job;

4 7 . Display each job along with minimum sal being paid in each job group.

select job, min(sal) from emp group by job;

4 8 . Display the department numbers with more than three employees in each
dept.

select deptno, count(*) from emp group by deptno having count(*)>3;

4 9 . Display the various jobs along with total sal for each of the jobs where total
sal

is greater than 40000.

select job, sum(sal) from emp group by job having sum(sal)>40000;

5 0 . Display the various jobs along with total number of employees in each job.
The

output should contain only those jobs with more than three employees.

select job, count(*) from emp group by job having count(*)>3;

5 1 . Display the name of emp who earns highest sal.

select ename from emp where sal=(select max(sal) from emp);


5 2 . Display the employee number and name of employee working as CLERK
and

earning highest salary among CLERKS.

select empno, ename from emp where job='CLERK' and sal=(select

max(sal) from emp where job='CLERK');

5 3 . Display the names of the salesman who earns a salary more than the
highest

salary of any clerk.

select ename from emp where job=’SALESMAN’ and sal >

(select max(sal) from emp where job='CLERK');

5 4 . Display the names of clerks who earn salary more than that of James of
that of

sal lesser than that of Scott.

select ename from emp where job='CLERK' and sal<(select sal from

emp where ename='SCOTT') and sal>(select sal from emp where

ename='JAMES');

5 5 . Display the names of employees who earn a Sal more than that of James
or

that of salary greater than that of Scott.

select ename from emp where sal <

(select sal from emp where ename='SCOTT') and sal >

(select sal from emp where ename='JAMES');

5 6 . Display the names of the employees who earn highest salary in their
respective

departments.

select * from emp e where sal =

(select max(sal) from emp where deptno=e.deptno)

5 7 . Display the names of employees who earn highest salaries in their


respective
job groups.

select * from emp e where sal in

(select max(sal) from emp group by job having e.job=job)

5 8 . Display the employee names who are working in accountings dept.

select ename from emp where deptno =

(select deptno from dept where dname=”ACCOUNTING”);

(or)

select ename from emp where deptno in (select deptno from dept

where dname=”ACCOUNTING”);

5 9 . Display the employee names who are working in Chicago.

select ename from emp where deptno =

(select deptno from dept where loc=’CHICAGO’);

6 0 . Display the job groups having total salary greater then the maximum salary
for

managers.

select job, sum(sal) from emp group by job having sum(sal) >

(select max(sal) from emp where job='MANAGER');

6 1 . Display the names of employees from department number 10 with salary

greater than that of any employee working in other departments.

select ename,sal,deptno from emp e where deptno=10 and sal >

any(select sal from emp where e.deptno!=deptno);

6 2 . Display the names of employee from department number 10 with salary

greater then that of all employee working in other departments.

select ename, sal, deptno from emp e where deptno=10 and sal >

any(select sal from emp where e.deptno != deptno);

6 3 . Display the names of employees in Upper case.

select upper(ename) from emp;


6 4 . Display the names of employees in lower case.

select lower(ename) from emp;

6 5 . Display the name of employees in proper case.

select initcap(ename) from emp;

6 6 . Find out the length of your name using appropriate function.

select length(‘India’) from dual;

6 7 . Display the length of all employees’ names.

select sum(length(ename)) from emp;

6 8 . Display the name of the employee concatenate with EMP no.

select ename||empno from emp;

(or)

select concat(ename,empno) from emp;

6 9 . Use appropriate function and extract 3 characters starting from 2 characters

from the following string ‘Oracle’ i.e. the output should be ‘rac’.

select substr(‘oracle’,2,3) from dual;

7 0 . Find the first occurrence of character a from the following string ‘computer
maintenance corporation’.
select instr(‘computer maintenance corporation’,’a’,1,1) from dual;
7 1 . Replace every occurrence of alphabet A with B in the string Allen’s (user
translate function).
select replace('Allens','A','b') from dual;
7 2 . Display the information from EMP table. Wherever job ‘manager’ is found it
should be displayed as boss(replace function).
select empno, ename, replace(job, 'MANAGER', 'Boss') JOB from emp;
7 3 . Display empno, ename, deptno from EMP table. Instead of display
department
numbers display the related department name (use decode function).
select e.empno, e.ename, d.dname from emp e,dept d where
e.deptno = d.deptno;
7 4 . Display your age in days.
select round(sysdate-to_date('15-aug-1947')) from dual;
7 5 . Display your age in months.
select floor(months_between(sysdate,'15-aug-1947'))
"age in months" from dual;
7 6 . Display current date as 15th august Friday nineteen forty seven.
select to_char(sysdate,'ddth month day year') from dual;
7 7 . Display the following output for each row from EMP table as ‘scott has joined
the company on Wednesday 13th august nineteen ninety’.
select ename||' has joined the company on '||to_char(hiredate,'day
ddth month year') from emp;
7 8 . Find the date of nearest Saturday after current day.
select next_day(sysdate, 'SATURDAY') from dual;
7 9 . Display current time.
select to_char(sysdate,'hh:mi:ss') Time from dual;
8 0 . Display the date three months before the current date.
select add_months(sysdate,-3) from dual;
8 1 . Display the common jobs from department number 10 and 20.
select job from emp where deptno=10 and job in(select job from emp
where deptno=20);
(or)
select job from emp where deptno=10 intersect select job from emp
where deptno=20;
8 2 . Display the jobs found in department number 10 and 20 eliminate duplicate
jobs.
select distinct(job) from emp where deptno=10 and job in(select job
from emp where deptno=20);
(or)

select job from emp where deptno=10 intersect select job from emp
where deptno=20;

8 3 . Display the jobs which are unique to dept no 10.

select job from emp where deptno=10 minus select job from emp

where deptno!=10;

(or)

select job from emp where deptno = 10 and job not in (select job from

emp where deptno<>10);

8 4 . Display the details of those who do not have any person working under
them.

select empno from emp where empno not in (select mgr from emp

where mgr is not null);

8 5 . Display the details of employees who are in sales dept and grade is 3.

select * from emp where sal>=(select losal from salgrade where

grade=3) and sal<=(select hisal from salgrade where grade=3) and

deptno=(select deptno from dept where dname='SALES');


8 6 . Display those who are not managers and who are managers any one.

select * from emp where empno in(select mgr from emp) union

select * from emp where empno not in(select mgr from emp where

mgr is not null);

8 7 . Display those employees whose name contains not less than 4 chars.

Select * from emp where length(ename)>4;

8 8 . Display those departments whose name start with ‘S’ while location name
end

with ‘O’.

select * from dept where dname like 'S%' and loc like '%O';

8 9 . Display those employees whose manager name is JONES.

select * from emp where mgr=(select empno from emp where

ename='JONES');

9 0 . Display those employees whose salary is more than 3000 after giving 20%

increment.

select * from emp where sal*120/100 > 3000;

(or)

select * from emp where sal+sal*20/100 > 3000;

9 1 . Display all employees with there dept name.

select ename, dname from emp e, dept d where e.deptno = d.deptno;

9 2 . Display ename who are working in sales dept.

select empno, ename from emp where

deptno=(select deptno from dept where dname='SALES');

9 3 . Display employee name, deptname, salary and comm. for those Sal in
between

2000 to 5000 while location is Chicago.

select empno,ename,deptno from emp where deptno=(select deptno


from dept where loc='CHICAGO') and sal between 2000 and 5000;

9 4 . Display those employees whose salary greater than his manager salary.
select * from emp e where sal>(select sal from emp where

empno=e.mgr);

9 5 . Display those employees who are working in the same dept where his
manager

is working.

select * from emp e where

deptno = (select deptno from emp where empno=e.mgr);

9 6 . Display those employees who are not working under any manger.

select * from emp where mgr is null or empno=mgr;

9 7 . Display grade and employees name for the dept no 10 or 30 but grade is
not 4,

while joined the company before 31-dec-82.

select empno,ename,sal,deptno,hiredate,grade from emp e,salgrade s

where e.sal>=s.losal and e.sal<=s.hisal and deptno in(10,30) and

grade<>4 and hiredate<'01-dec-1981';

9 8 . Update the salary of each employee by 10% increments that are not eligible
for

commission.

update emp set sal=sal+(sal*10/100) where comm is null;

9 9 . Delete those employees who joined the company before 31-dec-82 while
there

dept location is ‘NEW YORK’ or ‘CHICAGO’.

delete from emp where hiredate<'31-dec-1982' and deptno in

(select deptno from dept where loc in('NEW YORK','CHICAGO'));

1 0 0 . Display employee name, job, deptname, location for all who are working
as

managers.
select ename,job,dname,loc from emp e, dept d where

e.deptno=d.deptno and empno in (select mgr from emp);

1 0 1 . Display those employees whose manager names is Jones, and also


display

there manager name.

select e.empno, e.ename, m.ename MANAGER from emp e, emp m

where e.mgr=m.empno and m.ename='JONES';

1 0 2 . Display name and salary of ford if his Sal is equal to high Sal of his grade.

select ename,sal from emp e where ename='FORD' and sal=(select

hisal from salgrade where grade=(select grade from salgrade where

e.sal>=losal and e.sal<=hisal));

1 0 3 . Display employee name, his job, his dept name, his manager name, his
grade

and make out of an under department wise.

break on deptno;

select d.deptno, e.ename, e.job, d.dname, m.ename, s.grade from

emp e, emp m, dept d, salgrade s where e.deptno=d.deptno and e.sal

between s.losal and s.hisal and e.mgr=m.empno order by e.deptno;

1 0 4 . List out all the employees name, job, and salary grade and department
name

for every one in the company except ‘CLERK’. Sort on salary display the

highest salary.

select empno, ename, sal, dname, grade from emp e, dept d, salgrade s
where e.deptno=d.deptno and e.sal between s.losal and s.hisal and
e.job<>'CLERK' order by sal;
1 0 5 . Display employee name, his job and his manager. Display also
employees who
are without manager.
select e.ename, e.job, m.ename Manager from emp e,emp m where
e.mgr=m.empno union select ename,job,'no manager' from emp where
mgr is null;
1 0 6 . Find out the top 5 earner of company.
select * from emp e where 5>(select count(*) from emp where
sal>e.sal) order by sal desc;
1 0 7 . Display the name of those employees who are getting highest salary.
select empno,ename,sal from emp where sal=(select max(sal) from
emp);
1 0 8 . Display those employees whose salary is equal to average of maximum
and
minimum.
select * from emp where sal=(select (max(sal)+min(sal))/2 from
emp);
1 0 9 . Display count of employees in each department where count greater
than 3.
select deptno, count(*) from emp group by deptno having count(*)>3;
1 1 0 . Display dname where at least 3 are working and display only dname.
select dname from dept where deptno in
(select deptno from emp group by deptno having count(*)>3);
1 1 1 . Display name of those managers name whose salary is more than
average
salary of company.
select ename, sal from emp where empno in(select mgr from emp) and
sal > (select avg(sal) from emp);
1 1 2 . Display those managers name whose salary is more than an average
salary of
his employees.
select ename, sal from emp e where empno in(select mgr from emp)
and e.sal>(select avg(sal) from emp where mgr=e.empno);
1 1 3 . Display employee name, Sal, comm and net pay for those employees
whose
net pay are greater than or equal to any other employee salary of the
company?
select ename, sal, comm, sal+nvl(comm,0) netPay from emp where
sal+nvl(comm.,0)>=any(select sal from emp);
1 1 4 . Display those employees whose salary is less than his manager but
more than
salary of any other managers.
select * from emp e where sal<(select sal from emp where empno =
e.mgr) and sal>any(select sal from emp where empno!=e.mgr);
1 1 5 . Display all employees names with total Sal of company with employee
name.

Select ename,
1 1 6 . Find out the last 5(least) earner of the company?

select * from emp e where 5>(select count(*) from emp where

sal<e.sal) order by sal;

1 1 7 . Find out the number of employees whose salary is greater than there
manager
salary?

select count(*) from emp e where sal>(select sal from emp where

empno=e.mgr);

1 1 8 . Display those manager who are not working under president but they
are

working under any other manager?

select * from emp e where mgr in(select empno from emp where

ename<>'KING');

1 1 9 . Delete those department where no employee working?

delete from dept d where 0=(select count(*) from emp where

deptno=d.deptno);

1 2 0 . Delete those records from EMP table whose deptno not available in dept
table?

delete from emp where deptno not in(select deptno from dept);

1 2 1 . Display those earners whose salary is out of the grade available in Sal
grade

table?

select * from emp where sal<(select min(losal) from salgrade) or

sal>(select max(hisal) from salgrade);

1 2 2 . Display employee name, Sal, comm. and whose net pay is greater than
any

other in the company?

Select ename, sal, comm from emp where sal+sal*15/100-sal*5/100

+sal*10/100 = (select max(sal+sal*15/100-sal*5/100+sal*10/100)

from emp);

1 2 3 . Display name of those employees who are going to retire 31-dec-99. If


the

maximum job is period is 18 years?


select * from emp where (to_date('31-dec-1999')-hiredate)/365>18;

1 2 4 . Display those employees whose salary is ODD value?

select * from emp where mod(sal,2)=1;

1 2 5 . Display those employees whose salary contains at least 4 digits?

select * from emp where length(sal)>=4;

1 2 6 . Display those employees who joined in the company in the month of


DEC?

select * from emp where upper(to_char(hiredate,'mon'))='DEC';

1 2 7 . Display those employees whose name contains “A”?

select * from emp where instr(ename,'A',1,1)>0;

128. Display those employees whose deptno is available in salary?

select * from emp where instr(sal,deptno,1,1)>0;

1 2 9 . Display those employees whose first 2 characters from hire date-last


2
characters of salary?

select substr(hiredate,0,2)||substr(sal,length(sal)-1,2) from emp;

select concat( substr(hiredate,0,2), substr(sal,length(sal)-1,2) ) from

emp;

1 3 0 . Display those employees whose 10% of salary is equal to the year of


joining?

select * from emp where to_char(hiredate,'yy')=sal*10/100;

1 3 1 . Display those employees who are working in sales or research?

select * from emp where deptno in(select deptno from dept where

dname in('SALES','RESEARCH'));

1 3 2 . Display the grade of Jones?

select grade from salgrade where losal<=(select(sal) from emp where

ename='JONES') and hisal>=(select(sal) from emp where

ename='JONES');
1 3 3 . Display those employees who joined the company before 15th of the
month?

select empno,ename from emp where hiredate<(to_date('15-'||

to_char(hiredate,'mon')||'-'||to_char(hiredate,'yyyy')));

1 3 4 . Delete those records where no of employee in a particular department is


less

than 3?

delete from emp where deptno in(select deptno from emp group by

deptno having count(*)>3);

1 3 5 . Delete those employees who joined the company 21 years back from
today?

select * from emp where round((sysdate-hiredate)/365)>21;o r

select * from emp where (to_char (sysdate, 'yyyy')-to_char

(hiredate ,'yyyy') )>21;

1 3 6 . Display the department name the no of characters of which is equal to


no of

employees in any other department?

Select dname from dept where length(dname) in (select count(*) from

emp group by deptno);

1 3 7 . Display those employees who are working as manager?

select * from emp where empno in(select mgr from emp);

1 3 8 . Count the no of employees who are working as manager (use set


operation)?

select count(*) from emp where empno in(select mgr from emp);

1 3 9 . Display the name of then dept those employees who joined the company
on

the same date?

select empno,ename,hiredate,deptno from emp e where hiredate in

(select hiredate from emp where empno<>e.empno);


1 4 0 . Display those employees whose grade is equal to any number of Sal but
not

equal to first number of Sal?

141. Display the manager who is having maximum number of employees


working
under him?
Select mgr from emp group by mgr having count(*)=(select
max(count(mgr)) from emp group by mgr);
142. List out employees name and salary increased by 15% and expressed as
whole
number of dollars?
select empno,ename,lpad(concat('$',round(sal*115/100)),7) salary
from emp;
1 4 3 . Produce the output of the EMP table “EMPLOYEE_AND_JOB” for ename
and job?
select * from EMPLOYEE_AND_JOB;
1 4 4 . List all employees with hire date in the format ‘June 4 1988’?
select to_char(hiredate,'month ddy y y y') from emp;
1 4 5 . Print a list of employees displaying ‘Less Salary’ if less than 1500 if
exactly
1500 display as ‘Exact Salary’ and if greater than 1500 display ‘More Salary’?
select empno,ename,'Less Salary '||sal from emp where sal<1500
union
select empno,ename,'More Salary '||sal from emp where sal>1500
union
select empno,ename,'Exact Salary '||sal from emp where sal=1500
1 4 6 . Write query to calculate the length of employee has been with the
company?
Select round(sysdate-hiredate) from emp;
1 4 7 . Given a String of the format ‘nn/nn’ verify that the first and last 2
characters
are numbers. And that the middle characters is ‘y’ print the expressions ‘Yes’ if
valid ‘No’ of not valid use the following values to test your solution
1 4 8 . Employees hire on 15th of any month are paid on the last Friday of that
month.
Those hired after 15th are paid the last Friday of the following month. print a
list of employees their hire date and first pay date sort those whose Sal
contains first digits of their dept.
1 4 9 . Display those mangers who are getting less than his employees Sal.
Select empno from emp e where sal<any(select sal from emp where
mgr=e.empno);
1 5 0 . Print the details of all the employees who are sub ordinate to Blake.
Select * from emp where mgr=(select empno from emp where
ename='BLAKE');
1 5 1 . Display those who working as manager using co related sub query.
Select * from emp where empno in(select mgr from emp);
1 5 2 . Display those employees whose manger name is Jones and also with his
manager name.
Select * from emp where mgr=(select empno from emp where
ename='JONES') union select * from emp where empno=(select mgr
from emp where ename='JONES');

1 5 3 . Define variable representing the expressions used to calculate on


employee’s
total annual renumaration.

define emp_ann_sal=(sal+nvl(comm,0))*12;

1 5 4 . Use the variable in a statement which finds all employees who can earn
30,000

a year or more.

select * from emp where &emp_ann_sal>30000;

1 5 5 . Find out how many mangers are there with out listing them.

Select count (*) from EMP where empno in (select mgr from EMP);

1 5 6 . Find out the avg sal and avg total remuneration for each job type
remember

salesman earn commission.

select job,avg(sal+nvl(comm,0)),sum(sal+nvl(comm,0)) from emp

group by job;

1 5 7 . Check whether all employees number are indeed unique.

select count(empno),count(distinct(empno)) from emp having

count(empno)=(count(distinct(empno)));

1 5 8 . List out the lowest paid employees working for each manager, exclude
any

groups where min sal is less than 1000 sort the output by sal.

select e.ename,e.mgr,e.sal from emp e where sal in(select min(sal)

from emp where mgr=e.mgr) and e.sal>1000 order by sal;

1 5 9 . list ename, job, annual sal, deptno, dname and grade who earn 30000
per year

and who are not clerks.

Select e.ename, e.job, (e.sal+nvl(e.comm,0))*12, e.deptno, d.dname,


s.grade from emp e, salgrade s , dept d where e.sal between s.losal

and s.hisal and e.deptno=d.deptno and (e.sal+nvl(comm,0))*12>

30000 and e.job <> 'CLERK';

1 6 0 . find out the job that was failed in the first half of 1983 and the same job
that

was failed during the same period on 1984.

1 6 1 . find out the all employees who joined the company before their
manager.

Select * from emp e where hiredate<(select hiredate from emp where

empno=e.mgr);

1 6 2 . list out the all employees by name and number along with their
manager’s

name and number also display ‘No Manager’ who has no manager.

select e.empno,e.ename,m.empno Manager,m.ename ManagerName

from emp e,emp m where e.mgr=m.empno

union

select empno,ename,mgr,'No Manager' from emp where mgr is null;

1 6 3 . find out the employees who earned the highest Sal in each job typed
sort in

descending Sal order.

select * from emp e where sal =(select max(sal) from emp where

job=e.job);

1 6 4 . find out the employees who earned the min Sal for their job in ascending

order.

select * from emp e where sal =(select min(sal) from emp where
job=e.job) order by sal;

1 6 5 . find out the most recently hired employees in each dept order by hire date

select * from emp order by deptno,hiredate desc;


1 6 6 . display ename, sal and deptno for each employee who earn a Sal
greater than

the avg of their department order by deptno

select ename,sal,deptno from emp e where sal>(select avg(sal) from

emp where deptno=e.deptno) order by deptno;

1 6 7 . display the department where there are no employees

select deptno,dname from dept where deptno not in(select

distinct(deptno) from emp);

1 6 8 . display the dept no with highest annual remuneration bill as


compensation.

select deptno,sum(sal) from emp group by deptno having sum(sal) =

(select max(sum(sal)) from emp group by deptno);

1 6 9 . In which year did most people join the company. Display the year and
number

of employees

select count(*),to_char(hiredate,'yyyy') from emp group by

to_char(hiredate,'yyyy');

170. display avg sal figure for the dept

select deptno,avg(sal) from emp group by deptno;

1 7 1 . Write a query of display against the row of the most recently hired
employee.

display ename hire date and column max date showing.

select empno,hiredate from emp where hiredate=(select max

(hiredate) from emp);

1 7 2 . display employees who can earn more than lowest Sal in dept no 30

select * from emp where sal>(select min(sal) from emp where

deptno=30);

173. find employees who can earn more than every employees in dept no 30
select * from emp where sal>(select max(sal) from emp where

deptno=30);

select * from emp where sal>all(select sal from emp where

deptno=30);

1 7 4 . select dept name dept no and sum of Sal

break on deptno on dname;

select e.deptno,d.dname,sal from emp e, dept d where

e.deptno=d.deptno order by e.deptno;

175. find out avg sal and avg total remainders for each job type

176. find all dept’s which have more than 3 employees

select deptno from emp group by deptno having count(*)>3;

1 7 7 . If the pay day is next Friday after 15th and 30th of every month. What is
the
next pay day from their hire date for employee in emp table
1 7 8 . If an employee is taken by you today in your organization. And is a policy
in
your company to have a review after 9 months the joined date (and of 1st of
next month after 9 months) how many days from today your employee has to
wait for a review
179. Display employee name and his sal whose sal is greater than highest avg of
dept no
1 8 0 . Display the 10th record of EMP table. (without using rowid)
181. Display the half of the enames in upper case and remaining lower case
select concat ( upper ( substr ( ename, 0 , length (ename)/ 2) ),
lower (substr (ename, length(ename) / 2+1, length(ename) )) ) from
emp;
1 8 2 . display the 10th record of emp table without using group by and rowed
1 8 3 . Delete the 10th record of emp table.
1 8 4 . Create a copy of emp table.
Create table emp1 as select * from emp;
1 8 5 . Select ename if ename exists more than once.
select distinct(ename) from emp e where ename in(select ename from
emp where e.empno<>empno);
1 8 6 . display all enames in reverse order.
select ename from emp order by ename desc;
1 8 7 . Display those employee whose joining of month and grade is equal.
select empno,ename from emp e, salgrade s where e.sal between
s.losal and s.hisal and to_char(hiredate,'mm')=grade;
1 8 8 . Display those employee whose joining date is available in dept no
select * from emp where to_char(hiredate,'dd')=deptno;
189. Display those employees name as follows A ALLEN, B BLAKE
select substr(ename,1,1)||' '||ename from emp;
190. List out the employees ename, sal, PF from emp
Select ename,sal,sal*15/100 PF from emp;
191. Display RSPS from emp without using updating, inserting
192. Create table emp with only one column empno
Create table emp (empno number(5));
1 9 3 . Add this column to emp table ename Varchar(20).
alter table emp add ename varchar2(20) not null;

1 9 4 . OOPS! I forgot to give the primary key constraint. Add it now.


alter table emp add constraint emp_empno primary key (empno);

1 9 5 . Now increase the length of ename column to 30 characters.

alter table emp modify ename varchar2(30);

1 9 6 . Add salary column to emp table.

alter table emp add sal number(7,2);

1 9 7 . I want to give a validation saying that sal cannot be greater 10,000(note


give a

name to this column).

alter table emp add constraint emp_sal_check check (sal<10000);

1 9 8 . For the time being I have decided that I will not impose this validation. My

boss has agreed to pay more than 10,000.

Alter table emp disable constraint emp_sal_check;

199. My boss has changed his mind. Now he doesn’t want to pay more than

10,000. So revoke that salary constraint

Alter table emp enable constraint emp_sal_check;

200. Add column called as mgr to your emp table.

Alter table emp add mgr number(5);

201. Oh! This column should be related to empno. Give a command to add this

constraint

Alter table emp add constraint emp_mgr foreign key(empno);

202. Add dept no column to your emp table


Alter table emp add deptno number(3);

203. This dept no column should be related to deptno column of dept table

Alter table emp1 add constraint emp1_deptno foreign key(deptno)

references dept(deptno);

204. Create table called as new emp. Using single command create this table as
well

as to get data into this table (use create table as)

create table newemp as select *from emp;

205. Create table called as newemp. This table should contain only
empno,ename,

dname

create table newemp as select empno,ename,dname from emp e , dept

d where e.deptno=d.deptno;

2 0 6 . Delete the rows of employees who are working in the company for more
than 2

years.

Delete from emp where floor(sysdate-hiredate)>2*365;

2 0 7 . Provide a commission to employees who are not earning any


commission.

update emp set comm=300 where comm is null;

2 0 8 . If any employee has commission his commission should be incremented


by

10% of his salary.

update emp set comm=comm*10/100 where comm is not null;

2 0 9 . Display employee name and department name for each employee.


select ename,dname from emp e, dept d where e.deptno=d.deptno;

2 1 0 . Display employee number, name and location of the department in


which he is

working.
Select empno, ename, loc from emp e, dept d where

e.deptno=d.deptno;

2 1 1 . Display ename, dname even if there no employees working in a


particular

department(use outer join).

Select ename, dname from emp e, dept d where e.deptno (+)=

d.deptno;

2 1 2 . Display employee name and his manager name.

Select e.ename, m.ename from emp e, emp m where e.mgr=m.empno;

2 1 3 . Display the department name along with total salary in each


department.

Select deptno, sum(sal) from emp group by deptno;

2 1 4 . Display the department name and total number of employees in each

department.

select deptno,count(*) from emp group by deptno;

215. Alter table emp1 add constraint emp1_deptno foreign key(deptno)


references

dept(deptno)

216. Delete from emp where job name is clerk

2 1 7 . Insert into emp without giving any further commands move to another
client

system and log into the same user give the following command

218. Are the above changes reflected in this user

2 1 9 . Go to your fist system and give commit come back to the second system
and

give the following command

220. Display the current date and time

select to_char(sysdate,'month mon dd yy yyyy hh:mi:ss') from dual;


SQL SELECT
SELECT "column_name" FROM "table_name"

To illustrate the above example, assume that we have the following table:
Table Sales Date
Store_Information
store_name

Los Angeles $1500 Jan-05-


1999

San Diego $250 Jan-07-


1999

Los Angeles $300 Jan-08-


1999

Boston $700 Jan-08-


1999

Wiziq.com-----66 qtns& ans

Scribd.com----235 qtns & ans

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy