0% found this document useful (0 votes)
12 views59 pages

OOAD, General Interview Questions.: 1 By: Vishal Pachpute. Mob: 9960972016

Uploaded by

Mandar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views59 pages

OOAD, General Interview Questions.: 1 By: Vishal Pachpute. Mob: 9960972016

Uploaded by

Mandar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Java

OOAD, General Interview Questions.

1 By: Vishal Pachpute. Mob: 9960972016


What is Inheritance ?

The process of obtaining the data members and methods from one class to another class is known
as inheritance. It is one of the fundamental features of object-oriented programming.

What are advantage of Inheritance ?

If we develop any application using concept of Inheritance than that application have following
advantages,

 Application development time is less.


 Application take less memory.
 Application execution time is less.
 Application performance is enhance (improved).
 Redundancy (repetition) of the code is reduced or minimized so that we get consistence results
and less storage cost.

Why use Inheritance ?

 For Method Overriding (used for Runtime Polymorphism).


 It's main uses are to enable polymorphism and to be able to reuse code for different classes by
putting it in a common super class
 For code Re-usability

You can decrease scope of access modifier in inheritance ?

No, In Inheritance the scope of access modifier increasing is allow but decreasing is not allow.
Suppose in parent class method access modifier is default then it's present in child class with
default or public or protected access modifier but not private(it decreased scope).

How many type of inheritance are allow in java ?

In Java following inheritance are allow;

 Single inheritance
 Multilevel inheritance
 Hierarchical inheritance
 Hybrid inheritance

Which inheritance is not supported by Java ?

Multiple Inheritance, are not supported by java.

Why multiple inheritance is not supported in java?

Due to ambiguity problem java does not support multiple inheritance at class level.

How to achieve multiple inheritance in java ?

Java can not support multiple inheritance at class level but you can achieve multiple inheritance
in java by using Interface concept.

2 By: Vishal Pachpute. Mob: 9960972016


Difference between import and package ?

 Package keyword is always used for creating the undefined package and placing common classes
and interfaces.
 import is a keyword which is used for referring or using the classes and interfaces of a specific
package.

Give real life example of Inheritance ?

The real life example of inheritance is child and parents, all the properties of father are inherited
by his son.

What is Difference between Class and Object ?


Class Object

Class is a container which collection of


1 object is a instance of class
variables and methods.

No memory is allocated at the time of Sufficient memory space will be allocated for all the
2
declaration variables of class at the time of declaration.

One class definition should exist only


3 For one class multiple objects can be created.
once in the program.

Give real life example of class and object.

In real world many examples of object and class like dog, cat, and cow are belong to animal's
class. Each object has state and behaviors. For example a dog has state:- color, name, height, age
as well as behaviors:- barking, eating, and sleeping.

Interface
What is interface ?

Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.

Why use interface in java ?

In java interface are used for achieve multiple inheriatance.

Can an Interface extend another Interface?

Yes an Interface can inherit another Interface.

How interface is similar to class ?

Whenever we compile any Interface program it generate .class file. That means the bytecode of
an interface appears in a .class file.

3 By: Vishal Pachpute. Mob: 9960972016


How interface is different from class ?

 we cannot instantiate an interface.


 An interface does not contain any constructors.
 All methods in an interface are abstract.
 An interface cannot contain instance fields. Interface only contains public static final variables.
 An interface is can not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces. That means interface support multiple inheritance

Why interface have no constructor ?

Because, constructor are used for eliminate the default values by user defined values, but in case
of interface all the data members are public static final that means all are constant so no need to
eliminate these values.

Other reason because constructor is like a method and it is concrete method and interface does
not have concrete method it have only abstract methods that's why interface have no constructor.

Why Method Overloading is not possible by changing the return type of method?

In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity.

Why Interface have no Constructor ?

Because, constructor are used for eliminate the default values by user defined values, but in case
of interface all the data members are public static final that means all are constant so no need to
eliminate these values.

Other reason because constructor is like a method and it is concrete method and interface does
not have concrete method it have only abstract methods that's why interface have no constructor.

Why not use abstract and final modifier together ?

In java, abstract and final both modifiers are not allowed for a class at a time the reason is
abstract and final are opposite keywords. If a class is an abstract, then that class must be
extended (inherited). If a class is final then that class can not be extended. So both keyword can
not be use at a time

Why use Abstract class ?

Abstract class are used for fulfill common requirement. If we use concrete classes for fulfill
common requirements than such application will get the following limitations.

 Application will take more amount of memory space (main memory).


 Application execution time is more.
 Application performance is decreased.

To overcome above limitation you can use abstract class.

4 By: Vishal Pachpute. Mob: 9960972016


Difference between abstract class and concrete class ?
Concrete class Abstract class

Abstract class are used for fulfill common


Concrete class are used for specific requirement
requirement.

Object of abstract class can not be create directly


Object of concrete class can be create directly.
(can create indirectly).

Concrete class containing fully defined methods or Abstract class have both undefined method and
implemented method. defined method.

Difference between Abstraction and Encapsulation ?

Encapsulation is not provides fully security because we can access private member of the class
using reflation API, but in case of Abstraction we can't access static, abstract data member of
class.

Difference between Abstract and Interface ?


Abstract Interface

It is collection of abstract method and concrete


1 It is collection of abstract method.
methods.

There properties can be reused commonly in a There properties commonly usable in any
2
specific application. application of java environment.

3 It does not support multiple inheritance. It support multiple inheritance.

4 Abstract class is preceded by abstract keyword. It is preceded by Interface keyword.

5 Which may contain either variable or constants. Which should contains only constants.

The default access specifier of abstract class There default access specifier of interface method
6
methods are default. are public.

These class properties can be reused in other These properties can be reused in any other class
7
class using extend keyword. using implements keyword.

8 Inside abstract class we can take constructor. Inside interface we can not take any constructor.

For the abstract class there is no restriction like For the interface it should be compulsory to
9 initialization of variable at the time of variable initialization of variable at the time of variable
declaration. declaration.

Inside interface we can take instance and static Inside interface we can not take instance and static
10
block. block.

5 By: Vishal Pachpute. Mob: 9960972016


There are no any restriction for abstract class For the interface variable can not declare variable
11
variable. as private, protected, transient, volatile.

There are no any restriction for abstract class For the interface method can not declare method as
12 method modifier that means we can use any strictfp, protected, static, native, private, final,
modifiers. synchronized.

Give Real life example of Abstraction

Abstraction shows only important things to the user and hides the internal details for example
when we ride a bike, we only know about how to ride bike but can not know about how it work ?
and also we do not know internal functionality of bike.

Give real life example of Encapsulation ?

The common example of encapsulation is capsule. In capsule all medicine are encapsulated in
side capsule.

Difference between Encapsulation and Abstraction

Encapsulation is not provides fully security because we can access private member of the class
using reflation API, but in case of Abstraction we can't access static, abstract data member of
class.

How to achieve Encapsulation in java

In java you can achieve Encapsulation by using class concept.

polymorphism
Give Real life example of polymorphism

Suppose if you are in class room that time you behave like a student, when you are in market at
that time you behave like a customer, when you at your home at that time you behave like a son
or daughter, Here one person present in different-different behaviors.

Difference between Overloading and Overriding ?


Overloading Overriding

Whenever same method or Constructor is existing Whenever same method name is existing
multiple times within a class either with different multiple time in both base and derived class
1 number of parameter or with different type of with same number of parameter or same type
parameter or with different order of parameter is of parameter or same order of parameters is
known as Overloading. known as Overriding.

Arguments of method must be different at least Argument of method must be same including
2
arguments. order.

3 Method signature must be different. Method signature must be same.

6 By: Vishal Pachpute. Mob: 9960972016


Private, static and final methods can not be
4 Private, static and final methods can be overloaded.
overrided.

Access modifiers point of view not reduced


5 Access modifiers point of view no restriction.
scope of Access modifiers but increased.

Also known as compile time polymorphism or static Also known as run time polymorphism or
6
polymorphism or early binding. dynamic polymorphism or late binding.

Overloading can be exhibited both are method and Overriding can be exhibited only at method
7
constructor level. leve.

The scope of Overriding is base class and


8 The scope of overloading is within the class.
derived class.

Overloading can be done at both static and non- Overriding can be done only at non-static
9
static methods. method.

For overloading methods return type may or may For overriding method return type should be
10
not be same. same.

General Interview Questions


1. What are different oops concept in java?

OOPs stands for Object Oriented Programming. The concepts in oops are similar to any other
programming languages.

2. What is polymorphism?

The ability to define a function in multiple forms is called Polymorphism. In java, c++ there are two types
of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

7 By: Vishal Pachpute. Mob: 9960972016


3. What is Method Overloading and Overriding

Overloading: Overloading is determined at the compile time. It occurs when several methods have
same names with:

 Different method signature and different number or type of parameters.


 Same method signature but different number of parameters.
 Same method signature and same number of parameters but of different type

Rules of Method Overloading

1) First and important rule to overload a method in java is to change method signature. Method
signature is made of number of arguments, type of arguments and order of arguments if they
are of different types.
2) Return type of method is never part of method signature, so only changing the return type of
method does not amount to method overloading.
3) Thrown exceptions from methods are also not considered when overloading a method. So your
overloaded method throws the same exception, a different exception or it simply does no throw
any exception; no effect at all on method loading.

Example of Overloading
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[])


{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

}
}
Output:30
40
******************************
Method overriding: Overriding occurs when a class method has the same name and signature as a
method in parent class. When you override methods, JVM determines the proper methods to call at the
program’s run time, not at the compile time.
If a class inherits a method from its super class, then there is a chance to override the method
provided that it is not marked final.
The benefit of overriding is: ability to define a behaviour that's specific to the subclass type
which means a subclass can implement a parent class method based on its requirement.

In object-oriented terms, overriding means to override the functionality of an existing method.

Example:
class Animal{

public void move(){


System.out.println("Animals can move");
}
}

class Dog extends Animal{


8 By: Vishal Pachpute. Mob: 9960972016
public void move(){
System.out.println("Dogs can walk and run");
}
}

public class TestDog{

public static void main(String args[])


{
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class

b.move();//Runs the method in Dog class


}
}
This would produce the following result:
Animals can move
Dogs can walk and run

In the above example, you can see that the even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In compile time, the check is made on the reference
type. However, in the runtime, JVM figures out the object type and would run the method that belongs
to that particular object.
Therefore, in the above example, the program will compile properly since Animal class has the
method move. Then, at the runtime, it runs the method specific for that object.

Rules for method overriding:


 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level. For
example: if the superclass method is declared public then the overridding method in the sub
class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public or
protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not. However the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw narrower or fewer exceptions than the overridden method.
 Constructors cannot be overridden.

9 By: Vishal Pachpute. Mob: 9960972016


4. What is inheritance?

Inheritance allows a Child class to inherit properties from its parent class. In Java this is achieved by
using extends keyword. Only properties with access modifier public and protected can be accessed in
child class.

public class Parent


{
public String parentName;
public String familyName;

protected void printMyName() {


System.out.println(“ My name is “+ chidName+” “ +familyName);
}
}
public class Child extends Parent
{
public String childName;
public int childAge;
//inheritance
protected void printMyName() {
System.out.println(“ My child name is “+ chidName+” “ +familyName);
}
}

In above example the child has inherit its family name from the parent class just by inheriting the class.
When child object is created printMyName() present in child class is called.

Inheritance can be defined as the process where one class acquires the properties (methods and fields)
of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).

Sample Code

Below given is an example demonstrating Java inheritance. In this example you can observe two classes
namely Calculation and My_Calculation.

Using extends keyword the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.

*****************

class Calculation
{
int z;

public void addition(int x, int y)


{
z = x+y;
System.out.println("The sum of the given numbers:"+z);
}

public void Substraction(int x,int y)


{
z = x-y;
System.out.println("The difference between the given numbers:"+z);
}
10 By: Vishal Pachpute. Mob: 9960972016
}

public class My_Calculation extends Calculation


{
public void multiplication(int x, int y){
z = x*y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]){


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b);
}

**********************

After executing the program it will produce the following result.

The sum of the given numbers:30


The difference between the given numbers:10
The product of the given numbers:200

In the given program when an object to My_Calculation class is created, a copy of the contents of the
super class is made with in it. That is why, using the object of the subclass you can access the members
of a super class.

The Superclass reference variable can hold the subclass object, but using that variable you can access
only the members of the superclass, so to access the members of both classes it is recommended to
always create reference variable to the subclass.

If you consider the above program you can instantiate the class as given below as well. But using the
superclass reference variable ( cal in this case ) you cannot call the method multiplication(), which
belongs to the subclass My_Calculation.

11 By: Vishal Pachpute. Mob: 9960972016


Calculation cal = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);

Note − A subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the
superclass can be invoked from the subclass.

The super keyword

The super keyword is similar to this keyword following are the scenarios where the super keyword is
used.

 It is used to differentiate the members of superclass from the members of subclass, if they have
same names.
 It is used to invoke the superclass constructor from subclass.

Sample Code

This section provides you a program that demonstrates the usage of the super keyword.

In the given program you have two classes namely Sub_class and Super_class, both have a method
named display() with different implementations, and a variable named num with different values. We
are invoking display() method of both classes and printing the value of the variable num of both classes,
here you can observe that we have used super key word to differentiate the members of super class
from sub class.

Copy and paste the program in a file with name Sub_class.java.

class Super_class
{

int num = 20;

//display method of superclass


public void display(){
System.out.println("This is the display method of superclass");
}

public class Sub_class extends Super_class


{

int num = 10;

//display method of sub class


public void display(){
System.out.println("This is the display method of subclass");
}

public void my_method()


{

//Instantiating subclass
Sub_class sub = new Sub_class();

//Invoking the display() method of sub class


sub.display();

12 By: Vishal Pachpute. Mob: 9960972016


//Invoking the display() method of superclass
super.display();

//printing the value of variable num of subclass


System.out.println("value of the variable named num in sub class:"+
sub.num);

//printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+
super.num);
}

public static void main(String args[]){


Sub_class obj = new Sub_class();
obj.my_method();

}
}

On executing the program you will get the following result −

This is the display method of subclass


This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

IS-A Relationship

IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used
to achieve inheritance.

public class Animal{


}

public class Mammal extends Animal{


}

public class Reptile extends Animal{


}

public class Dog extends Mammal{


}

Now, based on the above example, In Object Oriented terms, the following are true −

 Animal is the superclass of Mammal class.


 Animal is the superclass of Reptile class.
 Mammal and Reptile are subclasses of Animal class.
 Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say −

 Mammal IS-A Animal


 Reptile IS-A Animal
 Dog IS-A Mammal
 Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.

13 By: Vishal Pachpute. Mob: 9960972016


We can assure that Mammal is actually an Animal with the use of the instance operator.

Example
class Animal{
}

class Mammal extends Animal{


}

class Reptile extends Animal{


}

public class Dog extends Mammal{

public static void main(String args[]){

Animal a = new Animal();


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce the following result −

true
true
true

Since we have a good understanding of the extends keyword let us look into how the implements
keyword is used to get the IS-A relationship.

Generally, the implements keyword is used with classes to inherit the properties of an interface.
Interfaces can never be extended by a class.

Example
public interface Animal {
}

public class Mammal implements Animal{


}

public class Dog extends Mammal{


}

The instanceof Keyword

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog
is actually an Animal

interface Animal{}

class Mammal implements Animal{}

public class Dog extends Mammal{

public static void main(String args[]){

14 By: Vishal Pachpute. Mob: 9960972016


Mammal m = new Mammal();
Dog d = new Dog();

System.out.println(m instanceof Animal);


System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}

This would produce the following result:

true
true
true

Types of inheritance

There are various types of inheritance as demonstrated below.

A very important fact to remember is that Java does not support multiple inheritance. This means that a
class cannot extend more than one class. Therefore following is illegal −

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces. This has made Java get rid of the impossibility
of multiple inheritance.

15 By: Vishal Pachpute. Mob: 9960972016


5. What is class ?

 A class is a specification or blue print or template of an object.


 Class is a logical construct , an object has physical reality.
 Class is a structure.
 Class is a user defined data type in java
 Class will acts as base for encapsulation.
 Class contains variables and methods.
 Java class may have access modifier as - Public , Private , default or Protected.

public class Dog


{
String breed;
int ageC
String color;

void barking()
{
}

void hungry()
{
}

void sleeping()
{
}
}

A class can contain any of the following variable types.

 Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will be
destroyed when the method has completed.
 Instance variables: Instance variables are variables within a class but outside any method. These
variables are initialized when the class is instantiated. Instance variables can be accessed from
inside any method, constructor or blocks of that particular class.
 Class variables: Class variables are variables declared with in a class, outside any method, with
the static keyword.

A class can have any number of methods to access the value of various kinds of methods. In the above
example, barking(), hungry() and sleeping() are methods.

6. What is Object in java

 Object is instance of class.


 Object is dynamic memory allocation of class.
 Object is an encapsulated form of all non static variables and non static methods of a particular
class.
 The process of creating objects out of class is known as instantiation.
 Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.

class Test
{
16 By: Vishal Pachpute. Mob: 9960972016
int a,b;
void print(){
System.out.println("a="+a);
System.out.println("b="+b);
}

public static void main(String [] args)


{
Test obj= new Test();
obj.a=10;
obj.b=20;
obj.print();
}
}

Output:

1. a=10
2. b=20

Software objects are conceptually similar to real-world objects: they too consist of state and related
behavior. An object stores its state in fields (variables in some programming languages) and exposes its
behavior through methods (functions in some programming languages). Methods operate on an object's
internal state and serve as the primary mechanism for object-to-object communication. Hiding internal
state and requiring all interaction to be performed through an object's methods is known as data
encapsulation — a fundamental principle of object-oriented programming.

Consider a bicycle, for example:

A bicycle modeled as a software object.

By attributing state (current speed, current pedal cadence, and current gear) and providing methods for
changing that state, the object remains in control of how the outside world is allowed to use it. For
example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than
1 or greater than 6.

Bundling code into individual software objects provides a number of benefits, including:

17 By: Vishal Pachpute. Mob: 9960972016


1. Modularity: The source code for an object can be written and maintained independently of the
source code for other objects. Once created, an object can be easily passed around inside the
system.
2. Information-hiding: By interacting only with an object's methods, the details of its internal
implementation remain hidden from the outside world.
3. Code re-use: If an object already exists (perhaps written by another software developer), you
can use that object in your program. This allows specialists to implement/test/debug complex,
task-specific objects, which you can then trust to run in your own code.
4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can
simply remove it from your application and plug in a different object as its replacement. This is
analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not
the entire machine.

7. What is Constructor in java

Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler
builds a default constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.

Example of a constructor is given below:

public class Puppy{


public Puppy(){
}

public Puppy(String name){


// This constructor has one parameter, name.
}
}

Rules for Java Constructor

1. Constructors can use any access modifier, including private. (A private constructor means only
code within the class itself can instantiate an object of that type, so if the private constructor
class wants to allow an instance of the class to be used, the class must provide a static method
or variable that allows access to an instance created from within the class.)
2. The constructor name must match the name of the class.
3. Constructors must not have a return type.
4. It’s legal (but stupid) to have a method with the same name as the class, but that doesn’t make
it a constructor. If you see a return type, it’s a method rather than a constructor. In fact, you
could have both a method and a constructor with the same namethe name of the classin the
same class, and that’s not a problem for Java. Be careful not to mistake a method for a
constructor, be sure to look for a return type.
5. If you don’t type a constructor into your class code, a default constructor will be automatically
generated by the compiler.
6. The default constructor is ALWAYS a no-arg constructor.
7. If you want a no-arg constructor and you’ve typed any other constructor(s) into your class code,
the compiler won’t provide the no-arg constructor for you. In other words, if you’ve typed in a
constructor with arguments, you won’t have a no-arg constructor unless you type it in yourself !
8. Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or
a call to the superclass constructor (super()), although remember that this call can be inserted
by the compiler.
18 By: Vishal Pachpute. Mob: 9960972016
9. If you do type in a constructor (as opposed to relying on the compiler-generated default
constructor), and you do not type in the call to super() or a call to this(), the compiler will insert
a no-arg call to super() for you, as the very first statement in the constructor.
10. A call to super() can be either a no-arg call or can include arguments passed to the super
constructor.
11. A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor, although
the default constructor is always a no-arg constructor. The default constructor is the one the
compiler provides! While the default constructor is always a no-arg constructor, you’re free to
put in your own noarg constructor.
12. You cannot make a call to an instance method, or access an instance variable, until after the
super constructor runs.
13. Only static variables and methods can be accessed as part of the call to super() or this().
(Example: super(Animal.NAME) is OK, because NAME is declared as a static variable.)
14. Abstract classes have constructors, and those constructors are always called when a concrete
subclass is instantiated.
15. Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree.

8. What is abstraction

Abstraction is the quality of dealing with ideas rather than events. for example when you consider the
case of e-mail, complex details such as what happens soon you send an e-mail, the protocol your email
server uses are hidden from the user, therefore to send an e-mail you just need to type the content,
mention the address of the receiver and click send.

like wise in Object oriented programming Abstraction is a process process of hiding the implementation
details from the user, only the functionality will be provided to the user. In other words user will have
the information on what the object does instead of how it does it.

In Java Abstraction is achieved using Abstract classes, and Interfaces.

Abstract Class

A class which contains the abstract keyword in its declaration is known as abstract class.

 Abstract classes may or may not contain abstract methods ie., methods with out body ( public
void get(); )
 But, if a class have at least one abstract method, then the class must be declared abstract.
 If a class is declared abstract it cannot be instantiated.
 To use an abstract class you have to inherit it from another class, provide implementations to
the abstract methods in it.
 If you inherit an abstract class you have to provide implementations to all the abstract methods
in it.

Example
This section provides you an example of the abstract class to create an abstract class just use the
abstract keyword before the class keyword, in the class declaration .

/* File name : Employee.java */


public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println("Constructing an Employee");
19 By: Vishal Pachpute. Mob: 9960972016
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
{
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
public String toString()
{
return name + " " + address + " " + number;
}
public String getName()
{
return name;
}
public String getAddress()
{
return address;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public int getNumber()
{
return number;
}
}

9. What is Encapsulation

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as as single unit. In encapsulation the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their current class, therefore it is also known
as data hiding.

To achieve encapsulation in Java

 Declare the variables of a class as private.


 Provide public setter and getter methods to modify and view the variables values.

Example:
Below given is an example that demonstrates how to achieve Encapsulation in Java:
/* File name : EncapTest.java */
public class EncapTest{

private String name;


private String idNum;
private int age;

public int getAge(){


return age;
20 By: Vishal Pachpute. Mob: 9960972016
}

public String getName(){


return name;
}

public String getIdNum(){


return idNum;
}

public void setAge( int newAge){


age = newAge;
}

public void setName(String newName){


name = newName;
}

public void setIdNum( String newId){


idNum = newId;
}
}

The public setXXX() and getXXX() methods are the access points of the instance variables of the
EncapTest class. Normally, these methods are referred as getters and setters. Therefore any class that
wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be accessed as below::

/* File name : RunEncap.java */


public class RunEncap{

public static void main(String args[]){


EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " +


encap.getAge());
}
}

This would produce the following result:

Name : James Age : 20

Benefits of Encapsulation:

 The fields of a class can be made read-only or write-only.


 A class can have total control over what is stored in its fields.
 The users of a class do not know how the class stores its data. A class can change the data type
of a field and users of the class do not need to change any of their code.

10. What is Interfaces in Java

An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods. A class
implements an interface, thereby inheriting the abstract methods of the interface.

21 By: Vishal Pachpute. Mob: 9960972016


Along with abstract methods an interface may also contain constants, default methods, static methods,
and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviours of an
object. And an interface contains behaviours that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be
defined in the class.

An interface is similar to a class in the following ways:

 An interface can contain any number of methods.


 An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

However, an interface is different from a class in several ways, including:

 You cannot instantiate an interface.


 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface must
be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears in
the class declaration following the extends portion of the declaration.

/* File name : MammalInt.java */


public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This would produce the following result:


22 By: Vishal Pachpute. Mob: 9960972016
ammal eats
ammal travels

11. Common java interview questions

Object Oriented Programming (OOP)

Java is a computer programming language that is concurrent, class-based and object-oriented.


The advantages of object oriented software development are shown below:

 Modular development of code, which leads to easy maintenance and modification.


 Reusability of code.
 Improved reliability and flexibility of code.
 Increased understanding of code.

Object-oriented programming contains many significant features, such as encapsulation,


inheritance, polymorphism and abstraction. We analyze each feature separately in the
following sections.

Encapsulation

Encapsulation provides objects with the ability to hide their internal characteristics and behavior.
Each object provides a number of methods, which can be accessed by other objects and change
its internal data. In Java, there are three access modifiers: public, private and protected. Each
modifier imposes different access rights to other classes, either in the same or in external
packages. Some of the advantages of using encapsulation are listed below:

 The internal state of every objected is protected by hiding its attributes.


 It increases usability and maintenance of code, because the behavior of an object can be
independently changed or extended.
 It improves modularity by preventing objects to interact with each other, in an undesired way.

Polymorphism

Polymorphism is the ability of programming languages to present the same interface for differing
underlying data types. A polymorphic type is a type whose operations can also be applied to
values of some other type.

Inheritance

Inheritance provides an object with the ability to acquire the fields and methods of another class,
called base class. Inheritance provides re-usability of code and can be used to add additional
features to an existing class, without modifying it.

Abstraction

Abstraction is the process of separating ideas from specific instances and thus, develop
classes in terms of their own functionality, instead of their implementation details. Java
supports the creation and existence of abstract classes that expose interfaces, without
including the actual implementation of all methods. The abstraction technique aims to
separate the implementation details of a class from its behavior.

Differences between Abstraction and Encapsulation

23 By: Vishal Pachpute. Mob: 9960972016


Abstraction and encapsulation are complementary concepts. On the one hand, abstraction
focuses on the behavior of an object. On the other hand, encapsulation focuses on the
implementation of an object’s behavior. Encapsulation is usually achieved by hiding information
about the internal state of an object and thus, can be seen as a strategy used in order to provide
abstraction.

General Questions about Java

1. What is JVM ? Why is Java called the “Platform Independent Programming


Language”

A Java virtual machine (JVM) is a process virtual machine that can execute Java
bytecode. Each Java source file is compiled into a bytecode file, which is executed by the
JVM. Java was designed to allow application programs to be built that could be run on
any platform, without having to be rewritten or recompiled by the programmer for each
separate platform. A Java virtual machine makes this possible, because it is aware of the
specific instruction lengths and other particularities of the underlying hardware platform.

2. What is the Difference between JDK and JRE ?

The Java Runtime Environment (JRE) is basically the Java Virtual Machine (JVM) where
your Java programs are being executed. It also includes browser plugins for applet
execution. The Java Development Kit (JDK) is the full featured Software Development
Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java
Debugger), in order for a user to develop, compile and execute Java applications.

3. What does the “static” keyword mean ? Can you override private or static method
in Java ?

The static keyword denotes that a member variable or method can be accessed, without
requiring an instantiation of the class to which it belongs. A user cannot override static
methods in Java, because method overriding is based upon dynamic binding at runtime
and static methods are statically binded at compile time. A static method is not associated
with any instance of a class so the concept is not applicable.

4. Can you access non static variable in static context ?

A static variable in Java belongs to its class and its value remains the same for all its
instances. A static variable is initialized when the class is loaded by the JVM. If your
code tries to access a non-static variable, without any instance, the compiler will
complain, because those variables are not created yet and they are not associated with any
instance.

5. What are the Data Types supported by Java ?

 Byte, short, int, long, float, double, boolean, char

6. Does Java support multiple inheritance ?

No, Java does not support multiple inheritance. Each class is able to extend only on one
class, but is able to implement more than one interfaces.

7. What is the difference between an Interface and an Abstract class ?


24 By: Vishal Pachpute. Mob: 9960972016
Java provides and supports the creation both of abstract classes and interfaces. Both
implementations share some common characteristics, but they differ in the following
features:

 All methods in an interface are implicitly abstract. On the other hand, an abstract class may
contain both abstract and non-abstract methods.
 A class may implement a number of Interfaces, but can extend only one abstract class.
 In order for a class to implement an interface, it must implement all its declared methods.
However, a class may not implement all declared methods of an abstract class. Though, in
this case, the sub-class must also be declared as abstract.
 Abstract classes can implement interfaces without even providing the implementation of
interface methods.
 Variables declared in a Java interface is by default final. An abstract class may contain non-
final variables.
 Members of a Java interface are public by default. A member of an abstract class can either
be private, protected or public.
 An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot
be instantiated, but can be invoked if it contains a main method.

8. What are pass by reference and pass by value ?

When an object is passed by value, this means that a copy of the object is passed. Thus,
even if changes are made to that object, it doesn’t affect the original value. When an
object is passed by reference, this means that the actual object is not passed, rather a
reference of the object is passed. Thus, any changes made by the external method, are
also reflected in all places.

9. How HashMap works in Java ?


A HashMap in Java stores key-value pairs. The HashMap requires a hash function and
uses hashCode and equals methods, in order to put and retrieve elements to and from the
collection respectively. When the put method is invoked, the HashMap calculates the
hash value of the key and stores the pair in the appropriate index inside the collection. If
the key exists, its value is updated with the new value. Some important characteristics of
a HashMap are its capacity, its load factor and the threshold resizing.

10. What differences exist between HashMap and Hashtable ?


Both the HashMap and Hashtable classes implement the Map interface and thus, have
very similar characteristics. However, they differ in the following features:

 A HashMap allows the existence of null keys and values, while a Hashtable doesn’t
allow neither null keys, nor null values.
 A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in
single-threaded environments, while a Hashtable is suitable for multi-threaded
environments.
 A HashMap provides its set of keys and a Java application can iterate over them.
Thus, a HashMap is fail-fast. On the other hand, a Hashtable provides an
Enumeration of its keys.
 The Hashtable class is considered to be a legacy class.

11. What are the two types of Exceptions in Java ? Which are the differences between
them ?

Java has two types of exceptions: checked exceptions and unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or a constructor’s throws
25 By: Vishal Pachpute. Mob: 9960972016
clause, if they can be thrown by the execution of the method or the constructor, and
propagate outside the method or constructor boundary. On the other hand, checked
exceptions must be declared in a method or a constructor’s throws clause. See here for
tips on Java exception handling.

12. What is the difference between Exception and Error in java ?

Exception and Error classes are both subclasses of the Throwable class. The Exception
class is used for exceptional conditions that a user’s program should catch. The Error
class defines exceptions that are not excepted to be caught by the user program.

13. What is the difference between throw and throws ?

The throw keyword is used to explicitly raise a exception within the program. On the
contrary, the throws clause is used to indicate those exceptions that are not handled by a
method. Each method must explicitly specify which exceptions does not handle, so the
callers of that method can guard against possible exceptions. Finally, multiple exceptions
are separated by a comma.

14. What is the importance of finally block in exception handling ?

A finally block will always be executed, whether or not an exception is actually thrown.
Even in the case where the catch statement is missing and an exception is thrown, the
finally block will still be executed. Last thing to mention is that the finally block is used
to release resources like I/O buffers, database connections, etc.

15. What will happen to the Exception object after exception handling ?

The Exception object will be garbage collected in the next garbage collection.

16. How does finally block differ from finalize() method ?

A finally block will be executed whether or not an exception is thrown and is used to
release those resources held by the application. Finalize is a protected method of the
Object class, which is called by the Java Virtual Machine (JVM) just before an object is
garbage collected.

17. What is the difference between a constructor and a method?

A constructor is a member function of a class that is used to create objects of that class. It
has the same name as the class itself, has no return type, and is invoked using the new
operator. A method is an ordinary member function of a class. It has its own name, a
return type (which may be void), and is invoked using the dot operator.

18. What is difference between Method and Function in java

Function is that piece of code that has name ( called function name) and data to operate
on ( called arguments) that is provided in the parenthesis adjacent to the function name.
All function arguments are explicit.
Method on the other had can be viewed as a function that acts on an Object. This object is
an instance of a class (blueprint of that instance). Method will always have an implicit
argument as a reference to self. For example in python you use self , or in Java you use
this.

26 By: Vishal Pachpute. Mob: 9960972016


19. Que: Access modifiers in Java
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
Default Y Y N N
private Y N N N

27 By: Vishal Pachpute. Mob: 9960972016


Basic Java Programs

28 By: Vishal Pachpute. Mob: 9960972016


1. Biggest of 3 Number’s:

package Programs;

import java.util.Scanner;

public class BiggestNo


{
public static void main(String args[])
{
int i, j, k;
Scanner scan = new Scanner (System.in);
System.out.println("Please enter 3 numbers");
i = scan.nextInt();
j = scan.nextInt();
k = scan.nextInt();
if(i>j && i>k)
{
System.out.print(+i +" Is the Biggest No");
}
if(j>i && j>k)
{
System.out.print(+j +" Is the Biggest No");
}
if(k>j && k>i)
{
System.out.print(+k +" Is the Biggest No");
}
}
}

2. Factorial No:

package Programs;

import java.util.Scanner;

public class FactorialNo


{
public static void main(String args[])
{
int prod = 1;
Scanner scan = new Scanner (System.in);
System.out.print("Please Enter No ");
int n = scan.nextInt();
for (int i=n;i>=1;i--)
{
prod = prod *i;

}
System.out.print("Factorial No is: " +prod);

}
3. Fibonacci Series:

package Programs;

public class FibonacciSeries


{

29 By: Vishal Pachpute. Mob: 9960972016


// method 1
public static void main(String args[])
{
int sum =0, i;
for (i=1;i<=10;i++)
{
sum = sum +i;

}
System.out.println (sum);
}
}

//Method 2
public static void main(String args[])
{
int prev, next, sum, n;
prev=next=1;
for(n=1;n<=10;n++)
{
System.out.println(prev);
sum=prev+next;
prev=next;
next=sum;
}
}
}

4. Patterns:

package Programs;

public class Pattern_Hat


{
// For Upper Half Star
public static void main(String[] agrs)
{
int i, j, k;
for (i = 1; i <= 5; i++)
{
for (j = 4; j >= i; j--)
{
System.out.print(" ");
}
for (k = 1; k <= (2 * i - 1); k++)
{
System.out.print("*");
}
System.out.println("");
}
}

//For Lower Half Star


public static void main (String [] args)
{
int i,j,k;
for (i=5;i>=1;i--)
{
for (j=5;j>i;j--)
{
System.out.print(" ");
}

30 By: Vishal Pachpute. Mob: 9960972016


for (k=1;k<(2*i);k++)
{
System.out.print("*");
}
System.out.println();
}

// Right angled triangle : Star


public static void main(String[] args)
{
int i,j;
for (i=1;i<=6;i++)
{
for (j=1;j<i;j++)
{
System.out.print("*");
}
System.out.println();
}

//Upper right angled triangle : Star


public static void main (String[] args)
{
int i,j;
for (i=5;i>=1;i--)
{
for (j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.println();
}

}
}

5. Prime Numbers

package Programs;

import java.util.Scanner;

public class PrimeNumbers


{
//All prime numbers between 1 to 100
public static void main(String args[])
{
int i,j,k;
for (i=1;i<100;i++)
{
k=0;
for (j=2;j<i;j++)
{
if(i%j==0)
{
k=1;
break;
}
}

31 By: Vishal Pachpute. Mob: 9960972016


if(k==0)
{
System.out.println(i);
}
}
}

Check weather given no is prime or not.

{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int res =0;
boolean flag=true;
for (int i=2; i<n/2;i++)
{
res=n%i;
if(res ==0)
{
flag=false;
break;
}
}
if(flag)

System.out.println("No is prime");

else

System.out.println("No is not prime");

6. Reverse of each word in String


package Programs;

import java.util.Scanner;

public class ReverseOfEachWordInSrting


{
public static void main(String args[])
{
String original , reverse = "";
Scanner scan = new Scanner(System.in);
System.out.println("Please enter Original String ");
original = scan.nextLine();
String [] words = original.split(" ");
for (int i=0; i<words.length; i++)
{
for (int j = words[i].length() -1; j>=0; j--)
{
reverse += words[i].charAt(j);
}
System.out.print(reverse + " ");
reverse = "";

32 By: Vishal Pachpute. Mob: 9960972016


}
}}

7. Reverse of Numbers
package Programs;

import java.util.Scanner;

public class ReverseOfNumbers


{
public static void main(String args[])
{
int no, reverse=0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter Number ");
no = scan.nextInt();
while(no>0)
{
int rem=no%10;
reverse=rem+(reverse*10);
no=no/10;
}
System.out.println("Reverse of No is " +reverse);
}
}

8. Reverse of String
package Programs;

import java.util.Scanner;

public class ReverseOfString


{
public static void main(String args[])
{
String original , reverse = "";
Scanner scan = new Scanner(System.in);
System.out.println("Please enter Original String ");
original = scan.nextLine();
for(int i=original.length()-1; i>=0;i--)
{
reverse = reverse + original.charAt(i);

}
System.out.println("After reverse " +reverse);
}

9. String Programs
package Programs;

import java.util.Scanner;

public class StringPrograms


{
// Position of character in String
public static void main(String args[]){
String string = ("You are awesome honey");
for (int i = 0 ; i<string.length() ; i++)
if (string.charAt(i) == 'o')
System.out.println(i);

33 By: Vishal Pachpute. Mob: 9960972016


}
}

//Check String is palindrome


public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);

System.out.println("Enter a string to check if it is a


palindrome");
original = in.nextLine();

int length = original.length();

for ( int i = length - 1; i >= 0; i-- )


reverse = reverse + original.charAt(i);

if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");

10. Sum of Numbers


package Programs;

import java.util.Scanner;

public class SumOfNumbers


{
public static void main(String args[])
{
int n1, sum=0, res;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter first No ");
n1 = scan.nextInt();
while (n1>0)
{
res = n1%10;
n1 = n1/10;
sum = sum +res ;

}
System.out.print("Sum of Numbers is " +sum);
}

11. Swap Numbers


package Programs;

import java.util.Scanner;

public class SwapNumbers


{
//Without using third variable.
public static void main(String args[])
{

34 By: Vishal Pachpute. Mob: 9960972016


int n1,n2;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter first No ");
n1 = scan.nextInt();
System.out.println("Please enter Second No ");
n2 = scan.nextInt();
n1= n1+n2;
n2=n1-n2;
n1=n1-n2;
System.out.println("First No: " + n1);
System.out.println("Second No: " + n2);

}
//Using Third variable

public static void main(String args[])


{
int n1,n2,temp;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter first No ");
n1 = scan.nextInt();
System.out.println("Please enter Second No ");
n2 = scan.nextInt();
temp = n1;
n1=n2;
n2=temp;
System.out.println("After Swap " +n1);
System.out.println("After Swap " +n2);
}

12. Table Of Numbers:


package Programs;

import java.util.Scanner;

public class TableOfNumber {

public static void main(String[] args)


{
int i, no, table=1;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the number: ");
no= scan.nextInt();
for (i=1;i<=10;i++)
{
table = no * i;
System.out.println(table);
}

35 By: Vishal Pachpute. Mob: 9960972016


Short Summary of logic:

Description Logic
for(i=2;i<=n/2;i++)
Prime Numbers - Prime Number are {
divisible by itself only. res=n%i;
if(res==0)
{
flag=false;
break;
}
}
if(flag)

for(n=1;n<=10;n++)
Fibonacci Series ( 1 1 2 3 5 8 13...) {
Sum of previous two numbers will System.out.println(prev);
give us next number sum=prev+next;
prev=next;
next=sum;
}

for(n=1;n<=10;n++)
Sum of 1st 10 Natural Numbers: Sum {
of previous two numbers will give sum+=n; //or sum=sum+n;
}
us next number. System.out.println(sum);

int n, sum=0;
Sum of Square of 1st 10 Natural for(n=1;n<=10;n++)
Numbers {
sum+=n;*n //or
sum=sum+n;*n
}
System.out.println(sum);

for(i=n;i>=1;i--)
Factorial : Factorial of 5 = 5 x 4 x 3 {
x2x1 prod*=i;
//prod=prod*i;
}
System.out.println("Factorial of " + n + " is " +
prod);
}

if(n1>n2 && n1>n3)


Biggest of 3 Numbers using Logical big=n1;
Operators else if(n2>n1 && n2>n3)
big=n2;
else
big=n3;
System.out.println("Biggest No: " +
big);
}

36 By: Vishal Pachpute. Mob: 9960972016


if(n1>n2)
Biggest of 3 Numbers using Nested If {
if(n1>n3)
big=n1;
else
big=n3;
}
else
{
if(n2>n3)
big=n2;
else
big=n3;
}
System.out.println("Biggest No: " +
big);
}

temp=n1;
Swap 2 Numbers using 3rd Variable n1=n2;
n2=temp;
System.out.println("First No: " +
n1);
System.out.println("Second No: " +
n2);

n1=n1+n2;
Swap 2 Numbers without using 3rd n2=n1-n2;
Variable n1=n1-n2

while(n>0)
Sum of Digits 513 -> 5+1+3=9 {
res=n%10;
n=n/10;
sum+=res;
//sum=sum+res;
}
System.out.println("Second No: " +
n2);

String[] words = input.split(" ");


Reverse of each word in string String reverse = "";
for (int i = 0; i < words.length; i++) {
for (int j = words[i].length() - 1; j >= 0; j--
) {
reverse += words[i].charAt(j);
}
System.out.print(reverse + " ");
reverse = "";
}

37 By: Vishal Pachpute. Mob: 9960972016


SQL
Theory, Joins, Common Queries

38 By: Vishal Pachpute. Mob: 9960972016


1. Types of SQL Statements
DDL

Data Definition Language (DDL) statements are used to define the database structure or
schema. Some examples:

 CREATE - to create objects in the database


CREATE TABLE employees
( employee_id INT NOT NULL,
last_name VARCHAR(50) NOT NULL,
first_name VARCHAR(50), salary MONEY );
 ALTER - alters the structure of the database
ALTER TABLE supplier
MODIFY (supplier_name char(100) NOT NULL,
city char(75));
 DROP - delete objects from the database
DROP TABLE table_name
DROP DATABASE database_name
 TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
TRUNCATE TABLE table_name

DML

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

o SELECT - retrieve data from the a database


o INSERT - insert data into a table
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
o UPDATE - updates existing data within a table
o DELETE - deletes all records from a table, the space for the records remain

DCL

Data Control Language (DCL) statements. Some examples:

o GRANT - Gives user's access privileges to database


GRANT ALL on monkeybar.* to 'MdRevUser'@'localhost' identified by
'R3vn1tUp@1_#$r';
Flush privileges;
o REVOKE - withdraw access privileges given with the GRANT command

TCL
Transaction Control (TCL) statements are used to manage the changes made by DML
statements. It allows statements to be grouped together into logical transactions.

o COMMIT - save work done


o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT
39 By: Vishal Pachpute. Mob: 9960972016
o SET TRANSACTION - Change transaction options like isolation level and what rollback
segment to use

2. Constraints in Database Management System


SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted by the
constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE statement) or
after the table is created (inside the ALTER TABLE statement).

 NOT NULL - Indicates that a column cannot store NULL value


 UNIQUE - Ensures that each row for a column must have a unique value
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or
combination of two or more columns) have a unique identity which helps to find a particular
record in a table more easily and quickly
 FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in
another table
 CHECK - Ensures that the value in a column meets a specific condition
 DEFAULT - Specifies a default value for a column

3. Difference between delete and truncate commands

 TRUNCATE is a DDL command whereas DELETE is a DML command.


 TRUNCATE is much faster than DELETE.
 You cann't rollback in TRUNCATE but in DELETE you can rollback.TRUNCATE removes the
record permanently.
 In case of TRUNCATE ,Trigger doesn't get fired.But in DML commands like DELETE .Trigger
get fired.
 You can't use conditions(WHERE clause) in TRUNCATE.But in DELETE you can write
conditions using WHERE clause

4. Different types of JOINs


 (INNER) JOIN: Select records that have matching values in both tables.
 LEFT (OUTER) JOIN: Select records from the first (left-most) table with matching right table
records.
 RIGHT (OUTER) JOIN: Select records from the second (right-most) table with matching left table
records.
 FULL (OUTER) JOIN: Selects all records that match either left or right table records.

40 By: Vishal Pachpute. Mob: 9960972016


Consider following 2 tables:

Table: Gardners

Table: Plantings

Inner Join

An inner join produces a result set that is limited to the rows where there is a match in both tables for
what we're looking for. If you don't know which kind of join you need, this will usually be your best bet.

Example:
SELECT gid, first_name, last_name, pid, gardener_id, plant_name
FROM Gardners
INNER JOIN Plantings
ON gid = gardener_id

Left Outer Join

A left outer join, or left join, results in a set where all of the rows from the first, or left hand side, table
are preserved. The rows from the second, or right hand side table only show up if they have a match
with the rows from the first table. Where there are values from the left table but not from the right, the
table will read null, which means that the value has not been set.

Example:
SELECT gid, first_name, last_name, pid, gardener_id, plant_name
FROM Gardners
LEFT OUTER JOIN Plantings
ON gid = gardener_id

41 By: Vishal Pachpute. Mob: 9960972016


Right Outer Join

A right outer join, or right join, is the same as a left join, except the roles are reversed. All of the rows
from the right hand side table show up in the result, but the rows from the table on the left are only
there if they match the table on the right. Empty spaces are null, just like with the the left join.

Example:
SELECT gid, first_name, last_name, pid, gardener_id, plant_name
FROM Gardners
RIGHT OUTER JOIN Plantings
ON gid = gardener_id

Cross Join

The cross join returns a table with a potentially very large number of rows. The row count of the result
is equal to the number of rows in the first table times the number of rows in the second table. Each row
is a combination of the rows of the first and second table.

Example:
SELECT gid, first_name, last_name, pid, gardener_id, plant_name
FROM Gardners
CROSS JOIN Plantings

42 By: Vishal Pachpute. Mob: 9960972016


Self Join

You can join a single table to itself. In this case, you are using the same table twice.

Example:
SELECT G1.gid, G1.first_name, G1.last_name, G2.gid, G2.first_name, G2.last_name
FROM Gardners G1
INNER JOIN Gardners G2
ON G1.first_name = G2.first_name

5. Queries on Employee and dept. table’s


Table: Emp

Table: Dept

43 By: Vishal Pachpute. Mob: 9960972016


Second highest Salary from emp table
1. Sub queries in SQL are great tool for this kind of scenario, here we first select maximum salary and
then another maximum excluding result of subquery.
mysql> SELECT max(salary) FROM Employee WHERE salary NOT IN (SELECT
max(salary) FROM Employee);
2. Here is another SQL query to find second highest salary using subquery and < operator instead of IN
clause
mysql> SELECT max(salary) FROM Employee WHERE salary < (SELECT
max(salary) FROM Employee);
3. TOP keyword of Sybase and SQL Server database is used to select top record or row of any result
set, by carefully using TOP keyword you can find out second maximum or Nth maximum salary as
shown below.
SELECT TOP 1 salary FROM ( SELECT TOP 2 salary FROM employees ORDER BY
salary DESC) AS emp ORDER BY salary ASC

Some Complex Queries

1) To fetch ALTERNATE records from a table. (EVEN NUMBERED)


select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp);

2) To select ALTERNATE records from a table. (ODD NUMBERED)


select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp);
3) Find the 3rd MAX salary in the emp table.
select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal <= e2.sal);

4) Find the 3rd MIN salary in the emp table.


select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where e1.sal >= e2.sal);

5) Select FIRST n records from a table.


select * from emp where rownum <= &n;

6) Select LAST n records from a table


select * from emp minus select * from emp where rownum <= (select count(*) - &n from emp);

7) List dept no., Dept name for all the departments in which there are no employees in the department.
select * from dept where deptno not in (select deptno from emp);
alternate solution: select * from dept a where not exists (select * from emp b where a.deptno =
b.deptno);
altertnate solution: select empno,ename,b.deptno,dname from emp a, dept b where a.deptno(+) =
b.deptno and empno is null;

8) How to get 3 Max salaries ?


select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where a.sal <= b.sal)
order by a.sal desc;

9) How to get 3 Min salaries ?


select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where a.sal >= b.sal);

10) How to get nth max salaries ?


select distinct hiredate from emp a where &n = (select count(distinct sal) from emp b where a.sal >=
b.sal);

44 By: Vishal Pachpute. Mob: 9960972016


11) Select DISTINCT RECORDS from emp table.
select * from emp a where rowid = (select max(rowid) from emp b where a.empno=b.empno);

12) How to delete duplicate rows in a table?


delete from emp a where rowid != (select max(rowid) from emp b where a.empno=b.empno);

13) Count of number of employees in department wise.


select count(EMPNO), b.deptno, dname from emp a, dept b where a.deptno(+)=b.deptno group by
b.deptno,dname;

14) Suppose there is annual salary information provided by emp table. How to fetch monthly salary of
each and every employee?
select ename,sal/12 as monthlysal from emp;

15) Select all record from emp table where deptno =10 or 40.
select * from emp where deptno=30 or deptno=10;

16) Select all record from emp table where deptno=30 and sal>1500.
select * from emp where deptno=30 and sal>1500;

17) Select all record from emp where job not in SALESMAN or CLERK.
select * from emp where job not in ('SALESMAN','CLERK');

18) Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.


select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');

19) Select all records where ename starts with ‘S’ and its lenth is 6 char.
select * from emp where ename like'S____';

20) Select all records where ename may be any no of character but it should end with ‘R’.
select * from emp where ename like'%R';

21) Count MGR and their salary in emp table.


select count(MGR),count(sal) from emp;

22) In emp table add comm+sal as total sal .


select ename,(sal+nvl(comm,0)) as totalsal from emp;

23) Select any salary <3000 from emp table.


select * from emp where sal> any(select sal from emp where sal<3000);

24) Select all salary <3000 from emp table.


select * from emp where sal> all(select sal from emp where sal<3000);

25) Select all the employee group by deptno and sal in descending order.
select ename,deptno,sal from emp order by deptno,sal desc;

26) How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;

27) How to retrive record where sal between 1000 to 2000?


Select * from emp where sal>=1000 And sal<2000

28) Select all records where dept no of both emp and dept table matches.
select * from emp where exists(select * from dept where emp.deptno=dept.deptno)

45 By: Vishal Pachpute. Mob: 9960972016


29) If there are two tables emp1 and emp2, and both have common record. How can I fetch all the
recods but common records only once?
(Select * from emp) Union (Select * from emp1)

30) How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)

31) How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)

32) Count the totalsa deptno wise where more than 2 employees exist.
SELECT deptno, sum(sal) As totalsal
FROM emp
GROUP BY deptno
HAVING COUNT(empno) > 2

Some More Simple Queries

) Display the details of all employees


SQL>Select * from emp;

2) Display the depart information from department table


SQL>select * from dept;

3) Display the name and job for all the employees


SQL>select ename,job from emp;

4) Display the name and salary for all the employees


SQL>select ename,sal from emp;

5) Display the employee no and totalsalary for all the employees


SQL>select empno,ename,sal,comm, sal+nvl(comm,0) as”total salary” from emp;

6) Display the employee name and annual salary for all employees.
SQL>select ename, 12*(sal+nvl(comm,0)) as “annual Sal” from emp

7) Display the names of all the employees who are working in depart number 10.
SQL>select emame from emp where deptno=10;

8) Display the names of all the employees who are working as clerks and
drawing a salary more than 3000.
SQL>select ename from emp where job=’CLERK’ and sal>3000;

9) Display the employee number and name who are earning comm.
SQL>select empno,ename from emp where comm is not null;

10) Display the employee number and name who do not earn any comm.
SQL>select empno,ename from emp where comm is null;

11) Display the names of employees who are working as clerks,salesman or


analyst and drawing a salary more than 3000.
46 By: Vishal Pachpute. Mob: 9960972016
SQL>select ename from emp where job=’CLERK’ OR JOB=’SALESMAN’
OR JOB=’ANALYST’ AND SAL>3000;

12) Display the names of the employees who are working in the company for
the past 5 years;
SQL>select ename from emp where to_char(sysdate,’YYYY’)-to_char(hiredate,’YYYY’)>=5;

13) Display the list of employees who have joined the company before
30-JUN-90 or after 31-DEC-90.
a)select ename from emp where hiredate < ’30-JUN-1990′ or hiredate > ’31-DEC-90′;

14) Display current Date.


SQL>select sysdate from dual;

15) Display the list of all users in your database(use catalog table).
SQL>select username from all_users;

16) Display the names of all tables from current user;


SQL>select tname from tab;

17) Display the name of the current user.


SQL>show user

18) Display the names of employees working in depart number 10 or 20 or 40


or employees working as CLERKS,SALESMAN or ANALYST.
SQL>select ename from emp where deptno in(10,20,40) or job
in(‘CLERKS’,’SALESMAN’,’ANALYST’);

19) Display the names of employees whose name starts with alaphabet S.
SQL>select ename from emp where ename like ‘S%’;

20) Display the Employee names for employees whose name ends with alaphabet S.
SQL>select ename from emp where ename like ‘%S’;

21) Display the names of employees whose names have second alphabet A in their names.
SQL>select ename from emp where ename like ‘_A%’;

22) select the names of the employee whose names is exactly five characters in length.
SQL>select ename from emp where length(ename)=5;

23) Display the names of the employee who are not working as MANAGERS.
SQL>select ename from emp where job not in(‘MANAGER’);

24) Display the names of the employee who are not working as SALESMAN OR
CLERK OR ANALYST.
SQL>select ename from emp where job not in(‘SALESMAN’,’CLERK’,’ANALYST’);

25) Display all rows from emp table.The system should wait after every screen full of
information.
SQL>set pause on

26) Display the total number of employee working in the company.


SQL>select count(*) from emp;

47 By: Vishal Pachpute. Mob: 9960972016


27) Display the total salary beiging paid to all employees.
SQL>select sum(sal) from emp;

28) Display the maximum salary from emp table.


SQL>select max(sal) from emp;

29) Display the minimum salary from emp table.


SQL>select min(sal) from emp;

30) Display the average salary from emp table.


SQL>select avg(sal) from emp;

31) Display the maximum salary being paid to CLERK.


SQL>select max(sal) from emp where job=’CLERK’;

32) Display the maximum salary being paid to depart number 20.
SQL>select max(sal) from emp where deptno=20;

33) Display the minimum salary being paid to any SALESMAN.


SQL>select min(sal) from emp where job=’SALESMAN’;

34) Display the average salary drawn by MANAGERS.


SQL>select avg(sal) from emp where job=’MANAGER’;

35) Display the total salary drawn by ANALYST working in depart number 40.
SQL>select sum(sal) from emp where job=’ANALYST’ and deptno=40;

36) Display the names of the employee in order of salary i.e the name of
the employee earning lowest salary should salary appear first.
SQL>select ename from emp order by sal;

37) Display the names of the employee in descending order of salary.


a)select ename from emp order by sal desc;

38) Display the names of the employee in order of employee name.


a)select ename from emp order by ename;

39) Display empno,ename,deptno,sal sort the output first base on name and
within name by deptno and with in deptno by sal.
SQL>select empno,ename,deptno,sal from emp order by

40) Display the name of the employee along with their annual salary(sal*12).The name of the
employee earning highest annual salary should apper first.
SQL>select ename,sal*12 from emp order by sal desc;

41) Display name,salary,hra,pf,da,total salary for each employee. The


output should be in the order of total salary,hra 15% of salary,da 10% of salary,pf 5%
salary,total salary will be(salary+hra+da)-pf.
SQL>select ename,sal,sal/100*15 as hra,sal/100*5 as pf,sal/100*10 as
da, sal+sal/100*15+sal/100*10-sal/100*5 as total from emp;

42) Display depart numbers and total number of employees working in each department.
SQL>select deptno,count(deptno)from emp group by deptno;

48 By: Vishal Pachpute. Mob: 9960972016


43) Display the various jobs and total number of employees within each job group.
SQL>select job,count(job)from emp group by job;

44) Display the depart numbers and total salary for each department.
SQL>select deptno,sum(sal) from emp group by deptno;

45) Display the depart numbers and max salary for each department.
SQL>select deptno,max(sal) from emp group by deptno;

46) Display the various jobs and total salary for each job
SQL>select job,sum(sal) from emp group by job;

47) Display the various jobs and total salary for each job
SQL>select job,min(sal) from emp group by job;

48) Display the depart numbers with more than three employees in each dept.
SQL>select deptno,count(deptno) from emp group by deptno having count(*)>3;

49) Display the various jobs along with total salary for each of the jobs
where total salary is greater than 40000.
SQL>select job,sum(sal) from emp group by job having sum(sal)>40000;

50) 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.
SQL>select job,count(empno) from emp group by job having count(job)>3

51) Display the name of the empployee who earns highest salary.
SQL>select ename from emp where sal=(select max(sal) from emp);

52) Display the employee number and name for employee working as clerk and
earning highest salary among clerks.
SQL>select empno,ename from emp where where job=’CLERK’
and sal=(select max(sal) from emp where job=’CLERK’);

53) Display the names of salesman who earns a salary more than the highest
salary of any clerk.
SQL>select ename,sal from emp where job=’SALESMAN’ and sal>(select
max(sal) from emp where job=’CLERK’);

54) Display the names of clerks who earn a salary more than the lowest
salary of any salesman.
SQL>select ename from emp where job=’CLERK’ and sal>(select min(sal)
from emp where job=’SALESMAN’);

55)Display the names of employees who earn a salary more than that of
Jones or that of salary grether than that of scott.
SQL>select ename,sal from emp where sal>
(select sal from emp where ename=’JONES’)and sal> (select sal from emp
where ename=’SCOTT’);

55) Display the names of the employees who earn highest salary in their respective departments.
SQL>select ename,sal,deptno from emp where sal in(select max(sal) from
emp group by deptno);

49 By: Vishal Pachpute. Mob: 9960972016


56) Display the names of the employees who earn highest salaries in their respective job groups.
SQL>select ename,sal,job from emp where sal in(select max(sal) from emp
group by job)

57) Display the employee names who are working in accounting department.
SQL>select ename from emp where deptno=(select deptno from dept where
dname=’ACCOUNTING’)

58) Display the employee names who are working in Chicago.


SQL>select ename from emp where deptno=(select deptno from dept where LOC=’CHICAGO’)

59) Display the Job groups having total salary greater than the maximum salary for managers.
SQL>SELECT JOB,SUM(SAL) FROM EMP GROUP BY JOB HAVING
SUM(SAL)>(SELECT
MAX(SAL) FROM EMP WHERE JOB=’MANAGER’);

60) Display the names of employees from department number 10 with salary
grether than that of any employee working in other department.
SQL>select ename from emp where deptno=10 and sal>any(select sal from emp where deptno
not in 10).

61) Display the names of the employees from department number 10 with salary greater than that
of all employee working in other departments.
SQL>select ename from emp where deptno=10 and sal>all(select sal from emp where deptno not
in 10).

62) Display the names of the employees in Uppercase.


SQL>select upper(ename)from emp

63) Display the names of the employees in Lowecase.


SQL>select lower(ename)from emp

64) Display the names of the employees in Propercase.


SQL>select initcap(ename)from emp;

65) Display the length of Your name using appropriate function.


SQL>select length(‘name’) from dual

66) Display the length of all the employee names.


SQL>select length(ename) from emp;

67) select name of the employee concatenate with employee number.


SQL>select ename||empno from emp;

68) User appropriate function and extract 3 characters starting from 2


characters from the following string ‘Oracle’. i.e the out put should be ‘ac’.
SQL>select substr(‘oracle’,3,2) from dual

69) Find the First occurance of character ‘a’ from the following string i.e
‘Computer Maintenance Corporation’.
SQL>SELECT INSTR(‘Computer Maintenance Corporation’,’a’,1) FROM DUAL

50 By: Vishal Pachpute. Mob: 9960972016


70) Replace every occurance of alphabhet A with B in the string Allens(use translate function)
SQL>select translate(‘Allens’,’A’,’B’) from dual

71) Display the informaction from emp table.Where job manager is found it
should be displayed as boos(Use replace function).
SQL>select replace(JOB,’MANAGER’,’BOSS’) FROM EMP;

72) Display empno,ename,deptno from emp table.Instead of display department


numbers display the related department name(Use decode function).
SQL>select
empno,ename,decode(deptno,10,’ACCOUNTING’,20,’RESEARCH’,30,’SALES’,40,’OPRATI
ONS’) from emp;

73) Display your age in days.


SQL>select to_date(sysdate)-to_date(’10-sep-77′)from dual

74) Display your age in months.


SQL>select months_between(sysdate,’10-sep-77′) from dual

75) Display the current date as 15th Augest Friday Nineteen Ninety Saven.
SQL>select to_char(sysdate,’ddth Month day year’) from dual

76) Display the following output for each row from emp table.
scott has joined the company on wednesday 13th August ninten nintey.
SQL>select ENAME||’ HAS JOINED THE COMPANY ON ‘||to_char(HIREDATE,’day
ddth Month year’) from EMP;

77) Find the date for nearest saturday after current date.
SQL>SELECT NEXT_DAY(SYSDATE,’SATURDAY’)FROM DUAL;

78) Display current time.


SQL>select to_char(sysdate,’hh:MM:ss’) from dual.

79) Display the date three months Before the current date.
SQL>select add_months(sysdate,3) from dual;

80) Display the common jobs from department number 10 and 20.
SQL>select job from emp where deptno=10 and job in(select job from emp
where deptno=20);

81) Display the jobs found in department 10 and 20 Eliminate duplicate jobs.
SQL>select distinct(job) from emp where deptno=10 or deptno=20 (or)
SQL>select distinct(job) from emp where deptno in(10,20);

82) Display the jobs which are unique to department 10.


SQL>select distinct(job) from emp where deptno=10

83) Display the details of those who do not have any person working under them.
SQL>select e.ename from emp,emp e where emp.mgr=e.empno group by
e.ename having count(*)=1;

84) Display the details of those employees who are in sales department and
grade is 3.

51 By: Vishal Pachpute. Mob: 9960972016


SQL>select * from emp where deptno=(select deptno from dept where
dname=’SALES’)and sal between(select losal from salgrade where grade=3)and
(select hisal from salgrade where grade=3);

85) Display those who are not managers and who are managers any one.
i)display the managers names
SQL>select distinct(m.ename) from emp e,emp m where m.empno=e.mgr;

ii)display the who are not managers


SQL>select ename from emp where ename not in(select distinct(m.ename)
from emp e,emp m where m.empno=e.mgr);

86) Display those employee whose name contains not less than 4 characters.
SQL>select ename from emp where length(ename)>4;

87) Display those department whose name start with “S” while the location
name ends with “K”.
SQL>select dname from dept where dname like ‘S%’ and loc like ‘%K’;

88) Display those employees whose manager name is JONES.


SQL>select p.ename from emp e,emp p where e.empno=p.mgr and
e.ename=’JONES’;

89) Display those employees whose salary is more than 3000 after giving 20%
increment.
SQL>select ename,sal from emp where (sal+sal*.2)>3000;

90) Display all employees while their dept names;


SQL>select ename,dname from emp,dept where emp.deptno=dept.deptno

91) Display ename who are working in sales dept.


SQL>select ename from emp where deptno=(select deptno from dept where
dname=’SALES’);

92) Display employee name,deptname,salary and comm for those sal in between
2000 to 5000 while location is chicago.
SQL>select ename,dname,sal,comm from emp,dept where sal between 2000
and 5000
and loc=’CHICAGO’ and emp.deptno=dept.deptno;

93)Display those employees whose salary greter than his manager salary.
SQL>select p.ename from emp e,emp p where e.empno=p.mgr and p.sal>e.sal

94) Display those employees who are working in the same dept where his
manager is work.
SQL>select p.ename from emp e,emp p where e.empno=p.mgr and
p.deptno=e.deptno;

95) Display those employees who are not working under any manager.
SQL>select ename from emp where mgr is null

96) Display grade and employees name for the dept no 10 or 30 but grade is
not 4 while joined the company before 31-dec-82.

52 By: Vishal Pachpute. Mob: 9960972016


SQL>select ename,grade from emp,salgrade where sal between losal and
hisal and deptno in(10,30) and grade<>4 and hiredate<’31-DEC-82′;

97) Update the salary of each employee by 10% increment who are not
eligiblw for commission.
SQL>update emp set sal=sal+sal*10/100 where comm is null;

98) SELECT those employee who joined the company before 31-dec-82 while
their dept location is newyork or Chicago.
SQL>SELECT EMPNO,ENAME,HIREDATE,DNAME,LOC FROM EMP,DEPT
WHERE (EMP.DEPTNO=DEPT.DEPTNO)AND
HIREDATE <’31-DEC-82′ AND DEPT.LOC IN(‘CHICAGO’,’NEW YORK’);

99) DISPLAY EMPLOYEE NAME,JOB,DEPARTMENT,LOCATION FOR ALL WHO ARE


WORKING
AS MANAGER?
SQL>select ename,JOB,DNAME,LOCATION from emp,DEPT where mgr is not
null;

100) DISPLAY THOSE EMPLOYEES WHOSE MANAGER NAME IS JONES? —


[AND ALSO DISPLAY THEIR MANAGER NAME]?
SQL> SELECT P.ENAME FROM EMP E, EMP P WHERE E.EMPNO=P.MGR AND
E.ENAME=’JONES’;

101) Display name and salary of ford if his salary is equal to hisal of his
grade
a)select ename,sal,grade from emp,salgrade where sal between losal and
hisal
and ename =’FORD’ AND HISAL=SAL;

102) Display employee name,job,depart name ,manager name,his grade and make
out an under department wise?
SQL>SELECT E.ENAME,E.JOB,DNAME,EMP.ENAME,GRADE FROM EMP,EMP
E,SALGRADE,DEPT
WHERE EMP.SAL BETWEEN LOSAL AND HISAL AND EMP.EMPNO=E.MGR
AND EMP.DEPTNO=DEPT.DEPTNO ORDER BY DNAME

103) List out all employees name,job,salary,grade and depart name for every
one in the company except ‘CLERK’.Sort on salary display the highest salary?
SQL>SELECT ENAME,JOB,DNAME,SAL,GRADE FROM EMP,SALGRADE,DEPT
WHERE
SAL BETWEEN LOSAL AND HISAL AND EMP.DEPTNO=DEPT.DEPTNO AND JOB
NOT IN(‘CLERK’)ORDER BY SAL ASC;

104) Display the employee name,job and his manager.Display also employee who
are without manager?
SQL>select e.ename,e.job,eMP.ename AS Manager from emp,emp e where
emp.empno(+)=e.mgr

105) Find out the top 5 earners of company?


SQL>SELECT DISTINCT SAL FROM EMP E WHERE 5>=(SELECT COUNT(DISTINCT
SAL)
FROM
EMP A WHERE A.SAL>=E.SAL)ORDER BY SAL DESC;
53 By: Vishal Pachpute. Mob: 9960972016
106) Display name of those employee who are getting the highest salary?
SQL>select ename from emp where sal=(select max(sal) from emp);

107) Display those employee whose salary is equal to average of maximum and
minimum?
SQL>select ename from emp where sal=(select max(sal)+min(sal)/2 from
emp);

108) Select count of employee in each department where count greater than 3?
SQL>select count(*) from emp group by deptno having count(deptno)>3

109) Display dname where at least 3 are working and display only department
name?
SQL>select distinct d.dname from dept d,emp e where d.deptno=e.deptno
and 3>any
(select count(deptno) from emp group by deptno)

110) Display name of those managers name whose salary is more than average
salary of his company?
SQL>SELECT E.ENAME,EMP.ENAME FROM EMP,EMP E
WHERE EMP.EMPNO=E.MGR AND E.SAL>(SELECT AVG(SAL) FROM EMP);

111)Display those managers name whose salary is more than average salary of
his employee?
SQL>SELECT DISTINCT EMP.ENAME FROM EMP,EMP E WHERE
E.SAL <(SELECT AVG(EMP.SAL) FROM EMP
WHERE EMP.EMPNO=E.MGR GROUP BY EMP.ENAME) AND
EMP.EMPNO=E.MGR;

112) Display employee name,sal,comm and net pay for those employee
whose net pay is greter than or equal to any other employee salary of
the company?
SQL>select ename,sal,comm,sal+nvl(comm,0) as NetPay from emp
where sal+nvl(comm,0) >any (select sal from emp)

113) Display all employees names with total sal of company with each
employee name?
SQL>SELECT ENAME,(SELECT SUM(SAL) FROM EMP) FROM EMP;

114) Find out last 5(least)earners of the company.?


SQL>SELECT DISTINCT SAL FROM EMP E WHERE
5>=(SELECT COUNT(DISTINCT SAL) FROM EMP A WHERE
A.SAL<=E.SAL)
ORDER BY SAL DESC;

115) Find out the number of employees whose salary is greater than their
manager salary?
SQL>SELECT E.ENAME FROM EMP ,EMP E WHERE EMP.EMPNO=E.MGR
AND EMP.SAL<E.SAL;

116) Display those department where no employee working?


SQL>select dname from emp,dept where emp.deptno not in(emp.deptno)

54 By: Vishal Pachpute. Mob: 9960972016


117) Display those employee whose salary is ODD value?
SQL>select * from emp where sal<0;

118) Display those employee whose salary contains alleast 3 digits?


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

119) Display those employee who joined in the company in the month of Dec?
SQL>select ename from emp where to_char(hiredate,’MON’)=’DEC’;

120) Display those employees whose name contains “A”?


SQL>select ename from emp where instr(ename,’A’)>0;
or
SQL>select ename from emp where ename like(‘%A%’);

121) Display those employee whose deptno is available in salary?


SQL>select emp.ename from emp, emp e where emp.sal=e.deptno;

122) Display those employee whose first 2 characters from hiredate -last 2
characters of salary?
SQL>select ename,SUBSTR(hiredate,1,2)||ENAME||substr(sal,-2,2) from emp

123) Display those employee whose 10% of salary is equal to the year of
joining?
SQL>select ename from emp where to_char(hiredate,’YY’)=sal*0.1;

124) Display those employee who are working in sales or research?


SQL>SELECT ENAME FROM EMP WHERE DEPTNO IN(SELECT DEPTNO FROM DEPT
WHERE
DNAME IN(‘SALES’,’RESEARCH’));

125) Display the grade of jones?


SQL>SELECT ENAME,GRADE FROM EMP,SALGRADE
WHERE SAL BETWEEN LOSAL AND HISAL AND Ename=’JONES’;

126) Display those employees who joined the company before 15 of the month?
a)select ename from emp where to_char(hiredate,’DD’)<15;

127) Display those employee who has joined before 15th of the month.
a)select ename from emp where to_char(hiredate,’DD’)<15;

128) Delete those records where no of employees in a particular department


is less than 3.
SQL>delete from emp where deptno=(select deptno from emp
group by deptno having count(deptno)<3);

129) Display the name of the department where no employee working.


SQL> SELECT E.ENAME,E.JOB,M.ENAME,M.JOB FROM EMP E,EMP M
WHERE E.MGR=M.EMPNO

130) Display those employees who are working as manager.


SQL>SELECT M.ENAME MANAGER FROM EMP M ,EMP E
WHERE E.MGR=M.EMPNO GROUP BY M.ENAME

55 By: Vishal Pachpute. Mob: 9960972016


131) Display those employees whose grade is equal to any number of sal but
not equal to first number of sal?
SQL> SELECT ENAME,GRADE FROM EMP,SALGRADE
WHERE GRADE NOT IN(SELECT SUBSTR(SAL,0,1)FROM EMP)

132) Print the details of all the employees who are Sub-ordinate to BLAKE?
SQL>select emp.ename from emp, emp e where emp.mgr=e.empno and
e.ename=’BLAKE’;

133) Display employee name and his salary whose salary is greater than
highest average of department number?
SQL>SELECT SAL FROM EMP WHERE SAL>(SELECT MAX(AVG(SAL)) FROM EMP
GROUP BY DEPTNO);

134) Display the 10th record of emp table(without using rowid)


SQL>SELECT * FROM EMP WHERE ROWNUM<11
MINUS
SELECT * FROM EMP WHERE ROWNUM<10

135) Display the half of the ename’s in upper case and remaining lowercase?
SQL>SELECT
SUBSTR(LOWER(ENAME),1,3)||SUBSTR(UPPER(ENAME),3,LENGTH(ENAME))
FROM EMP;

136) Display the 10th record of emp table without using group by and rowid?
SQL>SELECT * FROM EMP WHERE ROWNUM<11
MINUS
SELECT * FROM EMP WHERE ROWNUM<10

Delete the 10th record of emp table.


SQL>DELETE FROM EMP WHERE EMPNO=(SELECT EMPNO FROM EMP WHERE
ROWNUM<11
MINUS
SELECT EMPNO FROM EMP WHERE ROWNUM<10)

137) Create a copy of emp table;


SQL>create table new_table as select * from emp where 1=2;

138) Select ename if ename exists more than once.


SQL>select ename from emp e group by ename having count(*)>1;

139) Display all enames in reverse order?(SMITH:HTIMS).


SQL>SELECT REVERSE(ENAME)FROM EMP;

140) Display those employee whose joining of month and grade is equal.
SQL>SELECT ENAME FROM EMP WHERE SAL BETWEEN
(SELECT LOSAL FROM SALGRADE WHERE
GRADE=TO_CHAR(HIREDATE,’MM’)) AND
(SELECT HISAL FROM SALGRADE WHERE
GRADE=TO_CHAR(HIREDATE,’MM’));

141) Display those employee whose joining DATE is available in deptno.


SQL>SELECT ENAME FROM EMP WHERE TO_CHAR(HIREDATE,’DD’)=DEPTNO

56 By: Vishal Pachpute. Mob: 9960972016


142) Display those employees name as follows
A ALLEN
B BLAKE
SQL> SELECT SUBSTR(ENAME,1,1),ENAME FROM EMP;

143) List out the employees ename,sal,PF(20% OF SAL) from emp;


SQL>SELECT ENAME,SAL,SAL*.2 AS PF FROM EMP;

144) Create table emp with only one column empno;


SQL>Create table emp as select empno from emp where 1=2;

145) Add this column to emp table ename vrachar2(20).


SQL>alter table emp add(ename varchar2(20));

146) Oops I forgot give the primary key constraint. Add in now.
SQL>alter table emp add primary key(empno);

147) Now increase the length of ename column to 30 characters.


SQL>alter table emp modify(ename varchar2(30));

148) Add salary column to emp table.


SQL>alter table emp add(sal number(10));

149) I want to give a validation saying that salary cannot be greater 10,000
(note give a name to this constraint)
SQL>alter table emp add constraint chk_001 check(sal<=10000)

150) For the time being I have decided that I will not impose this validation.My boss has agreed
to pay more than 10,000.
SQL>again alter the table or drop constraint with alter table emp drop constraint chk_001
(or)Disable the constraint by using alter table emp modify constraint chk_001 disable;

151) My boss has changed his mind. Now he doesn’t want to pay more than
10,000.so revoke that salary constraint.
SQL>alter table emp modify constraint chk_001 enable;

152) Add column called as mgr to your emp table;


SQL>alter table emp add(mgr number(5));

153) Oh! This column should be related to empno. Give a command to add this
constraint.
SQL>ALTER TABLE EMP ADD CONSTRAINT MGR_DEPT FOREIGN KEY(MGR)
REFERENCES
EMP(EMPNO)

154) Add deptno column to your emp table;


SQL>alter table emp add(deptno number(5));

155) This deptno column should be related to deptno column of dept table;
SQL>alter table emp add constraint dept_001 foreign key(deptno)
reference dept(deptno)
[deptno should be primary key]

57 By: Vishal Pachpute. Mob: 9960972016


156) Give the command to add the constraint.
SQL>alter table <table_name) add constraint <constraint_name>
<constraint type>

157) Create table called as newemp. Using single command create this table
as well as get data into this table(use create table as);
SQL>create table newemp as select * from emp;
SQL>Create table called as newemp. This table should contain only
empno,ename,dname.
SQL>create table newemp as select empno,ename,dname from emp,dept where
1=2;

158) Delete the rows of employees who are working in the company for more
than 2 years.
SQL>delete from emp where (sysdate-hiredate)/365>2;

159) Provide a commission(10% Comm Of Sal) to employees who are not earning
any commission.
SQL>select sal*0.1 from emp where comm is null

160) If any employee has commission his commission should be incremented by


10% of his salary.
SQL>update emp set comm=sal*.1 where comm is not null;

161) Display employee name and department name for each employee.
SQL>select empno,dname from emp,dept where emp.deptno=dept.deptno

162)Display employee number,name and location of the department in which he


is working.
SQL>select empno,ename,loc,dname from emp,dept where
emp.deptno=dept.deptno;

163) Display ename,dname even if there are no employees working in a


particular department(use outer join).
SQL>select ename,dname from emp,dept where emp.deptno=dept.deptno(+)

164) Display employee name and his manager name.


SQL>select p.ename,e.ename from emp e,emp p where e.empno=p.mgr;

165) Display the department name and total number of employees in each
department.
SQL>select dname,count(ename) from emp,dept where
emp.deptno=dept.deptno group by dname;

166)Display the department name along with total salary in each department.
SQL>select dname,sum(sal) from emp,dept where emp.deptno=dept.deptno
group by dname;

167) Display itemname and total sales amount for each item.
SQL>select itemname,sum(amount) from item group by itemname;

58 By: Vishal Pachpute. Mob: 9960972016


168) Write a Query To Delete The Repeted Rows from emp table;
SQL>Delete from emp where rowid not in(select min(rowid)from emp group
by ename)

169) TO DISPLAY 5 TO 7 ROWS FROM A TABLE


SQL>select ename from emp
where rowid in(select rowid from emp where rownum<=7
minus
select rowid from empi where rownum<5)

170) DISPLAY TOP N ROWS FROM TABLE?


SQL>SELECT * FROM
(SELECT * FROM EMP ORDER BY ENAME DESC)
WHERE ROWNUM <10;

59 By: Vishal Pachpute. Mob: 9960972016

You might also like