Interview Preparation
Interview Preparation
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
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
• It is less secure because there is no proper way to hide • It provides more security.
data.
• 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.
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
Types of Inheritance:
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.
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.
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.
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
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.
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
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
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.
class Test
// static variable
// static block
static {
// static method
System.out.println("from m1");
return 20;
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.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
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 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:
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:
//method code
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.
SORTING TECHNIQUES
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.
• 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:
};
• 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:
GRAPHS:
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.
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).
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.
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
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
∩ (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
⟕(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
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
<> Not equal. Note: In some versions of SQL this operator may be written as !=
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;
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.