Document
Document
Document
•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 :
•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 trigger restriction
•A trigger action
What are the various types of database triggers ?
Answer: There are 12 types of triggers, they are combination of :
•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 :
•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
•Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes
instead of another.
•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
1000 camera 20
1001 laptop 10
1002 desktop 15
Table truncated.
PID NUMBER(4)
QTY NUMBER(4)
no rows selected
Table dropped.
SQL> desc sample;
ERROR:
SQL> rollback;
Rollback complete.
ERROR:
DEPT TABLE
EMP TABLE
BONUS TABLE
SALGRADE TABLE
PRODUCTS TABLE
ORDERS TABLE
SKILLS TABLE
BIN$DOC2aYDTQCCTgp0Y3TsHRA==$0 TABLE
8 rows selected.
Table created.
PID NUMBER(4)
QTY NUMBER(4)
1000 camera 20
1001 laptop 10
1002 desktop 15
Table dropped.
ERROR:
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.
3. SELECT statements:
4. The SELECT INTO Statement is most often used to create backup copies of
tables or for archiving records.
9. The IN operator may be used if you know the exact value you want to return for
at least one of the columns.
When this clause is used with the DROP command, a parent table can be dropped even
when a child table exists.
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.
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.
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.
26. Which date function is used to find the difference between two dates?
MONTHS_BETWEEN.
LIKE operator.
28. What is the use of the DROP option in the ALTER TABLE command?
IS NULL operator.
30. What are the privileges that can be granted on a table by a user to others?
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?
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?
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.
38. What is the parameter substitution symbol used with INSERT INTO command?
&
Sub-query is a query whose return values are used in filtering conditions of the main query.
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.
Using ROWID.
CONSTRAINTS
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.
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.
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.
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.
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.
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.
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.
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
The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which
trigger information will you add?
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
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.
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.
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;
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
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;
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:
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;
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.
What are steps required tuning this query to improve its performance?
-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;
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.
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.
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.
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
Simple Queries:
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:
10. List out the employees who are earning salary between 3000 and 4500
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.
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.
29. How many employees who are joined in January or September month.
33. Which is the department id, having greater than or equal to 3 employees joined in April
1985.
Sub-Queries
39. Update the employees salaries, who are working as Clerk on the basis of 10%.
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.
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
Self Join:
Outer Join:
Set Operators:
6. SQL > Select employee_id “id of the employee”, last_name “name", department id as
“department id” from employee;
10. SQL > Select * from employee where salary between 3000 and 4500
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
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
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
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
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:
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
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)
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.
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;
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 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;
SELECT EMPLOYEEIDNO
FROM EMPLOYEESTATISTICSTABLE
WHERE SALARY NOT BETWEEN 30000 AND 50000;
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.
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.
AntiqueOwners
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
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:
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:
As the column names are different in each table, however, this wasn't necessary.
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:
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.
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 ITEM
FROM ANTIQUES);
This gives:
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.
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:
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.
All tables within a database must be created at some point in time...let's see how we would create the
Orders table:
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:
• 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.
• 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):
The data for this new column can be updated or inserted as shown later.
Adding Data
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:
Deleting Data
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:
Updating Data
Let's update a Price into a row that doesn't have a price listed yet:
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:
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:
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:
Now, say we only want to see the maximum purchase price if the purchase is over $1000, so we use the
HAVING clause:
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 >
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
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 *
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 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.
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
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.
- NaYaN -
SQL SYNTAX
Select SELECT "column_name" FROM "table_name"
And/Or SELECT "column_name" FROM "table_name" WHERE "simple condition" {[AND|OR] "simple
condition"}+
Between SELECT "column_name" FROM "table_name" WHERE "column_name" BETWEEN 'value1' AND
'value2'
Create Table CREATE TABLE "table_name" ("column 1" "data_type_for_column_1", "column 2"
"data_type_for_column_2", ... )
Insert Into INSERT INTO "table_name" ("column1", "column2", ...) VALUES ("value1", "value2", ...)
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;
4 6 . Display the various jobs and total salary for each job.
4 7 . Display each job along with minimum sal being paid in each job group.
4 8 . Display the department numbers with more than three employees in each
dept.
4 9 . Display the various jobs along with total sal for each of the jobs where total
sal
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.
5 3 . Display the names of the salesman who earns a salary more than the
highest
5 4 . Display the names of clerks who earn salary more than that of James of
that of
select ename from emp where job='CLERK' and sal<(select sal from
ename='JAMES');
5 5 . Display the names of employees who earn a Sal more than that of James
or
5 6 . Display the names of the employees who earn highest salary in their
respective
departments.
(or)
select ename from emp where deptno in (select deptno from dept
where dname=”ACCOUNTING”);
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 ename, sal, deptno from emp e where deptno=10 and sal >
(or)
from the following string ‘Oracle’ i.e. the output should be ‘rac’.
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;
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
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
8 5 . Display the details of employees who are in sales dept and grade is 3.
select * from emp where empno in(select mgr from emp) union
select * from emp where empno not in(select mgr from emp where
8 7 . Display those employees whose name contains not less than 4 chars.
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';
ename='JONES');
9 0 . Display those employees whose salary is more than 3000 after giving 20%
increment.
(or)
9 3 . Display employee name, deptname, salary and comm. for those Sal in
between
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.
9 6 . Display those employees who are not working under any manger.
9 7 . Display grade and employees name for the dept no 10 or 30 but grade is
not 4,
9 8 . Update the salary of each employee by 10% increments that are not eligible
for
commission.
9 9 . Delete those employees who joined the company before 31-dec-82 while
there
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
1 0 2 . Display name and salary of ford if his Sal is equal to high Sal of his grade.
1 0 3 . Display employee name, his job, his dept name, his manager name, his
grade
break on 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?
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
select * from emp e where mgr in(select empno from emp where
ename<>'KING');
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?
1 2 2 . Display employee name, Sal, comm. and whose net pay is greater than
any
from emp);
emp;
select * from emp where deptno in(select deptno from dept where
dname in('SALES','RESEARCH'));
ename='JONES');
1 3 3 . Display those employees who joined the company before 15th of the
month?
to_char(hiredate,'mon')||'-'||to_char(hiredate,'yyyy')));
than 3?
delete from emp where deptno in(select deptno from emp group by
1 3 5 . Delete those employees who joined the company 21 years back from
today?
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
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.
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
group by job;
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.
1 5 9 . list ename, job, annual sal, deptno, dname and grade who earn 30000
per year
1 6 0 . find out the job that was failed in the first half of 1983 and the same job
that
1 6 1 . find out the all employees who joined the company before their
manager.
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.
union
1 6 3 . find out the employees who earned the highest Sal in each job typed
sort in
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
1 6 9 . In which year did most people join the company. Display the year and
number
of employees
to_char(hiredate,'yyyy');
1 7 1 . Write a query of display against the row of the most recently hired
employee.
1 7 2 . display employees who can earn more than lowest Sal in dept no 30
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);
deptno=30);
175. find out avg sal and avg total remainders for each job type
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 8 . For the time being I have decided that I will not impose this validation. My
199. My boss has changed his mind. Now he doesn’t want to pay more than
201. Oh! This column should be related to empno. Give a command to add this
constraint
203. This dept no column should be related to deptno column of dept table
references dept(deptno);
204. Create table called as new emp. Using single command create this table as
well
205. Create table called as newemp. This table should contain only
empno,ename,
dname
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.
working.
Select empno, ename, loc from emp e, dept d where
e.deptno=d.deptno;
d.deptno;
department.
dept(deptno)
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
2 1 9 . Go to your fist system and give commit come back to the second system
and
To illustrate the above example, assume that we have the following table:
Table Sales Date
Store_Information
store_name