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

Interview Preparation

The document provides an overview of key concepts in object-oriented programming such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It also discusses the differences between procedural programming and OOP, and features of OOP like access specifiers, constructors, and copy constructors.
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)
24 views

Interview Preparation

The document provides an overview of key concepts in object-oriented programming such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It also discusses the differences between procedural programming and OOP, and features of OOP like access specifiers, constructors, and copy constructors.
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/ 45

INTERVIEW PREPARATION

Venkata Reddy Bhimireddy


CSE
Pointer
Java doesn’t have pointers; Java has references.
Reference: A reference is a variable that refers to something else and can be used as an alias
for that something else.
Pointer: A pointer is a variable that stores a memory address, for the purpose of acting as an
alias to what is stored at that address.

Dangling Pointer
Sometimes the programmer fails to initialize the pointer with a valid address, then this type of
initialized pointer is known as a dangling pointer in C. Dangling pointer occurs at the time of the
object destruction when the object is deleted or de-allocated from memory without
modifying the value of the pointer.
OOPs

Object Oriented Programming (OOP) is a programming paradigm where the complete


software operates as a bunch of objects talking to each other. An object is a collection of data
and methods that operate on its data.

Why OOPs?
The main advantage of OOP is better manageable code that covers following.
1) The overall understanding of the software is increased as the distance between the
language spoken by developers and that spoken by users.
2) Object orientation eases maintenance by the use of encapsulation. One can easily change
the underlying representation by keeping the methods same.

Procedural Programming:
Procedural Programming can be defined as a programming model which is derived from
structured programming, based upon the concept of calling procedure. Procedures, also
known as routines, subroutines or functions, simply consist of a series of computational steps
to be carried out. During a program’s execution, any given procedure might be called at any
point, including by other procedures or itself.

Class

A class can be understood as a template or a blueprint, which contains some values, known as
member data or member, and some set of rules, known as behaviors or functions.

Object
An object refers to the instance of the class, which contains the instance of the members and
behaviors defined in the class template.
Difference Between Procedural Oriented Programming vs Object-oriented
Programming

• Procedural Oriented Programming • Object-Oriented Programming

• It is based on functions. • It is based on real-world objects.

• It follows a top-down approach. • It follows a bottom-up approach.

• It is less secure because there is no proper way to hide • It provides more security.
data.

• Data is visible to the whole program. • It encapsulates the data.

• Reuse of code is not allowed. • The code can be reused.

• Modification and extension of code are not easy. • We can easily modify and extend code.

• Examples of POP are C, VB, FORTRAN, Pascal, etc. • Examples of OOPs are C++, Java, C#, .NET
etc.

Various types of constructors in C++


The most common classification of constructors includes:

Default constructor: The default constructor is the constructor which doesn’t take any
argument. It has no parameters.

class ABC
{
int x;

ABC()
{
x = 0;
}
}
Parameterized constructor: The constructors that take some arguments are known as
parameterized constructors.

class ABC
{
int x;

ABC(int y)
{
x = y;
}
}

Copy constructor: A copy constructor is a member function that initializes an object using
another object of the same class.

class ABC
{
int x;

ABC(int y)
{
x = y;
}
// Copy constructor
ABC(ABC abc)
{
x = abc.x;
}
}

Copy Constructor
Copy Constructor is a type of constructor, whose purpose is to copy an object to another. What
it means is that a copy constructor will clone an object and its values, into another object, is
provided that both the objects are of the same class.
Destructor
Contrary to constructors, which initialize objects and specify space for them, Destructors are
also special methods. But destructors free up the resources and memory occupied by an object.
Destructors are automatically called when an object is being destroyed.

Virtual Function
A virtual function is a member function which is declared within a base class and is re-
defined(Overriden) by a derived class. When you refer to a derived class object using a pointer
or a reference to the base class, you can call a virtual function for that object and execute the
derived class’s version of the function.

• Virtual functions ensure that the correct function is called for an object, regardless of
the type of reference (or pointer) used for function call.
• They are mainly used to achieve Runtime polymorphism
• Functions are declared with a virtual keyword in base class.
• The resolving of function call is done at Run-time.

Friend Function
A friend function is a function that is specified outside a class but has the ability to access the
class members' protected and private data.

Shallow Copy
A shallow copy is a copy of an object that stores the reference of the original elements. It creates
the new collection object and then occupying it with reference to the child objects found in the
original.

It makes copies of the nested objects' reference and doesn't create a copy of the nested objects.
So if we make any changes to the copy of the object will reflect in the original object. We will use
the copy() function to implement it.
Deep Copy
A deep copy is a process where we create a new object and add copy elements recursively. We
will use the deepcopy() method which present in copy module. The independent copy is created
of original object and its entire object.
Features of OOPs:

1.Abstraction
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviours of an
object differentiate it from other objects of similar type and also help in classifying/grouping
the objects.

2.Encapsulation
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. Another way to think about
encapsulation is, it is a protective shield that prevents the data from being accessed by the
code outside this shield.
As in encapsulation, the data in a class is hidden from other classes, so it is also known
as data-hiding.Encapsulation can be achieved by Declaring all the variables in the class as
private and writing public methods in the class to set and get the values of variables.

3.Polymorphism
The word polymorphism means having many forms.
Eg:A man is a employee at the office at the same time being father to his son/daughter.

Method Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by
change in number of arguments or/and change in type of arguments.
Final methods can not be overridden: If we don’t want a method to be overridden, we declare
it as final.
Method Overriding: occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.

4.Inheritance
Inheritance is a mechanism in which one object acquires all the properties and
behaviors of a parent object.

• Child Class: Subclass is a class which inherits the other class. It is also called a derived class,
extended class, or child class.
• Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
Why use inheritance in java

• For Method Overriding (so runtime polymorphism can be achieved).


• For Code Reusability

Types of Inheritance:

1. Single Inheritance: In single inheritance, subclasses inherit the features of one


superclass. In the image below, class A serves as a base class for the derived class B.

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be inheriting a


base class and as well as the derived class also act as the base class to other class. In the
below image, class A serves as a base class for the derived class B, which in turn serves
as a base class for the derived class C.

3. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a


superclass (base class) for more than one subclass. In the below image, class A serves as
a base class for the derived class B, C and D.

4. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can


have more than one superclass and inherit features from all parent classes. Please note
that Java does not support multiple inheritances with classes. In java, we can achieve
multiple inheritances only through Interfaces.

Access specifiers
Access specifiers, as the name suggests, are a special type of keywords, which are used to
control or specify the accessibility of entities like classes, methods, etc. Some of the access
specifiers or access modifiers include “private”, “public”, etc. These access specifiers also play a
very vital role in achieving Encapsulation - one of the major features of OOPs.
Access specifiers for classes or interfaces in Java
• private (accessible within the class where defined)
• default or package private (when no access specifier is specified)
• protected.
• public (accessible from any class)

Abstract class
A class which is declared with the abstract keyword is known as an abstract class in Java. It can
have abstract and non-abstract methods (method with the body).

Interface in Java
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and multiple
inheritance in Java.
Difference between abstract class and interface:
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

Abstract class Interface

Interface can have only abstract methods. Since


1) Abstract class can have abstract and non-
Java 8, it can have default and static methods
abstract methods.
also.

2) Abstract class doesn't support multiple


Interface supports multiple inheritance.
inheritance.

3) Abstract class can have final, non-final,


Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Types of Variables in java
Instance Variable: It is an object-level variable. It should be declared inside a class but must be
outside a method, block, and constructor. It is created when an object is created by using the
new keyword. It can be accessed directly by calling the variable name inside the class.

Static Variable: It is a class-level variable. It is declared with keyword static inside a class but must
be outside of the method, block, and constructor. It stores in static memory. Its visibility is the
same as the instance variable. The default value of a static variable is the same as the instance
variable. It can be accessed by calling the class_name.variable_name.

Local Variable: It is a method-level variable. It can be declared in method, constructor, or block.


Note that the use of an access modifier is not allowed with local variables. It is visible only to the
method, block, and constructor in which it is declared. Internally, it is implemented at the stack
level. It must be declared and initialized before use.

Reference Variable: It is a variable that points to an object of the class. It points to the location
of the object that is stored in the memory.

Super Keyword in Java

The super keyword in java is a reference variable that is used to refer parent class objects. The
keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the
following contexts:

1. Use of super with variables: This scenario occurs when a derived class and base class
has same data members. In that case there is a possibility of ambiguity for the JVM.

2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we use
super keyword.

3. Use of super with constructors: super keyword can also be used to access the parent
class constructor. One more important thing is that, ‘’super’ can call both parametric as well as
non parametric constructors depending upon the situation.
This Keyword in Java

1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.

2) this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see
the example

3) this() : to invoke current class constructor:

The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining

Java static keyword


The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than
an instance of the class.

The static can be:


1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block

Static variables:

When a variable is declared as static, then a single copy of variable is created and shared
among all objects at class level. Static variables are, essentially, global variables. All instances
of the class share the same static variable.
Important points for static variables :-
• We can create static variables at class-level only.
• static block and static variables are executed in order they are present in a
program.
Below is the java program to demonstrate that static block and static variables are executed
in order they are present in a program.

// java program to demonstrate execution

// of static blocks and variables

class Test

// static variable

static int a = m1();

// static block

static {

System.out.println("Inside static block");


}

// static method

static int m1() {

System.out.println("from m1");

return 20;

// static method(main !!)

public static void main(String[] args)

System.out.println("Value of a : "+a);

System.out.println("from main");

Output:
from m1
Inside static block
Value of a : 20
from main

Static methods:

When a method is declared with static keyword, it is known as static method. The most
common example of a static method is main( ) method.As discussed above, Any static
member can be accessed before any objects of its class are created, and without reference to
any object.Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.

Java static block:

o Is used to initialize the static data member.


o It is executed before the main method at the time of classloading.

Final Keyword In Java

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be
constant).

2) Java final method

If you make any method as final, you cannot override it.

3) Java final class

If you make any class as final, you cannot extend it.

Exception Handling
Java try block:

Java try block is used to enclose the code that might throw an exception. It must be used within
the method.

If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.

Java catch block:

Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.

The catch block must be used after the try block only. You can use multiple catch block with a
single try block.

Throw:
The Java throw keyword is used to throw an exception explicitly. We can also define our own
set of conditions and throw an exception explicitly using throw keyword. For example, we can
throw ArithmeticException if we divide a number by another number. Here, we just need to set
the condition and throw exception using throw keyword.
Syntax:

throw new exception_class("error message");

Throws:

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception. So, it is better for the programmer to provide
the exception handling code so that the normal flow of the program can be maintained.
Syntax:

return_type method_name() throws exception_class_name{

//method code

Difference between final, finally and finalize


The final, finally, and finalize are keywords in Java that are used in exception handling. Each of
these keywords has a different functionality. The basic difference between final, finally and
finalize is that the final is an access modifier, finally is the block in Exception Handling and
finalize is the method of object class.

Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:

Sr.
Key final finally finalize
no.

final is the keyword and finally is the block in Java finalize is the method in Java
access modifier which is Exception Handling to which is used to perform
1. Definition used to apply restrictions execute the important code clean up processing just
on a class, method or whether the exception before object is garbage
variable. occurs or not. collected.

Final keyword is used with Finally block is always


Applicable finalize() method is used
2. the classes, methods and related to the try and catch
to with the objects.
variables. block in exception handling.

(1) Once declared, final


variable becomes (1) finally block runs the
constant and cannot be important code even if finalize method performs
modified. exception occurs or not. the cleaning activities with
3. Functionality
(2) final method cannot be (2) finally block cleans up all respect to the object before
overridden by sub class. the resources used in try its destruction.
(3) final class cannot be block
inherited.
Finally block is executed as
soon as the try-catch block
finalize method is executed
Final method is executed is executed.
4. Execution just before the object is
only when we call it.
It's execution is not destroyed.
dependant on the
exception.

SORTING TECHNIQUES

(never expect linear search)

Binary Search:
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval
covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half.
Repeatedly check until the value is found or the interval is empty.

Example :
1. Compare x with the middle element.
2. If x matches with the middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in the right half subarray
after the mid element. So we recur for the right half.
4. Else (x is smaller) recur for the left half.

Bubble Sort:

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5
> 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm
does not swap them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Insertion Sort:

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards
in your hands. The array is virtually split into a sorted and an unsorted part. Values from the
unsorted part are picked and placed at the correct position in the sorted part.
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before. Move
the greater elements one position up to make space for the swapped element.
Example:
DATA STRUCTURES

STACK:
Stack is a linear data structure which follows a particular order in which the operations are
performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).

There are many real-life examples of a stack. Consider an example of plates stacked over one
another in the canteen. The plate which is at the top is the first one to be removed, i.e. the
plate which has been placed at the bottommost position remains in the stack for the longest
period of time. So, it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out)
order.

QUEUE:
A Queue is a linear structure which follows a particular order in which the operations are
performed. The order is First In First Out (FIFO). A good example of a queue is any queue of
consumers for a resource where the consumer that came first is served first. The difference
between stacks and queues is in removing. In a stack we remove the item the most recently
added; in a queue, we remove the item the least recently added.
Linked List:
A linked list is a linear data structure, in which the elements are not stored at contiguous
memory locations. The elements in a linked list are linked using pointers. In simple words, a
linked list consists of nodes where each node contains a data field and a reference(link) to the
next node in the list.

Types Of Linked List

• Singly Linked List: It is the simplest type of linked list in which every node contains
some data and a pointer to the next node of the same data type. The node contains a
pointer to the next node means that the node stores the address of the next node in the
sequence. A single linked list allows traversal of data only in one way. Below is the
image for the same:
Structure of Linked List:

// Node of a doubly linked list


class Node {
public:
int data;

// Pointer to next node in Linked List


Node* next;

};

• Doubly Linked List: A doubly linked list or a two-way linked list is a more complex
type of linked list which contains a pointer to the next as well as the previous node in
sequence, Therefore, it contains three parts are data, a pointer to the next node, and a
pointer to the previous node. This would enable us to traverse the list in the backward
direction as well. Below is the image for the same:

Structure of Double Linked List:

// Node of a doubly linked list


struct Node {
int data;

// Pointer to next node in DLL


struct Node* next;

// Pointer to the previous node in DLL


struct Node* prev;
};
• Circular Linked List: A circular linked list is that in which the last node contains the
pointer to the first node of the list. While traversing a circular liked list, we can begin at
any node and traverse the list in any direction forward and backward until we reach the
same node we started. Thus, a circular linked list has no beginning and no end. Below is
the image for the same:

GRAPHS:

Breadth First Search (BFS)

There are many ways to traverse graphs. BFS is the most commonly used approach.

BFS is a traversing algorithm where you should start traversing from a selected node (source or
starting node) and traverse the graph layerwise thus exploring the neighbour nodes (nodes
which are directly connected to source node). You must then move towards the next-level
neighbour nodes.

As the name BFS suggests, you are required to traverse the graph breadthwise as follows:

1. First move horizontally and visit all the nodes of the current layer
2. Move to the next layer
Consider the following diagram.

The distance between the nodes in layer 1 is comparitively lesser than the distance between
the nodes in layer 2. Therefore, in BFS, you must traverse all the nodes in layer 1 before you
move to the nodes in layer 2.

Depth First Search (DFS)

The DFS algorithm is a recursive algorithm that uses the idea of backtracking. It involves
exhaustive searches of all the nodes by going ahead, if possible, else by backtracking.

Here, the word backtrack means that when you are moving forward and there are no more
nodes along the current path, you move backwards on the same path to find nodes to traverse.
All the nodes will be visited on the current path till all the unvisited nodes have been traversed
after which the next path will be selected.

This recursive nature of DFS can be implemented using stacks. The basic idea is as follows:
Pick a starting node and push all its adjacent nodes into a stack.
Pop a node from stack to select the next node to visit and push all its adjacent nodes into a
stack.
Repeat this process until the stack is empty. However, ensure that the nodes that are visited
are marked. This will prevent you from visiting the same node more than once. If you do not
mark the nodes that are visited and you visit the same node more than once, you may end up in
an infinite loop.
The following image shows how DFS works.
DBMS

Data Base:
A database is an organized collection of structured information, or data, typically stored
electronically in a computer system. A database is usually controlled by a database
management system (DBMS).

Data Base Management System:


A database management system (DBMS) is a software package designed to define,
manipulate, retrieve and manage data in a database. A DBMS generally manipulates the data
itself, the data format, field names, record structure and file structure. It also defines rules to
validate and manipulate this data.

Advantages of Data Base Mangement System:


Database management systems were developed to handle the following difficulties of
typical File-processing systems supported by conventional operating systems.
1. Data redundancy and inconsistency
2. Difficulty in accessing data
3. Data isolation – multiple files and formats
4. Integrity problems
5. Atomicity of updates
6. Concurrent access by multiple users
7. Security problems

Relational DataBase Management System:


RDBMS stands for Relational DataBase Management Systems. ... Relational Database is a
database system that stores and retrieves data in a tabular format organized in the form of
rows and columns.

Keys
A key is a set of attributes that can identify each tuple uniquely in the given
relation.
Types of Keys:
● Super Key - A superkey is a set of attributes that can identify each tuple uniquely in
the given relation. A super key may consist of any number of attributes.
● Candidate Key - A set of minimal attribute(s) that can identify each tuple uniquely in
the given relation is called a candidate key.
● Primary Key - A primary key is a candidate key that the database designer selects
while designing the database. Primary Keys are unique and NOT NULL.

● Alternate Key - Candidate keys that are left unimplemented or unused


after implementing the primary key are called as alternate keys.
● Foreign Key - An attribute ‘X’ is called as a foreign key to some other attribute ‘Y’ when
its values are dependent on the values of attribute ‘Y’. The relation in which attribute
‘Y’ is present is called as the referenced relation. The relation in which attribute ‘X’ is
present is called as the referencing relation.
● Composite Key - A primary key composed of multiple attributes and not just a
single attribute is called a composite key.
● Unique Key - It is unique for all the records of the table. Once assigned, its value
cannot be changed i.e. it is non-updatable. It may have a NULL value.

Normalization
In DBMS, database normalization is a process of making the database consistent by-
● Reducing the redundancies
● Ensuring the integrity of data through lossless decomposition

Normal Forms: (not important)


● First Normal Form (1NF) - A given relation is called in First Normal Form (1NF) if each
cell of the table contains only an atomic value i.e. if the attribute of every tuple is
either single valued or a null value.
● Second Normal Form (2NF) - A given relation is called in Second Normal Form (2NF)
if and only if
o Relation already exists in 1NF.
o No partial dependency exists in the relation.
A → B is called a partial dependency if and only if- A is a subset of
some candidate key and B is a non-prime attribute.
● Third Normal Form (3NF) - A given relation is called in Third Normal Form (3NF) if
and only if
o Relation already exists in 2NF.
o No transitive dependency exists for non-prime attributes.
A → B is called a transitive dependency if and only if- A is not a super key and
B is a non-prime attribute.
● Boyce-Codd Normal Form - A given relation is called in BCNF if and only
if o Relation already exists in 3NF.
o For each non-trivial functional dependency ‘A → B’, A is a super key of
the relation.

ACID Properties: (not important)


To ensure the consistency of the database, certain properties are followed by all the
transactions occurring in the system. These properties are called as ACID Properties
of a transaction.
● Atomicity –
o This property ensures that either the transaction occurs completely or it does
not occur at all.
o In other words, it ensures that no transaction occurs partially.
● Consistency –
o This property ensures that integrity constraints are maintained.
o In other words, it ensures that the database remains consistent before and
after the transaction.
● Isolation –
o This property ensures that multiple transactions can occur
simultaneously without causing any inconsistency.
o The resultant state of the system after executing all the transactions is the same
as the state that would be achieved if the transactions were executed serially
one after the other.
● Durability –
o This property ensures that all the changes made by a transaction after
its successful execution are written successfully to the disk.
o It also ensures that these changes exist permanently and are never lost even
if there occurs a failure of any kind.
Relational Algebra: (most important)
Relational Algebra is a procedural query language which takes a relation as an
input and generates a relation as an output.
Basic Operator Semantic

σ(Selection) Select rows based on given condition

∏(Projection) Project some columns

X (Cross Product) Cross product of relations, returns m*n rows where m and n
are number of rows in R1 and R2 respectively.

U (Union) Return those tuples which are either in R1 or in R2. Max no.
of rows returned = m+n and Min no. of rows returned =
max(m,n)

−(Minus) R1-R2 returns those tuples which are in R1 but not in R2.
Max no. of rows returned = m and Min no. of rows
returned = m-n

ρ(Rename) Renaming a relation to another relation.

Extended Operator Semantic

∩ (Intersection) Returns those tuples which are in both R1 and R2. Max no.
of rows returned = min(m,n) and Min no. of rows returned
=0

⋈c(Conditional Join) Selection from two or more tables based on some


condition (Cross product followed by selection)

⋈(Equi Join) It is a special case of conditional join when only


equality conditions are applied between attributes.

⋈(Natural Join) In natural join, equality conditions on common attributes


hold and duplicate attributes are removed by default.
Note: Natural Join is equivalent to cross product if two
relations have no attribute in common and natural join of a
relation R with itself will return R only.

⟕(Left Outer Join) When applying join on two relations R and S, some tuples of R
or S do not appear in the result set which does not satisfy the
join conditions. But Left Outer Joins gives all tuples of R in the
result set. The tuples of R which do not satisfy the join
condition will have values as NULL for attributes of S.
⟖(Right Outer Join) When applying join on two relations R and S, some tuples of R
or S do not appear in the result set which does not satisfy the
join conditions. But Right Outer Joins gives all tuples of S in
the result set. The tuples of S which do not satisfy the join
condition will have values as NULL for attributes of R.

⟗(Full Outer Join) When applying join on two relations R and S, some tuples of R
/(Division Operator) or S do not appear in the result set which does not satisfy the
join conditions. But Full Outer Joins gives all tuples of S and all
tuples of R in the result set. The tuples of S which do not
satisfy the join condition will have values as NULL for
attributes of R and vice versa.
Division operator A/B will return those tuples in A which are
associated with every tuple of B. Note: Attributes of B should
be a proper subset of attributes of A. The attributes in A/B
will be Attributes of A- Attribute of B.

SQL

SQL(Standard Query Language):


SQL is a standard language for storing, manipulating and retrieving data in databases.

DDL:
DDL is short name of Data Definition Language, which deals with database schemas
and descriptions, of how the data should reside in the database.
● CREATE - to create a database and its objects like (table, index, views, store
procedure, function, and triggers)
● ALTER - alters the structure of the existing database
● DROP - delete objects from the database
● TRUNCATE - remove all records from a table, including all spaces allocated for
the records are removed
● RENAME - rename an object

DML:
DML is short name of Data Manipulation Language which deals with data manipulation
and includes most common SQL statements such SELECT, INSERT, UPDATE, DELETE, etc.,
and it is used to store, modify, retrieve, delete and update data in a database.
● SELECT - retrieve data from a database
● INSERT - insert data into a table
● UPDATE - updates existing data within a table
● DELETE - Delete all records from a database table
● MERGE - UPSERT operation (insert or update)

DCL:
DCL is short name of Data Control Language which includes commands such as GRANT
and mostly concerned with rights, permissions and other controls of the database
system.
● GRANT - allow users access privileges to the database
● REVOKE - withdraw users access privileges given by using the GRANT command

TCL:
TCL is short name of Transaction Control Language which deals with a transaction
within a database.
● COMMIT - commits a Transaction
● ROLLBACK - rollback a transaction in case of any error occurs
● SAVEPOINT - to roll back the transaction making points within
groups

SELECT:
The SELECT statement is used to select data from a database.
Syntax -
● SELECT column1, column2, ...
FROM table_name;
● Here, column1, column2, ... are the field names of the table you want to select data
from. If you want to select all the fields available in the table, use the following syntax:
● SELECT * FROM table_name;
Ex –
● SELECT CustomerName, City FROM Customers;

SELECT DISTINCT:
The SELECT DISTINCT statement is used to return only distinct (different)
values. Syntax –
● SELECT DISTINCT column1, column2, ...
FROM table_name;
Ex –
● SELECT DISTINCT Country FROM Customers;

WHERE:
The WHERE clause is used to filter records.
Syntax –
● SELECT column1, column2, ...
FROM table_name
WHERE condition;
Ex –
● SELECT * FROM Customers
WHERE Country='Mexico';
Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some versions of SQL this operator may be written as !=

AND, OR and NOT:


The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
● The AND operator displays a record if all the conditions separated by AND are
TRUE.
● The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
Syntax –
● SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
● SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
● SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Ex –
● SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
● SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');

ORDER BY:
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
Syntax –
● SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Ex –
● SELECT * FROM Customers
ORDER BY Country;
● SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;

INSERT INTO:
The INSERT INTO statement is used to insert new records in a table.
Syntax –
● INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
● INSERT INTO table_name
VALUES (value1, value2, value3, ...);
*In the second syntax, make sure the order of the values is in the same order as the columns
in the table.
Ex –
● INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

NULL Value:
It is not possible to test for NULL values with comparison operators, such as =, <, or
<>. We will have to use the IS NULL and IS NOT NULL operators instead.
Syntax –
● SELECT column_names
FROM table_name
WHERE column_name IS NULL;
● SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Ex –
● SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;

UPDATE:
The UPDATE statement is used to modify the existing records in a
table. Syntax –
● UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Ex –
● UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

DELETE:
The DELETE statement is used to delete existing records in a table.
Syntax –
● DELETE FROM table_name WHERE condition;
● DELETE FROM table_name;
In 2ndsyntax, all rows are deleted. The table structure, attributes, and indexes will be
intact Ex –
● DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

SELECT TOP:
The SELECT TOP clause is used to specify the number of records to
return. Syntax –
● SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
● SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
● SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
● SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
*In case the interviewer asks other than the TOP, rest are also correct. (Diff. DB
Systems) Ex –
● SELECT TOP 3 * FROM Customers;
● SELECT * FROM Customers
LIMIT 3;
● SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;

Aggregate Functions:
MIN():
The MIN() function returns the smallest value of the selected
column. Syntax –
● SELECT MIN(column_name)
FROM table_name
WHERE condition;
Ex –
● SELECT MIN(Price) AS SmallestPrice
FROM Products;

MAX():
The MAX() function returns the largest value of the selected
column. Syntax –
● SELECT MAX(column_name)
FROM table_name
WHERE condition;
Ex –
● SELECT MAX(Price) AS LargestPrice
FROM Products;

COUNT():
The COUNT() function returns the number of rows that matches a specified
criterion. Syntax –
● SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Ex –
● SELECT COUNT(ProductID)
FROM Products;

AVG():
The AVG() function returns the average value of a numeric column.
Syntax –
● SELECT AVG(column_name)
FROM table_name
WHERE condition;
Ex –
● SELECT AVG(Price)
FROM Products;

SUM():
The SUM() function returns the total sum of a numeric column.
Syntax –
● SELECT SUM(column_name)
FROM table_name
WHERE condition;
Ex –
● SELECT SUM(Quantity)
FROM OrderDetails;

LIKE Operator:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column. There are two wildcards often used in conjunction with the LIKE operator:
● The percent sign (%) represents zero, one, or multiple characters
● The underscore sign (_) represents one, single character
Syntax –
● SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"

WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are at
least 2 characters in length

WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are at
least 3 characters in length

WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o"

IN:
The IN operator allows you to specify multiple values in a WHERE
clause. The IN operator is a shorthand for multiple OR conditions.
Syntax –
● SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
● SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Ex –
● SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
● SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);

BETWEEN:
The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates.
The BETWEEN operator is inclusive: begin and end values are included.
Syntax –
● SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Ex –
● SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

Joins:
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.

INNER JOIN:
The INNER JOIN keyword selects records that have matching values in both
tables.
Syntax –
● SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Ex –
● SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

LEFT (OUTER) JOIN:


The LEFT JOIN keyword returns all records from the left table (table1), and the matching
records from the right table (table2). The result is 0 records from the right side, if there is no
match.
Syntax –
● SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Ex –
● SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
RIGHT (OUTER) JOIN:
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records from the left table (table1). The result is 0 records from the left side, if
there is no match.
Syntax –
● SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Ex –
● SELECT Orders.OrderID, Employees.LastName,
Employees.FirstName FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID =
Employees.EmployeeID ORDER BY Orders.OrderID;

FULL (OUTER) JOIN:


The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or
right (table2) table records.
Syntax:
● SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Ex –
● SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON
Customers.CustomerID=Orders.CustomerID ORDER BY
Customers.CustomerName;

UNION:
The UNION operator is used to combine the result-set of two or more SELECT statements.
● Every SELECT statement within UNION must have the same number of
columns ● The columns must also have similar data types
● The columns in every SELECT statement must also be in the same order
The UNION operator selects only distinct values by default. To allow duplicate
values, use UNION ALL
Syntax –
● SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
● SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Ex –
● SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

GROUP BY:
The GROUP BY statement groups rows that have the same values into summary rows, like
"find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions
(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns. Syntax –
● SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Ex –
● SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

HAVING:
The HAVING clause was added to SQL because the WHERE keyword cannot be used
with aggregate functions.
*WHERE is given priority over HAVING.
Syntax –
● SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Ex –
● SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

CREATE DATABASE:
The CREATE DATABASE statement is used to create a new SQL
database. Syntax –
● CREATE DATABASE databasename;

DROP DATABASE:
The DROP DATABASE statement is used to drop an existing SQL
database. Syntax –
● DROP DATABASE databasename;

CREATE TABLE:
The CREATE TABLE statement is used to create a new table in a database.
Syntax –
● CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

DROP TABLE:
The DROP TABLE statement is used to drop an existing table in a
database. Syntax –
● DROP TABLE table_name;

TRUNCATE TABLE:
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself. Syntax –
● TRUNCATE TABLE table_name;

ALTER TABLE:
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
Syntax –
● ALTER TABLE table_name
ADD column_name datatype;
● ALTER TABLE table_name
DROP COLUMN column_name;
● ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Ex –
● ALTER TABLE Customers
ADD Email varchar(255);
● ALTER TABLE Customers
DROP COLUMN Email;
● ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;

Procedures :
A procedure is a combination of SQL statements written to perform a specified
tasks. It helps in code re-usability and saves time and lines of code.

Triggers :
A trigger is a special kind of procedure which executes only when some
triggering event such as INSERT, UPDATE, DELETE operations occurs in a table.

----- Just Crake IT -----

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy