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

competitive programming.doc

Uploaded by

Sudhanshu Chand
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

competitive programming.doc

Uploaded by

Sudhanshu Chand
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

1. What is the importance of Data structures in Programming?

Ans: Data structures play a major role in programming. Let us know some of the
important reasons.

● It is used or organize data and manage it efficiently.


● With the help of efficient data structures like linked lists, hash, trees and graphs, it
is easy to store, insert, and manipulate data while programming.
● Efficient use of resources.
● It helps with problem-solving in computer science programming.
● It helps to provide optimal solutions for real-world applications.

2. Non-Decreasing Array

You have been given an integer array/list 'ARR' of size 'N'. Write a solution to check if it
could become non-decreasing by modifying at most 1 element. We define an array as
non-decreasing, if ARR[i] <= ARR[i + 1] holds for every i (0-based) such that (0 <= i <=
N - 2).

Input format :

The first line of each test case contains an Integer 'N' denoting the size of the array/list.
The second line of each test case contains 'N' space-separated Integers denoting the
array/list.

Output format :

For each test case, print a single line containing "true" if it's possible to make 'ARR'
non-decreasing array with modifying at most one element or "false" otherwise. The
output for every test case will be printed in a separate line.

Solution:
As we are allowed at most one modification, we can try it on every index separately and
naively check whether the array becomes non-decreasing by any modification. For this,
we can modify the starting index (i.e. 0) to a very less value (say INT_MIN) and the rest
of the indexes as the value of the preceding element if present (i.e. ARR[i] = ARR[i - 1]).
Space Complexity: O (1)

Time Complexity: O (N ^ 2), where ‘N’ is the length of the array. For every index, we
are modifying it and linearly checking if this modification makes the array
non-decreasing. Hence, time complexity will be O (N ^ 2).
3. Merge K Sorted Arrays

You have been given ‘K’ different arrays/lists, which are sorted individually (in
ascending order). You need to merge all the given arrays/list such that the output
array/list should be sorted in ascending order.

Solution:

Create an output array ‘RESULT’. Traverse all the given arrays from start to end and
insert all the elements in the output array ‘RESULT’. Sort the ‘RESULT’ and return it.
Space Complexity Explanation:

O (N * K), Where ‘K’ is the number of arrays and ‘N’ is the average number of elements
in every array. We are using an array/list of size O (N * K) to store all the elements of the
‘K’ arrays/lists. Then, we are sorting the output array in ascending order which takes
at-least log (N * K) additional space. Thus, the total space complexity is O (K * N).

Time Complexity: O((N * K) * log(N * K)), Where ‘K’ is the number of arrays and ‘N’
is the average number of elements in every array. We are traversing all the ‘K’ arrays and
then we are sorting the output array. Thus, the total time complexity will be

O ((N * K) * log (N * K)).

Divide and Conquer

The idea is based on the divide and conquers strategy. We take pairs of arrays at each
step. Then merge the pairs using the two-pointer technique of merging two sorted arrays.
Thus, after merging all the pairs, the number of arrays will reduce by half. We will
continue this till the number of remaining arrays doesn’t become 1.

4. Find Unique

You have been given an integer array/list (ARR) of size N. Where N is equal to [2M + 1].
Now, in the given array/list, 'M' numbers are present twice and one number is present
only once. You need to find and return that number which is unique in the array/list.

Solution:

The task is to find the unique number in an array where all other numbers occur twice.
The array size is given by N = 2M + 1, where M is the number of elements occurring
twice. Loop through the array and use a hash map to count the occurrences of each
number. Return the number with a count of 1, as it is the unique number. Space
Complexity: O (1), Time Complexity: O(N)
5. Sort Linked List

You are given a Singly Linked List of integers which is sorted based on absolute value.
You have to sort the Linked List based on actual values. The absolute value of a real
number x, denoted |x|, is the non-negative value of x without regard to its sign.

Example: If the given list is {1 -> -2 -> 3} (which is sorted on absolute value), the
returned list should be {-2 -> 1 -> 3}.

Solution:
We will use the ‘Insertion Sort’ algorithm to sort the given linked list.

Algorithm:

We will make a list ‘SORTED_LIST’ which is initially empty and it stores the list after
sorting.

We will traverse the given list and insert the node in the ‘SORTED_LIST’ such that
nodes are present in sorted order.

For each node follow these steps:

If ‘SORTED_LIST’ is empty or the head of the ‘SORTED_LIST’ has a value greater than
the node, in this case, the current node will become the new head of ‘SORTED_LIST’.

Else, we will traverse the ‘SORTED_LIST’ until we find the node that has a value greater
than the current node or until we reach the end.

We will insert the node at this position and change it’s ‘next’ value such that it points to
the node which is greater than the current node.

Space Complexity: O(n) Explanation: O(N), where ‘N’ is the number of nodes in the
linked list.

As O(N) additional space is required to store the ‘SORTED_LIST’. Time Complexity:


O(N ^ 2), where ‘N’ is the number of nodes in the linked list.

In the worst case, it takes O(N) time to insert the node in ‘SORTED_LIST’, and
traversing the list takes O(N) time. Thus, the final time complexity is O(N ^ 2).

Node *sortLL(Node *head)


{
Node *sortedList = NULL;
while (head != NULL)
{
Node *ahead = head->next;
// This node will be the head of sortedList.
if (sortedList == NULL || head->data < sortedList->data)
{
head->next = sortedList;
sortedList = head;
}
else
{
Node *cur = sortedList;
// Traversing the sorted list.
while (cur->next != NULL && cur->next->data < head->data)
{
cur = cur->next;
}
Node *temp = cur->next;
cur->next = head;
head->next = temp;
}
head = ahead;
} return sortedList;
}
6. Check If Linked List Is Palindrome
You are given a Singly Linked List of integers. You have to find if the given linked list is
palindrome or not. A List is a palindrome if it reads the same from the left to the right and
from the right to the left. For example, the lists (1 -> 2 -> 1), (3 -> 4 -> 4-> 3), and (1) are
palindromes, while the lists (1 -> 2 -> 3) and (3 -> 4) are not.
Input Format:
The first line of input contains a single integer T, representing the number of test cases or
queries to be run. Then the T test cases follow. The first and only line of each test case
contains the elements of the linked list separated by a single space and terminated by -1.
Hence, -1 would never be a list element.
Output Format:
For each test case, print “True” if the given linked list is a palindrome, else print “False”.
Solution:
Using Stack
The idea is to store the list values in a stack and then compare the values in the list with
the values in the stack.
Algorithm:
Traverse the list from head to tail and push every node in the stack.
Make a pointer ‘cur’ which initially points to the head node.
If value at ‘cur’ is not equal to the top element of the stack, then the given list is not a
palindrome
Else, move the ‘cur’ pointer to its next node and pop the top element from the stack.
If stack is empty, then the given list is a palindrome
Else, repeat the steps 3 to 6.

Space Complexity: O (N), Where N is the number of nodes in the linked list. We are
storing node values in a stack which will take O (N) extra space.
Time Complexity: O(N), Where N is the number of nodes in the linked list. We are
traversing the list twice and traversing a list takes O(N) time, thus the final time
complexity is O(2 * N) = O(N).
bool isPalindrome(Node *head) {
stack visitedNodes;
// push all nodes in the stack
Node *cur = head;
while (cur != NULL)
{
visitedNodes.push(cur);
cur = cur->next;
}
cur = head;
while (cur != NULL)
{
// compare node values
Node *temp = visitedNodes.top();
if (cur->data != temp->data)
{
return false;
}
visitedNodes.pop();
cur = cur->next;
} return true;
}
7. Diameter Of Binary Tree
You are given a Binary Tree. You are supposed to return the length of the diameter of the
tree. The diameter of a binary tree is the length of the longest path between any two end
nodes in a tree.
Recursion
The basic idea of this approach is to break the problem into subproblems. Now, there are
three possible cases:
The diameter of the tree is present in the left subtree.
The diameter of the tree is present in the right subtree.
The diameter of the tree passes through the root node.
Let us define a recursive function, ‘getDiamter’, which takes the root of the binary tree as
input parameter and returns the diameter of the given subtree rooted at the “root” node.
We can easily find the diameter of the left subtree and right subtree by recursion. The
main task is to calculate the diameter of the tree corresponding to point 3 mentioned
above.

From the above figure, we can observe that if the diameter passes through the root node,
then it can be written as the length of the longest path between the leaves which passes
through the root. And we can get that using the height of the left and right subtrees. Now,
assume a function, ‘getHeight,’ which returns the height of the subtree rooted at the
“root” node. The longest path length(i.e., Number of edges in the path) between the
leaves can be written as: 1 + getHeight(left child of the root node) + getHeight(right child
of the root node)
Algorithm:
If the ‘root’ node is NULL, return 0. The diameter of an empty tree is 0.
Recur for the left subtree and store the diameter of the left subtree in a variable
‘leftDiameter’, i.e. ‘leftDiameter’ = getDiameter(left child of the root node)
Similarly, recur for the right subtree and store the diameter of the right subtree in a
variable ‘rightDiameter’ i.e. ‘rightDiameter’ = getDiameter(right child of the root node)
Now, get the height of the left subtree and right subtree and store it in a variable.
‘leftHeight’ = getHeight(left child of the root node)
‘rightHeight’ = getHeight(right child of the root node)
The diameter of the given tree will be the maximum of the following terms:
‘leftDiameter’
‘rightDiameter’
1 + ‘leftHeight’ + ‘rightHeight’
Return the maximum of above terms i.e.max(leftDiameter, rightDiameter, 1 + leftHeight
+ rightHeight).
Space Complexity: O(n) Explanation: O(N), Where ‘N’ is the number of nodes in the
given binary tree. Since we are doing a recursive tree traversal and in the worst case
(Skewed Trees), all nodes of the given tree can be stored in the call stack. So the overall
space complexity will be O(N).
Time Complexity: O (n^2) Explanation: O (N^2), Where ‘N’ is the number of nodes in
the given binary tree. We are traversing through every node of the binary time that takes
O(N) time, and we are calculating the height for every node, and in the worst case
(Skewed Trees), the getHeight() function will take O(N) time. So the overall time
complexity will be O (N^2).
int getHeight(TreeNode *root) {
if (root == NULL)
{
// Height of empty tree is 0.
return 0;
} // Get the height of left subtree.
int leftHeight = getHeight(root->left);
// Get the height of right subtree.
int rightHeight = getHeight(root->right);
// Height of the given binary tree will be 1 greater than maximum of "leftHeight" and
"rightHeight".
int height = max(leftHeight, rightHeight) + 1;
return height;
}
int getDiameter(TreeNode *root)
{
if (root == NULL)
{
// Diameter of an empty tree will be 0.
return 0;
}
// Get the height of left and right subtrees.
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
// Recur for left subtree and get the diameter.
int leftDiameter = getDiameter(root->left);
// Recur for right subtree and get the diameter.
int rightDiameter = getDiameter(root->right);
// Diameter of given binary tree.
int diameter = max(leftDiameter, max(rightDiameter, leftHeight + rightHeight));
return diameter;
}
int diameterOfBinaryTree(TreeNode *root)
{
return getDiameter(root);
}

8. Check if two given Strings are Isomorphic to each other:


two strings str1 and str2 are called isomorphic if there is a one-to-one
mapping possible for every character of str1 to every character of str2. And
all occurrences of every character in ‘str1’ map to the same character in
‘str2’. Examples:
Input: str1 = “aab”, str2 = “xxy”
Output: True
Explanation: ‘a’ is mapped to ‘x’ and ‘b’ is mapped to ‘y’.
Input: str1 = “aab”, str2 = “xyz”
Output: False
Explanation: One occurrence of ‘a’ in str1 has ‘x’ in str2 and other
occurrence of ‘a’ has ‘y’.
Follow the steps below to solve the problem:
● If the lengths of str1 and str2 are not same, return false.
● Do the following for every character in str1 and str2.
o If this character is seen first time in str1, then-current of str2 must
have not appeared before.
o If the current character of str2 is seen, return false. Mark
the current character of str2 as visited.
o Store mapping of current characters.
o Else check if the previous occurrence of str1[i] mapped to the
same character.
o
Time Complexity: O(N), Traversing over the string of size N
Auxiliary Space: O(1)

9. Count number of substrings with exactly k distinct characters:


Given a string of lowercase alphabets, count all possible substrings (not
necessarily distinct) that has exactly k distinct characters. Example:
Input: abc, k = 2 Output: 2 Possible substrings are {“ab”, “bc”}
Input: aba, k = 2 Output: 3 Possible substrings are {“ab”, “ba”, “aba”}
Method 1 (Brute Force): If the length of string is n, then there can be
n*(n+1)/2 possible substrings. A simple way is to generate all the substring
and check each one whether it has exactly k unique characters or not. If we
apply this brute force, it would take O(n*n) to generate all substrings and
O(n) to do a check on each one. Thus overall it would go O(n*n*n)
Method 2: The problem can be solved in O (n*n). Idea is to maintain a hash
table while generating substring and checking the number of unique
characters using that hash table. The implementation below assume that the
input string contains only characters from ‘a’ to ‘z’. Time Complexity:
O(n*n) Auxiliary Space: O(1), Only 26 size array is used, which can be
considered constant space.
10. Longest Palindromic Subsequence (LPS): The Longest Palindromic
Subsequence (LPS) is the problem of finding a maximum-length
subsequence of a given string that is also a Palindrome.
Input: S = “GEEKSFORGEEKS”
Output: 5
Explanation: The longest palindromic subsequence we can get is of length 5.
There are more than 1 palindromic subsequences of length 5, for example:
EEKEE, EESEE, EEFEE, …etc.
Input: S = “BBABCBCAB”
Output: 7
Explanation: As “BABCBAB” is the longest palindromic subsequence in it.
“BBBBB” and “BBCBB” are also palindromic subsequences of the given
sequence, but not the longest ones.
The naive solution for this problem is to generate all subsequences of the
given sequence and find the longest palindromic subsequence. This solution
is exponential in terms of time complexity. Let us see how this problem
possesses both important properties of a Dynamic Programming (DP)
Problem and can efficiently be solved using Dynamic Programming.
Following is a general recursive solution with all cases handled.
● Case1: Every single character is a palindrome of length 1
o L(i, i) = 1 (for all indexes i in given sequence)
● Case2: If first and last characters are not same
o If (X[i] != X[j]) L(i, j) = max{L(i + 1, j), L(i, j – 1)}
● Case3: If there are only 2 characters and both are same
o Else if (j == i + 1) L(i, j) = 2
● Case4: If there are more than two characters, and first and last
characters are same
o Else L(i, j) = L(i + 1, j – 1) + 2
Time complexity: O(2n), where ‘n’ is the length of the input sequence.
Auxiliary Space: O(n2) as we are using a 2D array to store the solutions of
the sub problems.
Using the Memoization Technique of Dynamic Programming: The idea
used here is to reverse the given input string and check the length of the
longest common subsequence. That would be the answer for the longest
palindromic subsequence. Time Complexity: O(n2)
Auxiliary Space: O(n2)
11. Largest BST in a Binary Tree: Given a Binary Tree, write a function that
returns the size of the largest subtree which is also a Binary Search Tree
(BST). If the complete Binary Tree is BST, then return the size of the whole
tree.
Input:
5
/ \
2 4
/ \
1 3
Output: 3
The following subtree is the
maximum size BST subtree
2
/ \
1 3
Input:
50
/ \
30 60
/ \ / \
5 20 45 70
/ \
65 80
Output: 5
The following subtree is the
maximum size BST subtree
60
/ \
45 70
/ \
65 80

A Tree is BST if following is true for every node x.


The largest value in left subtree (of x) is smaller than value of x.
The smallest value in right subtree (of x) is greater than value of x.
We traverse the tree in a bottom-up manner. For every traversed node, we
return the maximum and minimum values in the subtree rooted at that
node. The idea is to determine whether the subtree rooted at each node is
a Binary Search Tree (BST). If any node follows the properties of a BST
and has the maximum size, we update the size of the largest BST.
Time Complexity : O(n)
Space complexity: O(n) For call stack since using recursion
12. Symmetric Tree (Mirror Image of itself) :
this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
The idea is to write a recursive function isMirror() that takes two trees as
an argument and returns true if trees are the mirror and false if trees are not
mirrored. The isMirror() function recursively checks two roots and
subtrees under the root.
Iterative Approach:
Algorithm for checking whether a binary tree is a mirror of itself using an
iterative approach and a stack:
1. Create a stack and push the root node onto it twice.
2. While the stack is not empty, repeat the following steps:
a. Pop two nodes from the stack, say node1 and node2.
b. If both node1 and node2 are null, continue to the next iteration.
c. If one of the nodes is null and the other is not, return false as it is not
a mirror.
d. If both nodes are not null, compare their values. If they are not equal,
return false.
e. Push the left child of node1 and the right child of node2 onto the
stack.
f. Push the right child of node1 and the left child of node2 onto the
stack.
3. If the loop completes successfully without returning false, return true as it
is a mirror.

Time Complexity: O(n) where n is the number of nodes.


Space Complexity: O(h) where h is the height of the tree.
13. Program to Determine if given Two Trees are Identical or not
Two trees are identical when they have the same data and the arrangement of
data is also the same

Examples:

Input: 1 1
/ \ / \
2 3 2 3
/ /
4 4

Output: Both trees are identical

Input: 1 1
/ \ / \
2 3 5 3
/ /
4 4

Output: Trees are not identical

Using a Depth First Traversal


To identify if two trees are identical, we need to traverse both trees
simultaneously, and while traversing we need to compare data and children of
the trees
Follow the given steps to solve the problem:
● If both trees are empty then return 1(Base case)
● Else If both trees are non-empty
o Check data of the root nodes (tree1->data == tree2->data)
o Check left subtrees recursively
o Check right subtrees recursively
o If the above three statements are true then return 1
● Else return 0 (one is empty and the other is not)

Time Complexity: O(min(N, M)), Where N and M are the sizes of the trees
Auxiliary Space: O(log min(N, M)), due to auxiliary stack space used by
recursion calls
Using Morris traversal:
The basic idea behind the Morris traversal approach to solve the problem of
checking if two binary trees are identical is to use the Morris traversal
algorithm to traverse both trees in-order simultaneously, and compare the nodes
visited at each step.

Follow the steps to implement the above idea:


1. Check if both trees are empty. If they are, return true. If only one of them is
empty, return false.
2. Perform the Morris traversal for in-order traversal of both trees
simultaneously. At each step, compare the nodes visited in both trees.
3. If at any step, the nodes visited in both trees are not equal, return false.
4. If we reach the end of both trees simultaneously (i.e., both nodes are
NULL), return true.

Time Complexity: O(n) , Auxiliary Space: O(1)

14. Detect Cycle in a Directed Graph:


Given the root of a Directed graph, The task is to check whether the graph
contains a cycle or not.
Detect Cycle in a Directed Graph using DFS:
The problem can be solved based on the following idea:
To find cycle in a directed graph we can use the Depth First Traversal (DFS)
technique. It is based on the idea that there is a cycle in a graph only if there is
a back edge [i.e., a node points to one of its ancestors in a DFS tree] present in
the graph.
To detect a back edge, we need to keep track of the nodes visited till now and
the nodes that are in the current recursion stack [i.e., the current path that we
are visiting]. If during recursion, we reach a node that is already in the
recursion stack, there is a cycle present in the graph.
Note: If the graph is disconnected then get the DFS forest and check for a cycle
in individual trees by checking back edges.
Step-by-step algorithm:
● Create a recursive dfs function that has the following parameters – current
vertex, visited array, and recursion stack .
● Mark the current node as visited and also mark the index in the recursion
stack.
● Iterate a loop for all the vertices and for each vertex, call the recursive
function if it is not yet visited (This step is done to make sure that if there is
a forest of graphs, we are checking each forest):
o In each recursion call, Find all the adjacent vertices of the current
vertex which are not visited:
o If an adjacent vertex is already marked in the recursion
stack then return true.
o Otherwise, call the recursive function for that adjacent
vertex.
o While returning from the recursion call, unmark the current node
from the recursion stack, to represent that the current node is no
longer a part of the path being traced.
● If any of the functions returns true, stop the future function calls and
return true as the answer.

Time Complexity: O(V + E), the Time Complexity of this method is the same
as the time complexity of DFS traversal which is O(V+E).

Auxiliary Space: O(V). To store the visited and recursion stack O(V) space is
needed.

MySQL Interview Questions


MySQL is an open-source relational database management system (RDBMS). It
runs on the web as well as on the server. MySQL is fast, reliable, and easy to use. It
is open-source software. MySQL uses standard SQL and compiles on a number of
platforms. It is a multithreaded, multi-user SQL database management system.
1. What are the String Data Types in MySQL?
Type Name Meaning
CHAR fixed-length nonbinary(character) string
VARCHAR variable-length nonbinary string
BINARY fixed-length binary string
VARBINARY variable-length binary string
TINYBLOB Very small BLOB(binary large object)
BLOB Small BLOB
MEDIUMBLOB Medium-sized BLOB
Type Name Meaning
LONGBLOB Large BLOB
TINYTEXT A very small nonbinary string
TEXT Small nonbinary string
MEDIUMTEXT Medium-sized nonbinary string
LONGTEXT Large nonbinary string
An enumeration; each column value is assigned, one enumeration
ENUM
member
SET A set; each column value is assigned zero or more set members
NULL in SQL is the term used to represent a missing value. A
NULL value in a table is a value in a field that appears to be
NULL
blank. This value is different than a zero value or a field that
contains spaces.

2. What is BLOB in MySQL?


BLOB is an acronym that stands for a binary large object. It is used to hold a
variable amount of data. A BLOB can hold a very large amount of data. For
example - documents, images, and even videos. You could store your complete
novel as a file in a BLOB if needed.There are four types of BLOB:
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB

3. What are the Temporal Data Types in MySQL?


Type Name Meaning
DATEA date value, in ' CCYY-MM-DD ' Format
TIME A Time value, in ' hh : mm :ss ' format
DATETIME Date and time value, in ' CCYY-MM-DD hh : mm :ss ' format
TIMESTAMP A timestamp value, in ' CCYY-MM-DD hh : mm :ss ' format
YEAR A year value, in CCYY or YY format
Example: To select the records with an Order Date of "2018-11-11" from a table:
SELECT * FROM Orders WHERE OrderDate='2018-11-11'

5. How do you view a database in MySQL?


One can view all the databases on the MySQL server host using the following
command:
mysql> SHOW DATABASES;

6. How to Delete Data From a MySQL Table?


In MySQL, the DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE column_name = value_name

7. How to create an Index in MySQL?


In MySQL, there are different index types, such as a regular INDEX, a PRIMARY
KEY, or a FULLTEXT index. You can achieve fast searches with the help of an
index.
Example: Adding indexes to the history table:

ALTER TABLE history ADD INDEX(author(10));


ALTER TABLE history ADD INDEX(title(10));
ALTER TABLE history ADD INDEX(category(5));
ALTER TABLE history ADD INDEX(year);
DESCRIBE history;

8. How do you remove a column from a database?


You can remove a column by using the DROP keyword:
ALTER TABLE classics DROP pages;

9. How do you create a database in MySQL?


Use the following command to create a new database called ‘books’:
CREATE DATABASE books;

10. What are some of the common MySQL commands?


Command Action
ALTER To alter a database or table
BACKUP To back-up a table
\c To cancel Input
CREATE To create a database
DELETE To delete a row from a table
DESCRIBE To describe a table's columns
DROP To delete a database or table
EXIT(ctrl+c) To exit
GRANT To change user privileges
HELP (\h, \?) Display help
INSERT Insert data
LOCK Lock table(s)
QUIT(\q) Same as EXIT
RENAME Rename a Table
SHOW List details about an object
SOURCE Execute a file
STATUS (\s) Display the current status
TRUNCATE Empty a table
UNLOCK Unlock table(s)
UPDATE Update an existing record
USE Use a database

11. What are the MySQL clients and utilities?


Several MySQL programs are available to help you communicate with the server.
For administrative tasks, some of the most important ones are listed here:
• mysql—An interactive program that enables you to send SQL statements to the
server and to view the results. You can also use mysql to execute batch scripts (text
files containing SQL statements).
• mysqladmin—An administrative program for performing tasks such as shutting
down the server, checking its configuration, or monitoring its status if it appears
not to be functioning properly.
• mysqldump—A tool for backing up your databases or copying databases to
another server.
• mysqlcheck and myisamchk—Programs that help you perform table checking,
analysis, and optimization, as well as repairs if tables become damaged.
mysqlcheck works with MyISAM tables and to some extent with tables for other
storage engines. myisamchk is for use only with MyISAM tables.
12. What are MySQL Triggers?
A trigger is a task that executes in response to some predefined database event,
such as after a new row is added to a particular table. Specifically, this event
involves inserting, modifying, or deleting table data, and the task can occur either
prior to or immediately following any such event.
Triggers have many purposes, including:
Audit Trails
Validation
Referential integrity enforcement

13. How many Triggers are possible in MySQL?


There are six Triggers allowed to use in the MySQL database:
Before Insert
After Insert
Before Update
After Update
Before Delete
After Delete
14. What are MySQL “Views”?
In MySQL, a view consists of a set of rows that is returned if a particular query is
executed. This is also known as a ‘virtual table’. Views make it easy to retrieve the
way of making the query available via an alias.
The advantages of views are:
Simplicity
Security
Maintainability

MCQ
1) Which of the following commands will you use to load data files into tables?
a) mysqlimport
b) mysqldump
c) mysqlexport
d) mysqladmin

2) MySQL supports different character sets. Which command is used to display


all character sets?
a) SHOW CHARACTER SET;
b) SHOW;
c) CHARACTER SET;
d) None of the above

3) What exports table definitions and contents in MySQL?


a) mysqladmin
b) mysqlimport
c) mysqldump
d) mysqlexport

4) MySQL is capable of reading input from a file in batch mode. This is also
known as the non-interactive mode. A lot of typing and time can be saved
when commands are stored in a file and executed from a file.
Is the above statement True or False?
a) True
b) False

5) In MySQL, what does a fully qualified table name consist of?

a) only the table name


b) only the database name
c) table name followed by database name
d) database name followed by table name

6) Which one is the correct declaration for choosing the character set other than
default?
a) Varchar(20) character set;
b) Varchar(20) character set utf8;
c) Varchar(20);
d) None of the above

7) Character data can be stored as _


a) Fixed length string
b) Variable length string
c) Either Fixed or Variable length string
d) None of the above

8) The connection parameters for setting up MySQL can be stored in an option


file to save typing the names every time a connection is established.
a) True
b) False

9) Which among the following have the maximum bytes?


a) Varchar
b) Char
c) Text type
d) Both Varchar and Char

10) Which among the below options defines a cursor correctly?


a) It is a pointer to permanent work area created in the system memory
b) It is a pointer to temporary area for the DDL statement.
c) It is a pointer to a temporary work area which is created in the
system memory.
d) It is a pointer to permanent work area that was created for DDL
statement.

11) Maximum of how many triggers is possible to apply on one table?


a) 6
b) 12
c) 24
d) 48

12) Can we use a BOOLEAN datatype in functions that are called from SQL
statements?
a) Yes
b) Sometimes yes depending on the condition
c) No

13) Which among the below statements is used for terminating a loop based
on a condition in PL/SQL?
a) GOTO
b) KILL
c) EXIT WHEN
d) CONTINUE WHEN

14) Given the syntax:TYPE arr_name IS VARRAY(integer) OF arr_type,


what does the integer represent?
a) Lower bound of the varray
b) Upper bound of the varray
c) Number of elements present in the array
d) Maximum count of elements which can be stored in the array

1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)
12)
13)
14)
15) What is the default state of an uninitialized associative array variable?
a) Error
b) Undefined
c) NULL
d) Empty

16) Which among the below keywords is used for initializing the variables
instead of using the assignment operator?
a) NOTNULL
b) %TYPE
c) %ROWTYPE
d) DEFAULT

17) An SQL query to delete a table from the database and memory while
keeping the structure of the table intact?
a) DROP TABLE table_name;
b) DROP FROM TABLE table_name;
c) DELETE FROM TABLE table_name;
d) TRUNCATE TABLE table_name;

18) What is a pre-requisite for creating a database in PostgreSQL?To create a


database in PostgreSQL, you must have the special CREATEDB privilege or
a) Super user privilege or CREATEDB privilege
b) Admin privilege
c) CREATEDBL privilege and Super user privilege
d) Just run the script

19) Which of the following is known as a virtual table in SQL?


a) SELF JOIN
b) INNER JOIN
c) VIEW
d) NONE
20) SQL query used to fetch unique values from a field?
a) SELECT UNIQUE column_name FROM table_name;
b) SELECT DISTINCT column_name FROM table_name;
c) SELECT column_name FROM table_name WHERE
COUNT(column_name) = 1;
d) SELECT UNIQUE column_name FROM table_name WHERE
COUNT(column_name) = 1;

21) Which statement is used to update data in the database?


a) MODIFY
b) UPDATE
c) ALTER TABLE
d) SAVE AS

22) Which statement is false for the ORDER BY statement?


a) Requires a ASC or DESC keyword explicitly to sort the result set.
b) Sorts the result set in descending order using the DESC keyword.
c) Can sort based on multiple columns
d) None of the above.

23) Normalization which has neither composite values nor partial


dependencies?
a) Second Normal Formal
b) Third Normal Form
c) Boyce-Codd Normal Form
d) All of the above

24) Which statement is true for a PRIMARY KEY constraint?


a) Primary key defines a realtionship between two tables.
b) A table in SQL must have a primary key associated with it to uniquely
identify its records.
c) A table in SQL is indexed by default based on its primary key.
d) Primary key may or may not be unique but can be comprised of
multiple fields.
25) What is the order of results shown by default if the ASC or DESC
parameter is not specified with the ORDER BY command?
a) Results are shown in descending order
b) Results are shown in ascending order
c) Results display is random
d) Results are shown in ascending and descending order alternately.

26) What allows us to define how various tables are related to each other
formally in a database?
a) Views
b) Foreign Key Constraints
c) Primary Key Constraints
d) Database manager

27) What languages are supported by PostgreSQL?


a) PL/pgSQL, PL/Tcl, PL/Perl and PL/Python
b) PL/pgSQL, PL/Pcl, PL/Ruby and PL/Java
c) PL/Perl, PL/Dcl, PL/Dtl and PL/Dml
d) Only SQL

28) Query to select all records with "bar" in their name?


a) SELECT * FROM people WHERE name = "%bar%";
b) SELECT * FROM people WHERE name LIKE "%bar%";
c) SELECT * FROM people WHERE name IN ("bar");
d) SELECT * FROM people WHERE name = "_bar_"

29) Which statement is false for a FOREIGN KEY constraint?


a) Foreign key defines a relationship between two tables.
b) Foreign Key is automatically created when two tables are joined.
c) Foreign Key uniquely identifies all the records in the referenced table.
d) Foreign key may or may not be unique but can be comprised of
multiple fields.

30) What command is used for restoring the backup of PostgreSQL which
was created using pg_dump?
a) psql -R db_dump.psql db_name
b) psql -r db_dump.psql db_name
c) psql -f db_dump.psql db_name
d) psql -F db_dump.psql db_name

SQL Vs MySQL
Key Category SQL MySQL

MySQL was developed by MySQL


SQL is developed by Microsoft
Developers/Owners AB but is currently acquired and
Corporation.
owned by Oracle Corporation.

SQL is a structured query language MySQL is a Relational database


Function used for managing and retrieving system that uses SQL to query data
data from the database system. from the databases.

MySQL is software and not a


programming language, hence it
The syntax and format are fixed,
does not have any commands or
declarative, and easy to use. Start
Syntax and Format particular format.
with the clause and end with a
There are, however, the latest
semicolon.
updates and versions of MySQL for
enhanced performance.

SQL is proprietary based software MySQL is an open-source free


Licensing/Availability owned by Microsoft and not open platform that allows access to any
to others for free. and everyone.

SQL was built for WIndows, works MySQL is adaptable for


Platform Support partially for Linux, macOS with its cross-platforms, working well for
latest versions. Linux, macOS, and Windows.
MySQL supports all the basic
SQL is in itself a programming
programming languages like C,
Language Support language used for database
C++, Perl, PHP, Python, Ruby, and
systems.
many others.

MySQL supports different storage


engines and does not take up a lot of
SQL supports only a single storage
Storage Engine space for different functions and
engine for different operations
operations. It also enables the
plugin storage engine as well.

MySQL is susceptible to more


security threats due to its
SQL servers are secured as no third
open-source nature. It gives access
Data Security party or outsiders are allowed to
to data manipulation and
manipulate data.
modification to unauthorized users
as well during the run-time.

MySQL servers do not work


independently from databases and
In SQL, the server and database
hence, blocks the time for the users
work independently. This allows
to do anything else.
Server and Database users or interested parties to work
This function allows a lesser chance
on databases even during recovery
for data manipulation or corruption
sessions.
during the shifting of data into
different versions of the software.

In MySQL, the process of data


Time consumed for data restoration
restoration is quite time-consuming
Data Restoration in SQL is less for a large amount of
and requires a number of SQL
data.
statements for the same.

MySQL does not allow you to


SQL allows truncating a query even cancel a query in the middle of
Query Execution during execution without disabling execution. The user can cancel the
the whole process. query execution at the cost of
stopping the entire process.

SQL is available in different MySQL is available only in a single


Multilingual
languages. language that is English.
MySQL is equipped with an in-built
tool known as MySQL Workbench
SQL does not come up or support
Connector Support that enables you to create, design,
any connectors.
and build databases easily and
quickly.

SQL supports user-defined MySQL does not support any


Flexibility
functions and XML. user-defined function and XML.

The only support for SQL problems


and queries is Microsoft Support MySQL has great community
Community Support
care due to its highly protective support as it allows free access.
usage.

Interactive LanguageCoding not Open-source data SecurityHigh


Advantages requiredPortabilityHigh PerformanceComplete workflow
SpeedMultiple Data Views Control

An SQL database follows a


It is common for MySQL to be
standard format that does not
Updates updated frequently, as it has a
require many or any updates to be
number of different variants.
performed regularly.

MySQL vs. PostgreSQL: Head-To-Head


Comparison

MySQL PostgreSQL
1) It is a Relational Database Management 1) It is an Object-Relational Database Management
System. System.
2) MySQL was developed by a Swedish 2) PostgreSQL was developed by the Department
company called MySQL AB in 1995. of Computer Science, University of California.
3) MySQL is not completely ACID compliant.
It supports ACID only when used in InnoDB 3) PostgreSQL is completely ACID compliant.
and NDB.
4) In addition to its simplicity and reliability, 4) The PostgreSQL database is more complex and
MySQL is also fast and efficient. slower than MySQL.
MySQL PostgreSQL
5) MySQL is easy to troubleshoot as it has a
5) PostgreSQL is not easy to troubleshoot.
nice and devoted community ready to help.
6) Users cannot be assigned object-level
6) Users can be assigned object-level privileges.
privileges.
7) Only partially SQL compliant. 7) PostgreSQL is fully SQL compliant.
8) It is licensed under GNU GPU 8) It is licensed under the MIT style.
9) It is written in C/C++. 9) It is written in C.
10) MySQL is best suited for simple operations
10) In general, PostgreSQL is a good fit for systems
like read and write. For web-based projects
that perform large and complex queries, as well
requiring only simple data transactions,
as those that store and analyze data.
MySQL is a good choice.
11) PostgreSQL supports standard data types and in
11) MySQL supports standard data types like addition to these data types, PostgreSQL also
string, numeric, date and time, etc. supports advanced data types such as arrays,
hstore, and user-defined data types.
12) There is no support for table inheritance and
materialized views in MySQL. A 12) Table inheritance and materialized views are
materialized view is a pre-computed query both supported by PostgreSQL.
result that can be used later
13) It does not provide table inheritance. 13) It provides table inheritance.
14) PostgreSQL has a number of join capabilities
14) Join capabilities in MySQL are limited. like inner join, right join, left join, cross join,
full outer join, natural join, and self join.
15) MVCC is one of the most important reasons
15) MySQL does not provide support for
companies choose PostgreSQL. It handles
MVCC.
concurrency better than MySQL.
16) MySQL has a multilayer structure having a 16) PostgreSQL is a unified database storage server
set of storage engines. and has a single storage engine.
17) MySQL provides a workbench as a user 17) PostgreSQL provides PgAdmin as a user
interface. interface.
18) Every connection created in MySQL is an 18) Every connection created in PostgreSQL is an
Operating System (OS) thread. Operating System (OS) process.
19) It has native Server Sockets Layer (SSL)
support. SSL is a security protocol that 19) It has native Transport Layer Security (TLS)
creates a secure encrypted link between a support. TLS is an improved version of SSL.
web server and a web browser.
20) It does not support partial, bitmap, or 20) PostgreSQL supports partial, bitmap, or
expression indexes. expression indexes all of these.
21) Replication in PostgreSQL is synchronous
21) Replication in MySQL is one-way
replication where the master database is
asynchronous replication where one server
synchronized with the slave database. It utilizes
is used as primary and others as replicas.
two database instances running simultaneously.
MySQL PostgreSQL
22) Companies that use MySQL: 22) Companies that use PostgreSQL:
Facebook, Tesla, YouTube, Airbnb, NASA Apple, Cisco, Netflix, Reddit, Spotify, Fujitsu

Differentiate between SQL and PL/SQL.

SQL PL/SQL
SQL is a natural language meant for the interactive
PL/SQL is a procedural extension of SQL.
processing of data in the database.
PL/SQL supports all features of procedural language
Decision-making and looping are not allowed in SQL.
such as conditional and looping statements.
All SQL statements are executed at a time by the
PL/SQL statements are executed one block at a time
database server which is why it becomes a
thereby reducing the network traffic.
time-consuming process.
There is no error handling mechanism in SQL. This supports an error handling mechanism.

8. Differentiate between implicit cursor and explicit cursor.

Implicit Cursor Explicit Cursor


An implicit cursor is used when a query returns a When a subquery returns more than one row, an explicit
single row value. cursor is used. These rows are called Active Set.
This is used for all DML operations like
This is used to process Multirow SELECT Statements.
DECLARE, OPEN, FETCH, CLOSE.
NO_DATA_FOUND Exception is handled here. NO_DATA_FOUND cannot be handled here.

SQL vs NoSQL

Parameter SQL NoSQL

SQL databases are a type of system NoSQL databases are a type of software
software that supports management, that allows to maintain and retrieve
Define
analysis, capturing and querying the structured, unstructured, polymorphic data
structured data in a relational format. for different purposes.

A language used to communicate with


databases for storage, deletion, A software to retrieve, store and manage
Purpose
updation, insertion and retrieval of scalability of databases.
data.
NoSQL was developed in 2000 as an
Development SQL was developed in the year 1970
enhanced version for SQL databases for
Year for flat file storage problems.
unstructured and semi-structured data.

Query SQL databases support Structured NonSQL does not have any declarative
Language Query Languages. query language.

Supports document oriented, graph


Type Supports table based data type.
databases, key value pair-based.

Horizontally Scalable (Changing small


Vertically Scalable (Add resources to
nodes with larger nodes to increase the
Scalability increase the capacity of the existing
capacity of the existing hardware and
hardware and software).
software).

SQL supports predefined schemas,


Nosql supports dynamic schemas to store
Schemas making the storage of data restrictive
different forms of data.
to structured type only.

Architecture SQL is relational. Non-SQL is non relational.

NoSQL is best suited for unstructured


Ideal Use SQL is best suitable for complex
data or documents. Not ideal for complex
Cases queries, multi-row transactions.
queries.

Databases that support SQL require


NonSQL databases require commodity
Hardware powerful hardware to support vertical
hardware for horizontal scaling.
scaling.

SQL enables ACID(atomicity,


NonSQL follows CAP (consistency,
Properties consistency, isolation, and durability)
availability, partition tolerance) properties.
properties

SQL does not support hierarchical NoSQL is best suited for hierarchical
Data Storage
storage of data. storage of data.
SQL databases can only be run on a NoSQL databases are designed to follow
Distributed
single system and hence, does not data distribution features like repetition,
Data
follow distribution of data. partition.

• Secure • High Performance


Best
• Cross Platform Support • Flexible
Features
• Free • Easy to use

Top
Companies Microsoft, Dell, Cognizant, etc. Amazon, Capgemini, Adobe, etc.
Using

SQL supports databases like MySQL, Nosql databases are Hbase, MongoDB,
Examples
SQL Server, Oracle, etc. Redis, etc.

What is Normalization?

Normalization represents the way of organizing structured data in the database


efficiently. It includes the creation of tables, establishing relationships between
them, and defining rules for those relationships. Inconsistency and redundancy can
be kept in check based on these rules, hence, adding flexibility to the database.

What is Denormalization?

Denormalization is the inverse process of normalization, where the normalized


schema is converted into a schema that has redundant information. The
performance is improved by using redundancy and keeping the redundant data
consistent. The reason for performing denormalization is the overheads produced
in the query processor by an over-normalized structure.

What are the various forms of Normalization?

Normal Forms are used to eliminate or reduce redundancy in database tables. The
different forms are as follows:

● First Normal Form:


A relation is in first normal form if every attribute in that relation is
a single-valued attribute. If a relation contains a composite or multi-valued
attribute, it violates the first normal form. Let's consider the
following students table. Each student in the table, has a name, his/her
address, and the books they issued from the public library -

Students Table

Student Address Books Issued Salutation

Amanora Park Until the Day I Die (Emily Carpenter),


Sara Ms.
Town 94 Inception (Christopher Nolan)

62nd Sector The Alchemist (Paulo Coelho), Inferno


Ansh Mr.
A-10 (Dan Brown)

24th Street Park Beautiful Bad (Annie Ward), Woman 99


Sara Mrs.
Avenue (Greer Macallister)

Windsor Street
Ansh Dracula (Bram Stoker) Mr.
777

As we can observe, the Books Issued field has more than one value per record, and
to convert it into 1NF, this has to be resolved into separate individual records for
each book issued. Check the following table in 1NF form -

Students Table (1st Normal Form)

Student Address Books Issued Salutation

Until the Day I Die (Emily


Sara Amanora Park Town 94 Ms.
Carpenter)

Sara Amanora Park Town 94 Inception (Christopher Nolan) Ms.

Ansh 62nd Sector A-10 The Alchemist (Paulo Coelho) Mr.

Ansh 62nd Sector A-10 Inferno (Dan Brown) Mr.


Student Address Books Issued Salutation

24th Street Park


Sara Beautiful Bad (Annie Ward) Mrs.
Avenue

24th Street Park


Sara Woman 99 (Greer Macallister) Mrs.
Avenue

Ansh Windsor Street 777 Dracula (Bram Stoker) Mr.

● Second Normal Form:

A relation is in second normal form if it satisfies the conditions for the first normal
form and does not contain any partial dependency. A relation in 2NF has no
partial dependency, i.e., it has no non-prime attribute that depends on any proper
subset of any candidate key of the table. Often, specifying a single column Primary
Key is the solution to the problem. Examples -

Example 1 - Consider the above example. As we can observe, the Students Table
in the 1NF form has a candidate key in the form of [Student, Address] that can
uniquely identify all records in the table. The field Books Issued (non-prime
attribute) depends partially on the Student field. Hence, the table is not in 2NF. To
convert it into the 2nd Normal Form, we will partition the tables into two while
specifying a new Primary Key attribute to identify the individual records in the
Students table. The Foreign Key constraint will be set on the other table to ensure
referential integrity.

Students Table (2nd Normal Form)

Student_ID Student Address Salutation

1 Sara Amanora Park Town 94 Ms.

2 Ansh 62nd Sector A-10 Mr.

3 Sara 24th Street Park Avenue Mrs.

4 Ansh Windsor Street 777 Mr.


Books Table (2nd Normal Form)

Student_ID Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

Example 2 - Consider the following dependencies in relation to R(W,X,Y,Z)

WX -> Y [W and X together determine Y]

XY -> Z [X and Y together determine Z]

Here, WX is the only candidate key and there is no partial dependency, i.e., any
proper subset of WX doesn’t determine any non-prime attribute in the relation.

● Third Normal Form

A relation is said to be in the third normal form, if it satisfies the conditions for the
second normal form and there is no transitive dependency between the non-prime
attributes, i.e., all non-prime attributes are determined only by the candidate keys
of the relation and not by any other non-prime attribute.

Example 1 - Consider the Students Table in the above example. As we can


observe, the Students Table in the 2NF form has a single candidate key Student_ID
(primary key) that can uniquely identify all records in the table. The field
Salutation (non-prime attribute), however, depends on the Student Field rather than
the candidate key. Hence, the table is not in 3NF. To convert it into the 3rd Normal
Form, we will once again partition the tables into two while specifying a
new Foreign Key constraint to identify the salutations for individual records in the
Students table. The Primary Key constraint for the same will be set on the
Salutations table to identify each record uniquely.

Students Table (3rd Normal Form)

Student_ID Student Address Salutation_ID

1 Sara Amanora Park Town 94 1

2 Ansh 62nd Sector A-10 2

3 Sara 24th Street Park Avenue 3

4 Ansh Windsor Street 777 1

Books Table (3rd Normal Form)

Student_ID Book Issued

1 Until the Day I Die (Emily Carpenter)

1 Inception (Christopher Nolan)

2 The Alchemist (Paulo Coelho)

2 Inferno (Dan Brown)

3 Beautiful Bad (Annie Ward)

3 Woman 99 (Greer Macallister)

4 Dracula (Bram Stoker)

Salutations Table (3rd Normal Form)


Salutation_ID Salutation

1 Ms.

2 Mr.

3 Mrs.

Example 2 - Consider the following dependencies in relation to R(P,Q,R,S,T)

P -> QR

RS -> T

Q -> S

T -> P

For the above relation to exist in 3NF, all possible candidate keys in the above
relation should be {P, RS, QR, T}.

● Boyce-Codd Normal Form

A relation is in Boyce-Codd Normal Form if satisfies the conditions for third


normal form and for every functional dependency, Left-Hand-Side is super key. In
other words, a relation in BCNF has non-trivial functional dependencies in form X
–> Y, such that X is always a super key. For example - In the above example,
Student_ID serves as the sole unique identifier for the Students Table and
Salutation_ID for the Salutations Table, thus these tables exist in BCNF. The same
cannot be said for the Books Table and there can be several books with common
Book Names and the same Student_ID.

What are Aggregate and Scalar functions?

An aggregate function performs operations on a collection of values to return a


single scalar value. Aggregate functions are often used with the GROUP BY and
HAVING clauses of the SELECT statement. Following are the widely used SQL
aggregate functions:

● AVG() - Calculates the mean of a collection of values.


● COUNT() - Counts the total number of records in a specific table or view.

● MIN() - Calculates the minimum of a collection of values.

● MAX() - Calculates the maximum of a collection of values.

● SUM() - Calculates the sum of a collection of values.

● FIRST() - Fetches the first element in a collection of values.

● LAST() - Fetches the last element in a collection of values.

Note: All aggregate functions described above ignore NULL values except for the
COUNT function.

A scalar function returns a single value based on the input value. Following are the
widely used SQL scalar functions:

● LEN() - Calculates the total length of the given field (column).

● UCASE() - Converts a collection of string values to uppercase characters.

● LCASE() - Converts a collection of string values to lowercase characters.

● MID() - Extracts substrings from a collection of string values in a table.

● CONCAT() - Concatenates two or more strings.

● RAND() - Generates a random collection of numbers of a given length.

● ROUND() - Calculates the round-off integer value for a numeric field (or
decimal point values).

● NOW() - Returns the current date & time.

● FORMAT() - Sets the format to display a collection of values.

1) In the Student table, the marks column contains a list of values separated by
commas. How can you determine the number of values in this
comma-separated list?

CREATE TABLE Student (


id INT NOT NULL,

name VARCHAR(50) NOT NULL,

marks VARCHAR(255) NOT NULL,

PRIMARY KEY (id)

);

INSERT INTO Student (id, name, marks)

VALUES (1, 'Rohit', '87,92,76,89');

SELECT id, name, marks, LENGTH(marks) - LENGTH(REPLACE(marks, ',', ''))


+ 1 AS num_marks

FROM Student

WHERE id = 1;

Output:

2. Write a query to fetch the EmpFname from the EmployeeInfo table in


upper case and use the ALIAS name as EmpName.

1 SELECT UPPER(EmpFname) AS EmpName FROM EmployeeInfo;

3. Write a query to fetch the number of employees working in the department


‘HR’.

1 SELECT COUNT(*) FROM EmployeeInfo WHERE Department = 'HR';


4. Write a query to get the current date.

You can write a query as follows in SQL Server:

1 SELECT GETDATE();

You can write a query as follows in MySQL:

1 SELECT SYSTDATE();

5. Write a query to retrieve the first four characters of EmpLname from the
EmployeeInfo table.

1 SELECT SUBSTRING(EmpLname, 1, 4) FROM EmployeeInfo;

6. Write a query to fetch only the place name(string before brackets) from the
Address column of EmployeeInfo table.

Using the MID function in MySQL

1 SELECT MID(Address, 0, LOCATE('(',Address)) FROM EmployeeInfo;

Using SUBSTRING

1 SELECT SUBSTRING(Address, 1, CHARINDEX('(',Address)) FROM EmployeeInfo;

7. Write a query to create a new table which consists of data and structure
copied from the other table.

Using the SELECT INTO command:

1 SELECT * INTO NewTable FROM EmployeeInfo WHERE 1 = 0;

Using the CREATE command in MySQL:

1 CREATE TABLE NewTable AS SELECT * FROM EmployeeInfo;


8. Write q query to find all the employees whose salary is between 50000 to
100000.

SELECT * FROM EmployeePosition WHERE Salary BETWEEN '50000' AND


1
'100000';

9. Write a query to find the names of employees that begin with ‘S’

1 SELECT * FROM EmployeeInfo WHERE EmpFname LIKE 'S%';

10. Write a query to fetch top N records.

By using the TOP command in SQL Server:

1 SELECT TOP N * FROM EmployeePosition ORDER BY Salary DESC;


By using the LIMIT command in MySQL:

1 SELECT * FROM EmpPosition ORDER BY Salary DESC LIMIT N;

Q11. Write a query to retrieve the EmpFname and EmpLname in a single


column as “FullName”. The first name and the last name must be
separated with space.

1 SELECT CONCAT(EmpFname, ' ', EmpLname) AS 'FullName' FROM EmployeeInfo;


Q12. Write a query find number of employees whose DOB is between
02/05/1970 to 31/12/1975 and are grouped according to gender

SELECT COUNT(*), Gender FROM EmployeeInfo WHERE DOB BETWEEN '02/05/1970 ' AND
1
'31/12/1975' GROUP BY Gender;
Q13. Write a query to fetch all the records from the EmployeeInfo table
ordered by EmpLname in descending order and Department in the
ascending order.

To order the records in ascending and descnding order, you have to use the ORDER BY
statement in SQL.

1 SELECT * FROM EmployeeInfo ORDER BY EmpFname desc, Department asc;


Q14. Write a query to fetch details of employees whose EmpLname ends
with an alphabet ‘A’ and contains five alphabets.
To fetch details mathcing a certain value, you have to use the LIKE operator in SQL.

1 SELECT * FROM EmployeeInfo WHERE EmpLname LIKE '____a';


Q15. Write a query to fetch details of all employees excluding the
employees with first names, “Sanjay” and “Sonia” from the
EmployeeInfo table.

1 SELECT * FROM EmployeeInfo WHERE EmpFname NOT IN ('Sanjay','Sonia');


Q16. Write a query to fetch details of employees with the address as
“DELHI(DEL)”.

1 SELECT * FROM EmployeeInfo WHERE Address LIKE 'DELHI(DEL)%';


Q17. Write a query to fetch all employees who also hold the managerial
position.

1 SELECT E.EmpFname, E.EmpLname, P.EmpPosition


2 FROM EmployeeInfo E INNER JOIN EmployeePosition P ON
3 E.EmpID = P.EmpID AND P.EmpPosition IN ('Manager');
Q18. Write a query to fetch the department-wise count of employees
sorted by department’s count in ascending order.

1 SELECT Department, count(EmpID) AS EmpDeptCount


2 FROM EmployeeInfo GROUP BY Department
3 ORDER BY EmpDeptCount ASC;
Q19. Write a query to calculate the even and odd records from a table.

To retrieve the even records from a table, you have to use the MOD() function as
follows:

1 SELECT EmpID FROM (SELECT rowno, EmpID from EmployeeInfo) WHERE MOD(rowno,2)=0;
Similarly, to retrieve the odd records from a table, you can write a query as follows:

1 SELECT EmpID FROM (SELECT rowno, EmpID from EmployeeInfo) WHERE MOD(rowno,2)=1;
Q20. Write a SQL query to retrieve employee details from EmployeeInfo
table who have a date of joining in the EmployeePosition table.

1 SELECT * FROM EmployeeInfo E


2 WHERE EXISTS
3 (SELECT * FROM EmployeePosition P WHERE E.EmpId = P.EmpId);

Q21. Write a query to retrieve two minimum and maximum salaries from
the EmployeePosition table.
To retrieve two minimum salaries, you can write a query as below:
1 SELECT DISTINCT Salary FROM EmployeePosition E1
2 WHERE 2 >= (SELECTCOUNT(DISTINCT Salary)FROM EmployeePosition E2
3 WHERE E1.Salary >= E2.Salary) ORDER BY E1.Salary DESC;
To retrieve two maximum salaries, you can write a query as below:
1 SELECT DISTINCT Salary FROM EmployeePosition E1
2 WHERE 2 >= (SELECTCOUNT(DISTINCT Salary) FROM EmployeePosition E2
3 WHERE E1.Salary <= E2.Salary) ORDER BY E1.Salary DESC;
Q22. Write a query to find the Nth highest salary from the table without
using TOP/limit keyword.

1 SELECT Salary
2 FROM EmployeePosition E1
3 WHERE N-1 = (
4 SELECT COUNT( DISTINCT ( E2.Salary ) )
5 FROM EmployeePosition E2
6 WHERE E2.Salary > E1.Salary );
Q23. Write a query to retrieve duplicate records from a table.

1 SELECT EmpID, EmpFname, Department COUNT(*)


2 FROM EmployeeInfo GROUP BY EmpID, EmpFname, Department
3 HAVING COUNT(*) > 1;
Q24. Write a query to retrieve the list of employees working in the same
department.

1 Select DISTINCT E.EmpID, E.EmpFname, E.Department


2 FROM EmployeeInfo E, Employee E1
3 WHERE E.Department = E1.Department AND E.EmpID != E1.EmpID;
Q25. Write a query to retrieve the last 3 records from the EmployeeInfo
table.

1 SELECT * FROM EmployeeInfo WHERE


2 EmpID <=3 UNION SELECT * FROM
3 (SELECT * FROM EmployeeInfo E ORDER BY E.EmpID DESC)
4 AS E1 WHERE E1.EmpID <=3;
Q26. Write a query to find the third-highest salary from the EmpPosition
table.

1 SELECT TOP 1 salary


2 FROM(
3 SELECT TOP 3 salary
4 FROM employee_table
5 ORDER BY salary DESC) AS emp
6 ORDER BY salary ASC;
Q27. Write a query to display the first and the last record from the
EmployeeInfo table.

To display the first record from the EmployeeInfo table, you can write a query as follows:

1 SELECT * FROM EmployeeInfo WHERE EmpID = (SELECT MIN(EmpID) FROM EmployeeInfo);


To display the last record from the EmployeeInfo table, you can write a query as follows:

1 SELECT * FROM EmployeeInfo WHERE EmpID = (SELECT MAX(EmpID) FROM EmployeeInfo);


Q28. Write a query to add email validation to your database

SELECT Email FROM EmployeeInfo WHERE NOT REGEXP_LIKE(Email,


1 ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}’, ‘i’);
Q29. Write a query to retrieve Departments who have less than 2
employees working in it.

1SELECT DEPARTMENT, COUNT(EmpID) as 'EmpNo' FROM EmployeeInfo GROUP BY DEPARTMENT HAVING


COUNT(EmpD) < 2;
Q30. Write a query to retrieve EmpPostion along with total salaries paid
for each of them.

1 SELECT EmpPosition, SUM(Salary) from EmployeePosition GROUP BY EmpPosition;


Q31. Write a query to fetch 50% records from the EmployeeInfo table.

1 SELECT * FROM EmployeeInfo WHERE EmpID <= (SELECT COUNT(EmpID)/2 from EmployeeInfo);

Q32. How do you read the last five records from a database using a SQL
query?

To retrieve the last five records from a database using a SQL query, you can use the ORDER
BY clause combined with LIMIT. Here’s an example query:

SELECT *

FROM your_table

ORDER BY id DESC

LIMIT 5;

Q33. Write a SQL query that will provide you with the 10th-highest
employee salary from an Employee table.
Here’s an example SQL query:

SELECT salary

FROM (

SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_num

FROM Employee

) AS ranked_salary

WHERE row_num = 10;

JavaScript Interview Questions


JavaScript (JS) is the most popular lightweight scripting and interpreted
programming language. It was developed by Brendan Eich in 1995. It is
well-known as a scripting language for web pages, mobile apps, web servers, and
many more. It is an important language for aspiring front-end and back-end
developers.

1. What are the differences between Java and JavaScript?

JavaScript is a client-side scripting language and Java is object Oriented


Programming language. Both of them are totally different from each other.

● JavaScript: It is a light-weighted programming language (“scripting


language”) for developing interactive web pages. It can insert dynamic text
into the HTML elements. JavaScript is also known as the browser’s
language.

● Java: Java is one of the most popular programming languages. It is an


object-oriented programming language and has a virtual machine platform
that allows you to create compiled programs that run on nearly every
platform. Java promised, “Write Once, Run Anywhere”.

2. What are JavaScript Data Types?

There are three major Data types in JavaScript.

● Primitive
o Numbers
o Strings
o Boolean
o Symbol
● Trivial
o Undefined
o Null
● Composite
o Objects
o Functions
o Arrays
3. Which symbol is used for comments in JavaScript?

Comments prevent the execution of statements. Comments are ignored while the
compiler executes the code. There are two type of symbols to represent comments
in JavaScript:

● Double slash: It is known as a single-line comment.

// Single line comment

● Slash with Asterisk: It is known as a multi-line comment.

/*
Multi-line comments
...
*/

4. What would be the result of 3+2+”7″?

Here, 3 and 2 behave like an integer, and “7” behaves like a string. So 3 plus 2
will be 5. Then the output will be 5+”7″ = 57.

5. What is the use of the isNaN function?


The number isNan function determines whether the passed value is NaN (Not a
number) and is of the type “Number”. In JavaScript, the value NaN is considered a
type of number. It returns true if the argument is not a number, else it returns false.

6. Which is faster in JavaScript and ASP script?

JavaScript is faster compared to ASP Script. JavaScript is a client-side scripting


language and does not depend on the server to execute. The ASP script is a
server-side scripting language always dependable on the server.

7. What is negative infinity?

The negative infinity is a constant value represents the lowest available value. It
means that no other number is lesser than this value. It can be generate using a
self-made function or by an arithmetic operation. JavaScript shows the
NEGATIVE_INFINITY value as -Infinity.

8. Is it possible to break JavaScript Code into several lines?

Yes, it is possible to break the JavaScript code into several lines in a string
statement. It can be broken by using the backslash n ‘\n’.
For example:

console.log("A Online Computer Science Portal\n for Geeks")

The code-breaking line is avoid by JavaScript which is not preferable.

let gfg= 10, GFG = 5,


Geeks =
gfg + GFG;

9. What are undeclared and undefined variables?

1. Undefined: It occurs when a variable is declare not not assign any value.
Undefined is not a keyword.

2. Undeclared: It occurs when we try to access any variable which is not


initialize or declare earlier using the var or const keyword. If we use ‘typeof’
operator to get the value of an undeclare variable, we will face the runtime
error with the return value as “undefined”. The scope of the undeclare
variables is always global.

3. 11. Write a JavaScript code for adding new elements dynamically.


4. html

5. <!DOCTYPE html>
6. <html lang="en">
7. <head>
8. <title>Document</title>
9. </head>
10.
11. <body>
12. <button onclick="create()">
13. Click Here!
14. </button>
15.
16. <script>
17. function create() {
18. let geeks = document.createElement('geeks');
19. geeks.textContent = "Geeksforgeeks";
20. geeks.setAttribute('class', 'note');
21. document.body.appendChild(geeks);
22. }
23. </script>
24. </body>
25. </html>

10. What are global variables? How are these variables declared, and what are
the problems associated with them?

In contrast, global variables are the variables that define outside of functions.
These variables have a global scope, so they can be used by any function
without passing them to the function as parameters.
Example:
javascript
26. let petName = "Rocky"; // Global Variable
27. myFunction();
28.
29. function myFunction() {
30. console.log("Inside myFunction - Type of petName:", typeof
petName);
31. console.log("Inside myFunction - petName:", petName);
32. }
33.
34. console.log("Outside myFunction - Type of petName:", typeof petName);
35. console.log("Outside myFunction - petName:", petName);

Output
36. Inside myFunction - Type of petName: string
37. Inside myFunction - petName: Rocky
38. Outside myFunction - Type of petName: string
39. Outside myFunction - petName: Rocky
It is difficult to debug and test the code that relies on global variables.

11. What do you mean by NULL in JavaScript?


The NULL value represents that no value or no object. It is known as empty
value/object.

12. How to delete property-specific values?


The delete keyword deletes the whole property and all the values at once like

let gfg={Course: "DSA", Duration:30};


delete gfg.Course;

13. What is a prompt box?

The prompt box is a dialog box with an optional message prompting the user to
input some text. It is often used if the user wants to input a value before entering a
page. It returns a string containing the text entered by the user, or null.
14. What is the ‘this’ keyword in JavaScript?

Functions in JavaScript are essential objects. Like objects, it can be assign to


variables, pass to other functions, and return from functions. And much like
objects, they have their own properties. ‘this’ stores the current execution context
of the JavaScript program. Thus, when it use inside a function, the value of ‘this’
will change depending on how the function is defined, how it is invoked, and the
default execution context.

15. Explain the working of timers in JavaScript. Also elucidate the drawbacks
of using the timer, if any.

The timer executes some specific code at a specific time or any small amount of
code in repetition to do that you need to use the
functions setTimout, setInterval, and clearInterval. If the JavaScript code sets
the timer to 2 minutes and when the times are up then the page displays an alert
message “times up”. The setTimeout() method calls a function or evaluates an
expression after a specified number of milliseconds.

16. What is the difference between ViewState and SessionState?

● ViewState: It is specific to a single page in a session.

● SessionState: It is user specific that can access all the data on the web
pages.

17. How to submit a form using JavaScript?

You can use document.form[0].submit() method to submit the form in JavaScript.

18. Does JavaScript support automatic type conversion?

Yes, JavaScript supports automatic type conversion.

21. What are all the looping structures in JavaScript?

● while loop:

● for loop:

● do while:
22. Explain how to read and write a file using JavaScript?
The readFile() functions is used for reading operation.

readFile( Path, Options, Callback)

The writeFile() functions is used for writing operation.

writeFile( Path, Data, Callback)

23. What is called Variable typing in JavaScript ?

The variable typing is the type of variable used to store a number and using that
same variable to assign a “string”.

Geeks = 42;
Geeks = "GeeksforGeeks";

24. How to convert the string of any base to integer in JavaScript?

In JavaScript, parseInt() function is used to convert the string to an integer. This


function returns an integer of base which is specified in second argument of
parseInt() function. The parseInt() function returns Nan (not a number) when the
string doesn’t contain number.

25. Explain how to detect the operating system on the client machine?

To detect the operating system on the client machine, one can simply use
navigator.appVersion or navigator.userAgent property. The Navigator appVersion
property is a read-only property and it returns the string that represents the version
information of the browser.

26. What are the types of Pop up boxes available in JavaScript?

There are three types of pop boxes available in JavaScript.

● Alert
● Confirm
● Prompt
27. What is the difference between an alert box and a confirmation box?

An alert box will display only one button which is the OK button. It is used to
inform the user about the agreement has to agree. But a Confirmation box displays
two buttons OK and cancel, where the user can decide to agree or not.

28. What is the disadvantage of using innerHTML in JavaScript?

There are lots of disadvantages of using the innerHTML in JavaScript as the


content will replace everywhere. If you use += like “innerHTML = innerHTML +
‘html’” still the old content is replaced by HTML. It preserves event handlers
attached to any DOM elements.

29. What is the use of void(0) ?

The void(0) is used to call another method without refreshing the page during the
calling time parameter “zero” will be passed.

30. What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program
or a function in a “strict” operating context. This strict context prevents certain
actions from being taken and throws more exceptions. The statement “use strict”
instructs the browser to use the Strict mode, which is a reduced and safer feature
set of JavaScript.

31. How to get the status of a CheckBox?


The DOM Input Checkbox Property is used to set or return the checked status of a
checkbox field. This property is used to reflect the HTML Checked attribute.

document.getElementById("GFG").checked;

If the CheckBox is checked then it returns True.

32. How to explain closures in JavaScript and when to use it?


The closure is created when a child functions to keep the environment of the
parent’s scope even after the parent’s function has already executed. The Closure is
a locally declared variable related to a function. The closure will provide better
control over the code when using them.
JavaScript
// Explanation of closure
function foo() {
let b = 1;
function inner() {
return b;
}
return inner;
}
let get_func_inner = foo();

console.log(get_func_inner());
console.log(get_func_inner());
console.log(get_func_inner());

Output
1
1
1

33. What is the difference between call() and apply() methods ?


Both methods are used in a different situation
● call() Method: It calls the method, taking the owner object as argument. The
keyword this refers to the ‘owner’ of the function or the object it belongs to. We
can call a method that can be used on different objects.
● apply() Method: The apply() method is used to write methods, which can be
used on different objects. It is different from the function call() because it takes
arguments as an array.

34. How to target a particular frame from a hyperlink in JavaScript ?


This can be done by using the target attribute in the hyperlink. Like

<a href="/geeksforgeeks.htm" target="newframe">New Page</a>

35. Write the errors shown in JavaScript?


There are three different types of errors in JavaScript.
● Syntax error: A syntax error is an error in the syntax of a sequence of
characters or tokens that are intended to be written in a particular programming
language.
● Logical error: It is the most difficult error to be traced as it is the error on the
logical part of the coding or logical error is a bug in a program that causes to
operate incorrectly and terminate abnormally.
● Runtime Error: A runtime error is an error that occurs during the running of
the program, also known as an exception.

36. What is the difference between JavaScript and Jscript?


JavaScript
● It is a scripting language developed by Netscape.
● It is used to design client and server-side applications.
● It is completely independent of Java language.
Jscript
● It is a scripting language developed by Microsoft.
● It is used to design active online content for the word wide Web.

37. What does var myArray = [[]]; statement declares?


In JavaScript, this statement is used to declare a two-dimensional array.

38. How many ways an HTML element can be accessed in JavaScript code?
There are four possible ways to access HTML elements in JavaScript which are:
● getElementById() Method: It is used to get the element by its id name.
● getElementsByClass() Method: It is used to get all the elements that have the
given classname.
● getElementsByTagName() Method: It is used to get all the elements that have the
given tag name.
● querySelector() Method: This function takes CSS style selector and returns the
first selected element.

39. What is the difference between innerHTML & innerText?


The innerText property sets or returns the text content as plain text of the specified
node, and all its descendants whereas the innerHTML property sets or returns the
plain text or HTML contents in the elements. Unlike innerText, inner HTML lets
you work with HTML rich text and doesn’t automatically encode and decode text.

40. What is an event bubbling in JavaScript?


Consider a situation an element is present inside another element and both of them
handle an event. When an event occurs in bubbling, the innermost element handles
the event first, then the outer, and so on.
1. What is JavaScript?

JavaScript is a lightweight, interpreted, object-oriented scripting language. It


allows you to build interactivity into static HTML pages. Netscape, Internet
Explorer, and other web browsers include the language's general-purpose core.

2. What are the benefits of JavaScript over other web-based technologies?

These are the benefits of JavaScript:

1) Interactive Enhancement

2) JavaScript interacts with static web pages and makes them respond to users'
inputs.

3) Quick Feedback

4) There is no reason for a page on the internet to load again when using
JavaScript. For example, form input validation.

5) Rich User Interface

6) JavaScript assists in making the user interface of web-based


applications look and feel better.

7) Frameworks

8) JavaScript has vast libraries and frameworks that can be widely used to
develop games and web-based applications.

3. What are the features of JavaScript?

These are some of the features of JavaScript:

● Cross-platform compatible

● Open-source

● Object-oriented

● Integration with various front-end and back-end technologies


4.When should generators be used in ES6?

Generators in ES6 can be used in two main scenarios:

When one wants to move out of a function, one can do so using generators, and the
outer code determines when to move back into the function.

With the help of generators, one can control an asynchronous call outside the code.
Most importantly, though, the next value can come in only when needed; all values
do not need to come back at once

5. Why are promises used in JavaScript?

Promises help in managing asynchronous operations, such as server requests in


JavaScript. Earlier, callbacks were used for the same purpose. However, callbacks
have limited functionality and, thus, can make the code unmanageable. There are
four states of the promise object:

Pending: This is the first state of the promise and shows that the promise has been
neither fulfilled nor rejected.

Fulfilled: This state represents the completion of the asynchronous operation. In


other words, the promise has been fulfilled.

Rejected: This state represents the failure of the asynchronous operation due to
some reason. In other words, the promise has been rejected.

Settled: This is the last state of the promise, showing that the promise has been
either fulfilled or rejected.

A promise constructor uses a callback with two parameters - resolve and reject - to
create a promise. The resolve function is called when the asynchronous operation
has succeeded. The reject function is called when the asynchronous operation has
failed.

6. What are the different data types present in JavaScript?

There are three major data types present in JavaScript.

Primitive
● Numbers

● Strings

● Boolean

Composite

● Objects

● Functions

● Arrays

Trivial

● Null

● Undefined

7. Why are Arrow functions used almost everywhere?

Arrow functions are used everywhere because:

● Safety of scope: When the arrow function is used everywhere, it brings


consistency of scope because the same thisObject is used everywhere. If by
any chance, a standard function is used alongside the arrow function, there
are chances of the scope getting mixed up.

● Compactness: As compared to the standard function, the arrow function is


compact as it does away with the need for keywords, curly braces,
parenthesis, etc. in certain cases. It is, therefore, easier to read and write.

● Clarity: When the arrow function is used everywhere, there is a certain


consistency of scope. Thus, whenever a standard function is mixed with it, it
stands out distinctly. The developer can therefore look for the next higher
function to locate the thisObject.
8. Is JavaScript a dynamically typed or statically typed language?

JavaScript is a dynamically typed language.

9. Describe Arrow functions.

The ES6 Javascript version introduced Arrow functions. With the Arrow functions,
we can declare functions using new and shorter syntax. These functions can only
be used as function expressions. The declaration of these functions is done without
using the function keyword. Moreover, if there is a single returning expression,
then even the return keyword is not needed. Additionally, wherever the code occurs
in a single line only, we can omit the curly {} braces. If there is only one argument
in a function, then we can omit even the () parenthesis.

10. What are the main differences between Java and JavaScript?

Java is a general-purpose programming language that is class-based, whereas


JavaScript is an interpreted scripting language. Java is used to create complete
applications that may run on a single computer or be distributed among servers and
clients in a network. JavaScript is used to create interactive webpages that may
respond to user actions.

11. Which company developed JavaScript?

The language was developed by Brenden Eich in 1995 when he was working as an
employee of netscape. He is also the founder of Mozilla foundation.

12. What are classes in Javascript?

Classes in Javascript are templates for building objects. Classes bind the data with
code so that the data works as per the code. They were introduced in the ES6
version of Javascript and while they were created on prototypes, they also have
syntax and semantics that are not common with ES5. Classes can be seen as special
functions. There are two components of class syntax: class expressions and class
declarations.

Class expressions are one of the ways to define classes. They may or may not have
names. If a class expression has a name, it is held locally in the class body but can
be accessed through the name property. Before using class expressions, one must
declare them.

Another way to define classes is class declaration. For declaring a class, the class
keyword must be followed by the class name.

One class may use the properties of methods of another class by using the extend
keyword. Classes in Javascript must follow the strict mode. If the strict mode is not
followed, errors will appear.

13. Explain rest parameter and spread operator.

The ES6 version of Javascript introduced the rest parameter and spread operator.

Rest Parameter

The use of three dots (...) before any parameter shows a rest parameter. This
improves the handling of function parameters. With the help of the rest parameter,
we can create such functions that can take a different number of arguments. By
using the rest parameter, all these arguments will be converted into arrays. The rest
parameter can also be used to extract any or all parts of an argument.

Spread Operator

Though the spread operator syntax is the same as that of the rest parameter, the
spread operators help to spread arrays and object literals. Another use of spread
operators is when one or more arguments are expected to be in a given function
call. So, while the rest parameter creates an array, a spread operator spreads an
array.

14. How can you create objects in JavaScript?

Because JavaScript is fundamentally an object-oriented scripting language, it


encourages and supports using objects when developing web-based applications.
15. How can you make arrays in JavaScript?

Here's a simple method to create arrays with JavaScript using the array literal:

16.What is object destructuring?

Object destructuring is a JavaScript feature to extract object properties and bind


these properties to variables. It can be used to extract several properties in a single
statement and can reach properties from nested objects. When no property exists,
object destructuring can set default values.

17. Which is faster, JavaScript or ASP script?

JavaScript is faster than ASP script, as it is a lightweight language that is designed


to run quickly in the browser. However, ASP script can perform more complex
tasks that JavaScript cannot, so it can be faster in certain situations.

18. Explain temporal dead zone.

Temporal dead zone (TDZ) was introduced for the first time in the ES6 version of
JavaScript. TDZ is a behavior that occurs when a variable is accessed before it is
initialized. It is a language construct that helps to catch errors as accessing data
before initializing it is incorrect. When let and const keywords are used to declare
variables a TDZ may occur.

19. What is WeakMap in JavaScript?

WeakMap object stores key-value pairs with weakly referenced keys. Keys in
WeakMap must only be objects, while values can be arbitrary. Primitive data types
cannot be keys in WeakMap. Since native WeakMap contains weakly referenced
keys, these keys can be garbage collected and therefore references get removed.
Also, because of the weak referencing, garbage collection of values in WeakMap is
not prevented. When information about a key is valuable ‘only if’ the key is not
garbage collected, WeakMap is useful in mapping keys to the information about
them.

20. What are the rules for naming a variable in JavaScript?

The following are the conventions for naming variables in JavaScript:

● Variable names should not be identical to the reserved keywords. For


example, var, let, const, etc.

● Variable names can't start with a numeric value. They should only begin with
the letter or underscore character.

● Variable names have a case-sensitive nature.

21. What is WeakSet in Javascript?

WeakSet in Javascript is a collection of unique and orderly objects. Unlike Set, a


WeakSet does not contain any other elements. Those objects of a collection that are
weakly held, appear in WeakSet. This also means that if there is no reference for a
weakly held object, it will be collected as garbage. There are three methods of
WeakSet: add(), delete(), and has().

22. What is Callback in JavaScript?

In JavaScript, the functions are objects that can take different functions as
arguments and be returned by other functions. A callback is a JavaScript function
passed to another function as an argument, or parameter. This function is executed
when the function that it is passed to gets executed.
23. How to debug JavaScript code?

Modern web browsers, such as Chrome, Firefox, etc., include a built-in debugger
that can be opened anytime by pressing the appropriate key, typically the key F12.

24. What is Negative Infinity?

The negative infinity is a constant value that represents the lowest available value.
This means that no number is less than this value. Negative Infinity is calculated
by dividing a negative number by zero.

25. Which character is used to split JavaScript Code spanning into multiple lines?

The backslash, '' character, is used at the end of the first line if the JavaScript code
is spread across multiple lines.

26. What are the undeclared and undefined variables in JavaScript?

Undeclared variables are variables that do not exist in the program and therefore
are not declared. If a program attempts to determine the values of an undefined
variable, it will fail because of a runtime error.

Undefined variables refer to ones declared by the program but not given a value. If
the program attempts to find the values of an undefined variable the variable is
returned with an undefined value.

27. Explain global variables in JavaScript.

A variable declared outside of a function definition is referred to as a global


variable, and its scope is across your entire program. This implies that its value is
accessible and adjustable throughout your program.

28. What does the prompt box mean in JavaScript?

It displays an interactive dialog box that displays an optional prompt for users to
enter some text. It is typically used when users want to enter a number before
entering a webpage. This returns either a string containing the user's input text or a
null.
29. What is NULL in JavaScript?

The NULL value signifies no value or no object. It is also known as an empty


value or empty object.

30. What is the "this" keyword in JavaScript?

"this" refers to an object running the current line of code. It is a reference to the
object which executes the current function. If the function that is being referenced
is a regular one, "this" references the global object. If the function is a method of
the object, "this" refers to the object itself.

31. Define the purpose of timers in JavaScript.

Timers can be used to execute the code at an exact time or repeat the code within
an interval. This can be accomplished by employing the methods setTimeout,
setInterval, and clearInterval.

32. Which character is used to denote a comment?

The // character is for single-line comments, and the /* */ characters are used for
multi-line comments.

33. Differentiate between ViewState and SessionState?

ViewState: It is specific to the page state within the browser in a session.

SessionState: It's user-specific containing the data of the user session and allows
access to all data on the web pages.

34. What is the use of the === operator?

The === operator is a strict comparison operator, meaning it checks for both the
value and the type of two variables.

35. Does JavaScript support automatic type conversion?

JavaScript supports automatic type conversion. This is the most common method
of type conversion that JavaScript developers use.
36. Define Variable Typing in JavaScript.

Variable typing allows you to assign a numerical value to a variable. The same
variable could be assigned to a string.

37. What is the main difference between "==" and "===" in JavaScript?

== tests only for value equality; however, "===" is a stricter equality test that
returns false if the value or the type of two variables is different.

38. How to find the operating system in the client machine using JavaScript?

To detect the operating system, we can use a navigator.appVersion or


navigator.userAgent property in JavaScript.

39. What's the purpose of the delete operator in JavaScript?

Delete operator is used to delete the property and its value.

40. List all Pop-up box types in JavaScript.

The pop-up boxes available in JavaScript are Alert, Confirm, and Prompt.

41. What is the use of Void(0)?

Void(0) stops pages from refreshing, and "zero" is used to pass the parameter while
calling.

42. Differentiate between an alert box and a confirmation box.

An alert box shows only one button, an OK button. A confirmation box has two
buttons: the OK and Cancel buttons.

43. Define escape characters.

In JavaScript, escape characters are used to represent special characters within a


string. Escape characters start with a backslash followed by a character. The
character that follows the backslash determines the special character being
represented.
44. Explain JavaScript Cookies.

Cookies are small text files saved on the computer. They are created to store the
required information when users browse the website. Examples include Users
Name information and information about shopping carts from previous visits.

45. Explain the purpose of the pop() method.

This pop() method works like the shift() method. However, the difference is the
shift method operates from the beginning of the array. The pop() method takes the
final element off of the given array and returns it. The array upon which it is called
is then altered.

46. What are break and continue statements?

A break statement is a way to exit the current loop. The continue statement
continues with the next statement of the loop.

47. What's the purpose of the blur function in JavaScript?

The blur function removes the focus from the specified object.

48. How to create Generic objects in JavaScript?

Generic objects can be created by:

Looking for remote developer job at US companies?

INTERMEDIATE JAVASCRIPT INTERVIEW QUESTIONS

1. What is the outcome of 4+2+"8"?

The 4 and 2, in this case, behave as integers, and "8" behaves like a string.
Therefore 4 + 2 equals 6. The output is 6+"8" = 68.

2. What keywords are used to handle the exceptions?


The keywords commonly used to handle exceptions are: try, catch, finally, throw,
and throws.

3. How to print screen in JavaScript?

By calling the window.print() method in the browser, we can print the content of
the current window in JavaScript.

4. How to submit a form using JavaScript?

By using document.form[0].submit(), you can submit a form using JavaScript.

5. What are the looping structures in JavaScript?

while loop: A while loop control flow statement that allows code to run repeatedly
in response to a Boolean condition. The while loop is considered a repeated if
statement.

for loop: A for loop offers an easy structure to write. In contrast to a while loop, for
statement combines an initialization process, condition, and increment/decrement
in one line, thereby giving a simpler, easier-to-understand looping structure.

do while: A do-while loop can be like a while loop, but with the exception that it
examines the condition after executing the statements, which is why it's an instance
of the Exit Control Loop.

6. How to read a cookie?

The process of reading a cookie with JavaScript is also very easy. We can use the
document.cookie string to store the cookies we have just created with the string.

The document.cookie string stores a list of name-value pairs separated by


semicolons. The "name" is the name given to the cookie, and the "value" is its
value. You can also employ split() method to split the value of the cookie into
values and keys.

7. How to delete a cookie using JavaScript?

If you'd like to delete a cookie, so that future attempts to read it in JavaScript return
nothing, then you must change the date of expiration to a date in the past. Defining
the cookie's path is important to ensure you erase the correct cookie. Certain
browsers won't allow you to delete a cookie if the path is not specified.

8. How to create cookies using JavaScript?

To create cookies using JavaScript, you must assign a string value to the
document.cookie object.

9. What is the main difference between Attributes and Property?

Attributes- It provides more details on an element like id, type, value, etc.

Property- The value assigned to the property such as type="text" value='Name'.

10. How an HTML element is accessible in JavaScript code?

Here are the methods by which an HTML element can be used in JavaScript code:

getElementById('idname'): Gets an element by its ID name

getElementsByClass('classname'): Gets all the elements that have the given class
name.

getElementsByTagName('tagname'): Gets all the elements with the given tag name.

querySelector(): It returns the first selected element using a CSS style selector.

11. In what ways a JavaScript code can be involved in an HTML file?

There are three ways that a JavaScript code can be used in the HTML file: Inline,
Internal, and External.

Inline JavaScript
Internal JavaScript

External JavaScript

12. What is unshift method in JavaScript?

It's used to add elements to the front of the array and provides the updated length
of the array. It's similar to a push method, which inserts elements at the beginning
of the array.
13. What is a Typed language?

Typed Language is where the datatype is defined which is interpreted by the


machine at runtime.The typed language can be classified into two types:

Dynamically: In this case, the variable could contain multiple types; just like in JS
variables, a variable can be a number or characters.

Statically: In this case, the variable can only hold one data type. Like Java, the
variable declared of string can hold only one set of characters.

14. Name some JavaScript frameworks.

JavaScript framework is an application framework written using JavaScript. In its


control flow, it is different from a JavaScript Library. There are many JavaScript
frameworks, but the most popular are: Angular, Node, Bootstrap, and Vue among
others.

15. What is the difference between Local storage & Session storage?

Local Storage: The data is not transmitted directly to the server with each HTTP
request (HTML, images, JavaScript, CSS, etc), thus reducing the traffic between
the server and the client. It remains until removed manually through settings or
software.

Session Storage: It is identical to local storage; the only difference is that while the
data stored locally does not expire, whereas in session storage, it is deleted when
the session is over. Session Storage is removed once the browser closes.

16. What's the difference between a window and a document?

JavaScript window can be described as a global object that contains properties and
methods that interact with it.

The document is a part of the window and is considered as the property of the
window.

17. What's the distinct difference between innerText and innerHTML?


innerHTML - innertHTML returns the entire text, including the HTML tags, that
are contained within an element.

innerText - innerText returning the entire text that is contained within an element as
well as its child elements.

18. How to convert the string of a base to an integer using JavaScript?

This parseInt() function can convert numbers between different bases. This
function returns an integer of a base specified in the second argument of the
parseInt() method.

19. What are Exports and Imports?

Imports and exports allow the writing of modular JavaScript code. With the help of
exports and imports, we can break the code into multiple files.

20. What is the 'Strict' Mode in JavaScript?

Strict Mode in JavaScript is a way to opt into a restricted variant of the language,
which enforces stricter parsing and error handling rules. It helps developers write
more secure and efficient code by catching common mistakes and potential bugs
that might otherwise go unnoticed.

When enabled, Strict Mode may throw errors for code that previously worked
without any issues, but it does so in order to catch potential issues that could lead
to bugs or security vulnerabilities. Strict Mode also disables some features of
JavaScript that could be problematic or confusing, such as the automatic creation
of global variables.

Overall, Strict Mode is a useful tool for writing safer and more reliable JavaScript
code, but it requires developers' care and attention to use effectively.

21. What is the difference between let and var?

Let and var are utilized for method and variable declarations within JavaScript.
The primary difference between them is the scope in which these variables are
used. The variables that are declared using ‘Let’ are only used within the block
where they are declared. The variables declared by ‘Var’ are available across the
function where they are declared.
22. Demonstrate the importance of isNaN() function in JavaScript.

The isNaN() function is used to determine whether the given value is an illegal
number or not. If it returns true, the value is a NaN - Not a number. Else returns
false. It differs from the Number.isNaN() method.

23. What are the types of errors found in JavaScript?

JavaScript has three types of errors: Runtime, Logical, and Syntax.

Syntax errors- These occur when the code violates the rules of the JavaScript
language. For example, a missing semicolon, an unclosed string, or an unexpected
token.

Logical errors - These occur when the code does not produce the desired outcome,
but there is no error message displayed. Logical errors are usually caused by
mistake in the code's logic or algorithm.

Runtime errors- These occur when the code is syntactically correct and logically
sound, but still throws an error during execution. For example, accessing an
undefined variable, calling a function that does not exist, or attempting to divide by
zero.

ADVANCED JAVASCRIPT INTERVIEW QUESTIONS AND ANSWERS

1. How would you go about debugging a JavaScript program that is not


running correctly?

The first step to debugging a JavaScript program is to identify the error. This can
be done by using the JavaScript console in the browser’s developer tools. The
console will display any errors that occur during script execution such as syntax
errors, type errors, and reference errors. Once the error has been identified, the
code can be examined line by line to find the source of the issue and the issue can
be addressed.

2. How would you create a function that takes two numbers and adds them
together?
To create a function that takes two numbers and adds them together, you can use
the following code snippet:

3. Which method extracts a character from a certain index?

We can retrieve a character from a certain index using the charAt() function.

4. How do you create a for loop in JavaScript?

A for loop in JavaScript takes 3 parameters (initialization, condition, and


increment/decrement) and contains a block of code that is executed until the
condition is met. For example:

5. What is the design prototype pattern?

The Prototype design Pattern is described as a property pattern or prototype pattern


that can be used to create different objects and prototypes that are copied using a
template with specific values.
The key idea behind the Prototype Pattern is to use an existing object as a template
and create new instances by copying its properties. This approach can be more
efficient than creating new instances from scratch, especially if the object has a
complex initialization process. By copying an existing object, we can avoid the
need to repeat the initialization process for every new object that we create.

6. How is the Temporal Dead Zone defined?

AIt is an area of block where a variable cannot be accessed until it is completely


initialized with a value by the computer. Incase, one tries to access it before
complete initialization, JavaScript throws “ReferenceError”. It is defined using
const and let keywords.

7. What is the difference between the methods .map() and .forEach() in


JavaScript?

The .map() and .forEach() methods are both used to iterate over an array, but the
.map() method can be used to transform an array by returning a new array with the
same number of elements but with different values. The .forEach() method is used
to perform an action on each element in the array without returning a new array.
For example:
8. How would you go about creating a method that returns the sum of all the
elements in an array?

To create a method that returns the sum of all the elements in an array, you can use
the Array.prototype.reduce() method. For example:

9. How to change style/class of an element?

The style/class of an element can be changed in two ways.

document.getElementById("myText").style.fontSize = "14px;

document.getElementById("myText").className = "anyclass";

10. How can you get rid of duplicates from a JavaScript array?

There are two ways we can eliminate duplicates from the JavaScript array:

Through the Filter Method:

The filter() method can use three arguments: arrays, current element, and the
current element's index.

Utilizing the For Loop

The For loop involves iterating through the original array and checking whether
each element has already been added to a new array. If it hasn't, the element is
added; if it has, it is skipped.
11. Explain how to read and write a file using JavaScript?

For reading operations, the readFile() function is used.

readFile( Path, Options, Callback)

For writing operations,The writeFile() functions is used.

writeFile( Path, Data, Callback)

12. How can you target a particular frame from a hyperlink in JavaScript?

This can be done by using the target attribute in the hyperlink. Like

13. What is the main difference between JavaScript and JScript?

JavaScript:

● It is a scripting programming language created by Netscape.

● This is utilized to develop the server and client-side software.

● It is independent of Java language.

JScript:

● This is a scripting language created by Microsoft.

● It's used to create interactive online content.

14. How can we hide JavaScript code from old browsers that don't support
JavaScript?

To hide the JavaScript codes from old browsers that do not have support for
JavaScript, you can make use of:
The majority of browsers from the past will consider it as a long comment of
HTML. New browsers that support JavaScript will treat it as an online message.
Alternatively, you could use the "noscript" element to provide alternative content
that will display for users who do not have JavaScript enabled.

15. Can you explain the usage of Internal and External JavaScript Code?

When there are only a few lines of code for a particular webpage, it is preferable to
keep JavaScript code internal within the HTML document.
However, if the JavaScript code is used on multiple web pages, it is advisable to
keep the code in a separate file.

17. Write a sample code for JavaScript multiplication table.


18. What do you know about unescape() and escape() functions?
The escape () function codes a string to transfer the information across a network from one
system to another. Example The unescape() function decodes the coded string.

19. Write a code to explain how unshift() works?

20. Can you explain what screen objects are?

Screen objects read the information from the screen of the client. Some properties
of screen objects are

● AvailHeight: Provides the height of the screen

● AvailWidth: Provides the width of the screen

● ColorDepth: Provides the bit depth of images on the screen

● Height: Provides the total height of the screen along with the taskbar

● Width: Provides the total width of the screen, including the taskbar

21. Explain different functional components in JavaScript?

The functional components in JavaScript are-


First-class functions: functions are used as first-class objects. This means they can
be passed as arguments to other functions, sent back as values from other
functions, assigned to variables, or can even be saved as data structures.

Nested functions: These are defined inside other functions and called every time
the main function is called.

22. Explain deferred scripts in JavaScript.

When the page loads, HTML code parsing is paused by default till the time the
script has not fully executed. this happens when the server is slow or the script is
heavy, and the web page gets delayed. So by using Deferred script , scripts
execution is delayed till the HTML parser rums. this helps reduce the loading time
of web pages and they can be displayed faster.

23. Explain how event handlers are used in JavaScript.

Whenever the user clicks the link or fills out a form, events take place. Events are
the actions that come off as a result of activities. An event handler serves to
manage the proper execution of all these events. They are an extra attribute if the
object which includes the vent's name and action is taken when the event takes
place.

24. Explain how DOM is utilized in JavaScript.

Document Object Model (DOM) is how different objects in a document interact


with each other. It is used for developing web pages that include objects like
paragraphs, links, etc. These Objects can be made to perform actions like add or
delete. Also, it adds extra abilities to a web page.

25. How would you define a class in JavaScript?

To define a class in JavaScript, you can use the class keyword. For example:
26. Explain event bubbling.

In JavaScript, DOM elements can be nested inside each other.


Now, in such cases, when the handler of the child is clicked, the handler associated
with the parent will also work.

27. Define window.onload and onDocumentReady.

Window.onload is an event that is fired when the page has finished loading. This
event is often used to perform tasks that need to be done after the page has loaded,
such as setting up event handlers, initializing components, or making AJAX
requests.

On the contrary, onDocumentReady is an event that is fired when the page's HTML
document is ready to be interacted with. This event is often used to perform tasks
that need to be done when the page is ready, such as setting up event handlers,
initializing components, or making AJAX requests.

28. How to get the status of a CheckBox?

The following syntax is used


alert(document.getElementById('checkbox1').checked);

29. How can you append a value to an array?

We can append a value to an array by


arr[arr.length] = value;

You might also like