Operating System Interview
Questions
To view the live version of the
page, click here.
© Copyright by Interviewbit
Contents
Basic OS Interview Questions
1. Why is the operating system important?
2. What's the main purpose of an OS? What are the different types of OS?
3. What are the benefits of a multiprocessor system?
4. What is RAID structure in OS? What are the different levels of RAID configuration?
5. What is GUI?
6. What is a Pipe and when it is used?
7. What are the different kinds of operations that are possible on semaphore?
8. What is a bootstrap program in OS?
9. Explain demand paging?
10. What do you mean by RTOS?
11. What do you mean by process synchronization?
12. What is IPC? What are the different IPC mechanisms?
13. What is different between main memory and secondary memory.
14. What do you mean by overlays in OS?
15. Write top 10 examples of OS?
Intermediate OS Interview Questions
16. What is virtual memory?
17. What is thread in OS?
18. What is a process? What are the different states of a process?
Page 1                                                         © Copyright by Interviewbit
                                                   Operating System Interview Questions
Intermediate OS Interview Questions                                   (.....Continued)
19. What do you mean by FCFS?
20. What is Reentrancy?
21. What is a Scheduling Algorithm? Name different types of scheduling algorithms.
22. What is the difference between paging and segmentation?
23. What is thrashing in OS?
24. What is the main objective of multiprogramming?
25. What do you mean by asymmetric clustering?
26. What is the difference between multitasking and multiprocessing OS?
27. What do you mean by Sockets in OS?
28. Explain zombie process?
29. What do you mean by cascading termination?
30. What is starvation and aging in OS?
Advanced OS Interview Questions
31. What do you mean by Semaphore in OS? Why is it used?
32. What is Kernel and write its main functions?
33. What are different types of Kernel?
34. Write difference between micro kernel and monolithic kernel?
35. What is SMP (Symmetric Multiprocessing)?
36. What is a time-sharing system?
Page 2                                                        © Copyright by Interviewbit
                                                    Operating System Interview Questions
Advanced OS Interview Questions                                        (.....Continued)
37. What is Context Switching?
38. What is difference between Kernel and OS?
39. What is difference between process and thread?
40. What are various sections of the process?
41. What is a deadlock in OS? What are the necessary conditions for a deadlock?
42. What do you mean by Belady’s Anomaly?
43. What is spooling in OS?
Page 3                                                         © Copyright by Interviewbit
Let's get Started
What do you mean by an operating system? What are its basic
functions?
Operating System (OS) is basically a so ware program that manages and handles all
resources of a computer such as hardware and so ware. The first OS was introduced
in the early 1950s known as GMOs. An OS is responsible for managing, handling, and
coordinating overall activities and sharing of computer resources. It acts as an
intermediary among users of computer and computer hardware.
Functions of OS:
There are many functions of the OS. Some of the important functions of OS are given
below:
Page 4                                                        © Copyright by Interviewbit
                                                      Operating System Interview Questions
     Memory and Processor Management
     Providing user interface to users
     File Management and Device Management
     Scheduling of resources and jobs
     Error Detection
     Security
Basic OS Interview Questions
1. Why is the operating system important?
OS is the most essential and vital part of a computer without which it is considered
useless. It enables an interface or acts like a link for interaction between computer
so ware that is installed on OS and users. It also helps to communicate with
hardware and also maintains balance among hardware and CPU. It also provides
services to users and a platform for programs to run on. It performs all common tasks
applications require.
2. What's the main purpose of an OS? What are the different
   types of OS?
The main purpose of an OS is to execute user programs and make it easier for users
to understand and interact with computers as well as run applications. It is specially
designed to ensure that the computer system performs better by managing all
computational activities. It also manages computer memory, processes, and
operation of all hardware and so ware.
Types of OS:
     Batched OS (Example: Payroll System, Transactions Process, etc.)
     Multi-Programmed OS (Example: Windows O/S, UNIX O/S, etc.)
     Timesharing OS (Example: Multics, etc.)
     Distributed OS (LOCUS, etc.)
     Real-Time OS (PSOS, VRTX, etc.)
3. What are the benefits of a multiprocessor system?
Page 5                                                           © Copyright by Interviewbit
                                                       Operating System Interview Questions
A Multiprocessor system is a type of system that includes two or more CPUs. It
involves the processing of different computer programs at the same time mostly by a
computer system with two or more CPUs that are sharing single memory.
Benefits:
     Such systems are used widely nowadays to improve performance in systems
     that are running multiple programs concurrently.
     By increasing the number of processors, a greater number of tasks can be
     completed in unit time.
     One also gets a considerable increase in throughput and is cost-effective also as
     all processors share the same resources.
     It simply improves the reliability of the computer system.
4. What is RAID structure in OS? What are the different levels of
   RAID configuration?
RAID (Redundant Arrays of Independent Disks) is a method used to store data on
Multiple hard disks therefore it is considered as data storage virtualization
technology that combines multiple hard disks. It simply balances data protection,
system performance, storage space, etc. It is used to improve the overall
performance and reliability of data storage. It also increases the storage capacity of
the system and its main purpose is to achieve data redundancy to reduce data loss.
Different levels of RAID
Nowadays, RAID is available in various schemes or RAID level as given below:
Page 6                                                            © Copyright by Interviewbit
                                                       Operating System Interview Questions
     RAID 0 - Non-redundant striping: This level is used to increase the performance
     of the server.
     RAID 1 - Mirroring and duplexing: This level is also known as disk mirroring and is
     considered the simplest way to implement fault tolerance.
     RAID 2 - Memory-style error-correcting codes: This level generally uses dedicated
     hamming code parity I.e., a liner form of error correction code.
     RAID 3 - Bit-interleaved Parity: This level requires a dedicated parity drive to
     store parity information.
     RAID 4 - Block-interleaved Parity: This level is similar to RAID 5 but the only
     difference is that this level confines all parity data to a single drive.
     RAID 5 - Block-interleaved distributed Parity: This level provides far better
     performance than disk mirroring and fault tolerance.
     RAID 6 - P+Q Redundancy: This level generally provides fault tolerance for two
     drive failures.
5. What is GUI?
Page 7                                                            © Copyright by Interviewbit
                                                        Operating System Interview Questions
GUI (Graphical User Interface) is basically a type of user interface that allows users to
use graphics to interact with OS. GUI is created because it is more user-friendly, less
complex, and easier to understand rather than a command-line interface. Its main
goal is to increase efficiency and ease of use. Instead of having to memorize
commands, users can just click on a button to simply execute the procedure.
Examples of GUI include Microso Windows, macOS, Apple’s iOS, etc.
6. What is a Pipe and when it is used?
The pipe is generally a connection among two or more processes that are
interrelated to each other. It is a mechanism that is used for inter-process
communication using message passing. One can easily send information such as the
output of one program process to another program process using a pipe. It can be
used when two processes want to communicate one-way i.e., inter-process
communication (IPC).
7. What are the different kinds of operations that are possible
   on semaphore?
There are basically two atomic operations that are possible:
     Wait()
     Signal()
8. What is a bootstrap program in OS?
It is generally a program that initializes OS during startup i.e., first code that is
executed whenever computer system startups. OS is loaded through a bootstrapping
process or program commonly known as booting. Overall OS only depends on the
bootstrap program to perform and work correctly. It is fully stored in boot blocks at a
fixed location on the disk. It also locates the kernel and loads it into the main
memory a er which the program starts its execution.
Page 8                                                             © Copyright by Interviewbit
                                                      Operating System Interview Questions
9. Explain demand paging?
Demand paging is a method that loads pages into memory on demand. This method
is mostly used in virtual memory. In this, a page is only brought into memory when a
location on that particular page is referenced during execution. The following steps
are generally followed:
     Attempt to access the page.
     If the page is valid (in memory) then continue processing instructions as normal.
     If a page is invalid then a page-fault trap occurs.
     Check if the memory reference is a valid reference to a location on secondary
     memory. If not, the process is terminated (illegal memory access). Otherwise,
     we have to page in the required page.
     Schedule disk operation to read the desired page into main memory.
     Restart the instruction that was interrupted by the operating system trap.
10. What do you mean by RTOS?
Page 9                                                           © Copyright by Interviewbit
                                                     Operating System Interview Questions
Real Time Operating System (RTOS) is an operating system that is used for real-time
applications i.e., for those applications where data processing should be done in a
fixed and small measure of time. It performs much better on tasks that are needed to
be executed within a short time. It also takes care of execution, monitoring, and all-
controlling processes. It also occupies less memory and consumes fewer resources.
Types of RTOS:
     Hard Real-Time
     Firm Real-Time
     So Real-Time
RTOS is used in Air traffic control systems, Anti-lock Brake Systems, and Heart
pacemakers.
11. What do you mean by process synchronization?
Process synchronization is basically a way to coordinate processes that use shared
resources or data. It is very much essential to ensure synchronized execution of
cooperating processes so that will maintain data consistency. Its main purpose is to
share resources without any interference using mutual exclusion. There are two
types of process synchronization:
Page 10                                                         © Copyright by Interviewbit
                                                    Operating System Interview Questions
     Independent Process
     Cooperative Process
12. What is IPC? What are the different IPC mechanisms?
IPC (Interprocess Communication) is a mechanism that requires the use of resources
like a memory that is shared between processes or threads. With IPC, OS allows
different processes to communicate with each other. It is simply used for exchanging
data between multiple threads in one or more programs or processes. In this
mechanism, different processes can communicate with each other with the approval
of the OS.
Different IPC Mechanisms:
     Pipes
     Message Queuing
     Semaphores
     Socket
     Shared Memory
     Signals
13. What is different between main memory and secondary
    memory.
Main memory: Main memory in a computer is RAM (Random Access Memory). It is
also known as primary memory or read-write memory or internal memory. The
programs and data that the CPU requires during the execution of a program are
stored in this memory.
Secondary memory: Secondary memory in a computer are storage devices that can
store data and programs. It is also known as external memory or additional memory
or backup memory or auxiliary memory. Such storage devices are capable of storing
high-volume data. Storage devices can be hard drives, USB flash drives, CDs, etc.
Page 11                                                        © Copyright by Interviewbit
                                                 Operating System Interview Questions
          Primary Memory                 Secondary Memory
                                         Firstly, data is transferred to
          Data can be directly
                                         primary memory and a er
          accessed by the processing
                                         then routed to the processing
          unit.
                                         unit.
          It can be both volatile and
                                         It is non-volatile in nature.
          non-volatile in nature.
          It is more costly than         It is more cost-effective or less
          secondary memory.              costly than primary memory.
          It is temporary because        It is permanent because data
          data is stored temporarily.    is stored permanently.
                                         In this memory, data is stored
          In this memory, data can be
                                         permanently and therefore
          lost whenever there is a
                                         cannot be lost even in case of
          power failure.
                                         power failure.
          It is much faster than         It is slower as compared to
          secondary memory and           primary memory and saves
          saves data that is currently   different kinds of data in
          used by the computer.          different formats.
                                         It can be accessed by I/O
          It can be accessed by data.
                                         channels.
14. What do you mean by overlays in OS?
Page 12                                                     © Copyright by Interviewbit
                                                     Operating System Interview Questions
Overlays is basically a programming method that divides processes into pieces so
that instructions that are important and need can be saved in memory. It does not
need any type of support from the OS. It can run programs that are bigger in size than
physical memory by only keeping only important data and instructions that can be
needed at any given time.
15. Write top 10 examples of OS?
Some of the top OS’s that are used mostly are given below:
     MS-Windows
     Ubuntu
     Mac OS
     Fedora
     Solaris
     Free BSD
     Chrome OS
     CentOS
     Debian
     Android
Intermediate OS Interview Questions
16. What is virtual memory?
It is a memory management technique feature of OS that creates the illusion to users
of a very large (main) memory. It is simply space where a greater number of programs
can be stored by themselves in the form of pages. It enables us to increase the use of
physical memory by using a disk and also allows us to have memory protection. It can
be managed in two common ways by OS i.e., paging and segmentation. It acts as
temporary storage that can be used along with RAM for computer processes.
Page 13                                                         © Copyright by Interviewbit
                                                         Operating System Interview Questions
17. What is thread in OS?
Thread is a path of execution that is composed of a program counter, thread id,
stack, and set of registers within the process. It is a basic unit of CPU utilization that
makes communication more effective and efficient, enables utilization of
multiprocessor architectures to a greater scale and greater efficiency, and reduces
the time required in context switching. It simply provides a way to improve and
increase the performance of applications through parallelism. Threads are
sometimes called lightweight processes because they have their own stack but can
access shared data.
Multiple threads running in a process share: Address space, Heap, Static data, Code
segments, File descriptors, Global variables, Child processes, Pending alarms, Signals,
and signal handlers.
Each thread has its own: Program counter, Registers, Stack, and State.
Page 14                                                             © Copyright by Interviewbit
                                                    Operating System Interview Questions
18. What is a process? What are the different states of a
    process?
The process is basically a program that is currently under execution. The main
function of an OS is to manage and handle all of these processes. When a program is
loaded into the memory and it becomes a process, it can be divided into four
sections ─ stack, heap, text, and data. There are two types of processes:
  1. Operating System Processes
  2. User Processes
Page 15                                                        © Copyright by Interviewbit
                                                       Operating System Interview Questions
States of Process:
Different states of the process through which process goes are given below:
     New State: In this state, a process is just created.
     Running: In this state, the CPU starts working on the process’s instructions.
     Waiting: In this state, the process cannot run because it just waits for some
     event to occur
     Ready: In this state, the process has all resources available that are required to
     run but it waits to get assigned to a processor because CPUs are not working
     currently on instructions passed by the process.
     Terminate: In this state, the process is completed I.e., the process has finished
     execution.
19. What do you mean by FCFS?
Page 16                                                           © Copyright by Interviewbit
                                                        Operating System Interview Questions
FCFS (First Come First Serve) is a type of OS scheduling algorithm that executes
processes in the same order in which processes arrive. In simple words, the process
that arrives first will be executed first. It is non-preemptive in nature. FCFS scheduling
may cause the problem of starvation if the burst time of the first process is the
longest among all the jobs. Burst time here means the time that is required in
milliseconds by the process for its execution. It is also considered the easiest and
simplest OS scheduling algorithm as compared to others. Implementation of FCFS is
generally managed with help of the FIFO (First In First Out) queue.
20. What is Reentrancy?
Reentrant is simply a function in which various clients can use and shares a single
copy of a program during a similar period. This concept is generally associated with
OS code and does not deal with concurrency. It has two major functions:
     Program code cannot change or modify itself.
     Local data for every client process needs to be stored in different disks.
21. What is a Scheduling Algorithm? Name different types of
    scheduling algorithms.
A scheduling algorithm is a process that is used to improve efficiency by utilizing
maximum CPU and providing minimum waiting time to tasks. It simply deals with the
problem of deciding which of outstanding requests is to be allocated resources. Its
main aim is to reduce resource starvation and to ensure fairness amongst parties
that are utilizing the resources. In simple words, it is used to allocate resources
among various competing tasks.
Types of Scheduling Algorithm
There are different types of scheduling algorithms as given below:
Page 17                                                            © Copyright by Interviewbit
                                                   Operating System Interview Questions
22. What is the difference between paging and segmentation?
Paging: It is generally a memory management technique that allows OS to retrieve
processes from secondary storage into main memory. It is a non-contiguous
allocation technique that divides each process in the form of pages.
Segmentation: It is generally a memory management technique that divides
processes into modules and parts of different sizes. These parts and modules are
known as segments that can be allocated to process.
Page 18                                                       © Copyright by Interviewbit
                                                   Operating System Interview Questions
          Paging                       Segmentation
          It is invisible to a
                                       It is visible to a programmer.
          programmer.
          In this, the size of pages   In this, the size of segments is not
          is fixed.                    fixed.
          Procedures and data
                                       Procedures and data can be
          cannot be separated in
                                       separated in segmentation.
          paging.
          It allows a cumulative
                                       It allows all programs, data, and
          total of virtual address
                                       codes to break up into
          spaces to cross physical
                                       independent address spaces.
          main memory.
                                       It is mostly available on Windows
          It is mostly available on    servers that may support
          CPUs and MMU chips.          backward compatibility, while
                                       Linux has limited support.
          It is faster for memory
          access as compared to        It is slower as compared to paging.
          segmentation.
          In this, OS needs to         In this, OS needs to maintain a list
          maintain a free frame.       of holes in the main memory.
          In paging, the type of
                                       In segmentation, the type of
          fragmentation is
                                       fragmentation is external.
          internal.
          The size of the page is
                                       The size of the page is determined
          determined by
                                       by the user.
          available memory.
Page 19                                                       © Copyright by Interviewbit
                                                       Operating System Interview Questions
23. What is thrashing in OS?
It is generally a situation where the CPU performs less productive work and more
swapping or paging work. It spends more time swapping or paging activities rather
than its execution. By evaluating the level of CPU utilization, a system can detect
thrashing. It occurs when the process does not have enough pages due to which the
page-fault rate is increased. It inhibits much application-level processing that causes
computer performance to degrade or collapse.
24. What is the main objective of multiprogramming?
It refers to the ability to execute or perform more than one program on a single
processor machine. This technique was introduced to overcome the problem of
underutilization of CPU and main memory. In simple words, it is the coordination of
execution of various programs simultaneously on a single processor (CPU). The main
objective of multiprogramming is to have at least some processes running at all
times. It simply improves the utilization of the CPU as it organizes many jobs where
the CPU always has one to execute.
25. What do you mean by asymmetric clustering?
Page 20                                                           © Copyright by Interviewbit
                                                     Operating System Interview Questions
Asymmetric Clustering is generally a system in which one of the nodes among all
nodes is in hot standby mode whereas the rest of all nodes run different applications.
It simply uses whole or entire hardware resources therefore it is considered a more
reliable system as compared to others.
26. What is the difference between multitasking and
    multiprocessing OS?
Multitasking: It is a system that allows more efficient use of computer hardware.
This system works on more than one task at one time by rapidly switching between
various tasks. These systems are also known as time-sharing systems.
Page 21                                                         © Copyright by Interviewbit
                                                      Operating System Interview Questions
Multiprocessing: It is a system that allows multiple or various processors in a
computer to process two or more different portions of the same program
simultaneously. It is used to complete more work in a shorter period of time.
Page 22                                                          © Copyright by Interviewbit
                                                 Operating System Interview Questions
          Multitasking                     Multiprocessing
          It performs more than one        It performs more than one
          task at a time using a single    task at a time using multiple
          processor.                       processors.
          In this, the number of CPUs is   In this, the number of CPUs
          only one.                        is more than one.
          It is more economical.           It is less economical.
          It is less efficient than         It is more efficient than
          multiprocessing.                 multitasking.
          It allows fast switching among   It allows smooth processing
          various tasks.                   of multiple tasks at once.
          It requires more time to         It requires less time for job
          execute tasks as compared to     processing as compared to
          multiprocessing.                 multitasking.
27. What do you mean by Sockets in OS?
Page 23                                                     © Copyright by Interviewbit
                                                       Operating System Interview Questions
The socket in OS is generally referred to as an endpoint for IPC (Interprocess
Communication). Here, the endpoint is referred to as a combination of an IP address
and port number. Sockets are used to make it easy for so ware developers to create
network-enabled programs. It also allows communication or exchange of
information between two different processes on the same or different machines. It is
mostly used in client-server-based systems.
Types of Sockets
There are basically four types of sockets as given below:
     Stream Sockets
     Datagram Sockets
     Sequenced Packet Sockets
     Raw Sockets
28. Explain zombie process?
Zombie process, referred to as a defunct process, is basically a process that is
terminated or completed but the whole process control block is not cleaned up from
the main memory because it still has an entry in the process table to report to its
parent process. It does not consume any of the resources and is dead, but it still
exists. It also shows that resources are held by process and are not free.
29. What do you mean by cascading termination?
Cascading termination is a process termination in which if the parent process is
exiting or terminating then the children process will also get terminated. It does not
allow the child to continue processing as its parent process terminates. It is generally
initiated by OS.
30. What is starvation and aging in OS?
Page 24                                                           © Copyright by Interviewbit
                                                       Operating System Interview Questions
Starvation: It is generally a problem that usually occurs when a process has not been
able to get the required resources it needs for progress with its execution for a long
period of time. In this condition, low priority processes get blocked and only high
priority processes proceed towards completion because of which low priority
processes suffer from lack of resources.
Aging: It is a technique that is used to overcome the situation or problem of
starvation. It simply increases the priority of processes that wait in the system for
resources for a long period of time. It is considered the best technique to resolve the
problem of starvation as it adds an aging factor to the priority of each and every
request by various processes for resources. It also ensures that low-level queue jobs
or processes complete their execution.
Advanced OS Interview Questions
31. What do you mean by Semaphore in OS? Why is it used?
Semaphore is a signaling mechanism. It only holds one positive integer value. It is
simply used to solve the problem or issue of critical sections in the synchronization
process by using two atomic operations i.e., wait() and signal().
Types of Semaphore
There are usually two types of semaphores as given below:
     Binary Semaphore
     Counting Semaphore
Page 25                                                           © Copyright by Interviewbit
                                                      Operating System Interview Questions
          Binary Semaphore                          Mutex
          It allows various process threads         It allows various process
          to get the finite instance of the         threads to get single
          resource until resources are              shared resource only at
          available.                                a time.
                                                    Its functions are based
          Its functions are based upon
                                                    upon a locking
          signaling mechanisms.
                                                    mechanism.
                                                    Mutex is slower as
          Binary semaphores are much
                                                    compared to binary
          faster as compared to Mutex.
                                                    semaphores.
          It is basically an integer.               It is basically an object.
32. What is Kernel and write its main functions?
The kernel is basically a computer program usually considered as a central
component or module of OS. It is responsible for handling, managing, and
controlling all operations of computer systems and hardware. Whenever the system
starts, the kernel is loaded first and remains in the main memory. It also acts as an
interface between user applications and hardware.
Page 26                                                          © Copyright by Interviewbit
                                                       Operating System Interview Questions
Functions of Kernel:
     It is responsible for managing all computer resources such as CPU, memory,
     files, processes, etc.
     It facilitates or initiates the interaction between components of hardware and
     so ware.
     It manages RAM memory so that all running processes and programs can work
     effectively and efficiently.
     It also controls and manages all primary tasks of the OS as well as manages
     access and use of various peripherals connected to the computer.
     It schedules the work done by the CPU so that the work of each user is executed
     as efficiently as possible.
33. What are different types of Kernel?
There are basically five types of Kernels as given below:
Page 27                                                           © Copyright by Interviewbit
                                                       Operating System Interview Questions
     Monolithic Kernel
     MicroKernel
     Hybrid Kernel
     Nano Kernel
     Exo Kernel
34. Write difference between micro kernel and monolithic
    kernel?
MicroKernel: It is a minimal OS that executes only important functions of OS. It only
contains a near-minimum number of features and functions that are required to
implement OS.
Example: QNX, Mac OS X, K42, etc.
Monolithic Kernel: It is an OS architecture that supports all basic features of
computer components such as resource management, memory, file, etc.
Example: Solaris, DOS, OpenVMS, Linux, etc.
Page 28                                                           © Copyright by Interviewbit
                                                    Operating System Interview Questions
          MicroKernel                       Monolithic Kernel
          In this so ware or program,       In this so ware or program,
          kernel services and user          kernel services and user
          services are present in           services are usually present in
          different address spaces.          the same address space.
          It is smaller in size as
                                            It is larger in size as compared
          compared to the
                                            to a microkernel.
          monolithic kernel.
          It is easily extendible as
                                            It is hard to as extend as
          compared to a monolithic
                                            compared to a microkernel.
          kernel.
          If a service crashes, it does     If a service crashes, the whole
          affect on working of the           system crashes in a
          microkernel.                      monolithic kernel.
          It uses message queues to         It uses signals and sockets to
          achieve inter-process             achieve inter-process
          communication.                    communication.
35. What is SMP (Symmetric Multiprocessing)?
SMP is generally referred to as computer architecture in which the processing of
programs is done by multiple processors that share a common OS and memory. SMP
is very much required if you want to take advantage of multiprocessor hardware. It
simply enables any processor to work on any of the tasks no matter where data or
resources for that particular task are located in memory. These systems are more
reliable than single-processor systems.
Page 29                                                        © Copyright by Interviewbit
                                                      Operating System Interview Questions
36. What is a time-sharing system?
It is a system that allows more than one user to access the resources of a particular
system in many locations. In simple words, it performs multiple tasks on a single
processor or CPU. As the name suggests, it means to share time into multiple slots in
several processes. It also allows different users from different locations to use a
particular computer system at the same time therefore it is considered one of the
important types of OS.
37. What is Context Switching?
Context switching is basically a process of saving the context of one process and
loading the context of another process. It is one of the cost-effective and time-saving
measures executed by CPU the because it allows multiple processes to share a single
CPU. Therefore, it is considered an important part of a modern OS. This technique is
used by OS to switch a process from one state to another i.e., from running state to
ready state. It also allows a single CPU to handle and control various different
processes or threads without even the need for additional resources.
38. What is difference between Kernel and OS?
Page 30                                                          © Copyright by Interviewbit
                                                   Operating System Interview Questions
Kernel: Kernel is a system program that controls all programs running on the
computer. The kernel is basically a bridge between the so ware and hardware of the
system.
Operating System: Operating system is a system program that runs on the computer
to provide an interface to the computer user so that they can easily operate on the
computer.
Page 31                                                       © Copyright by Interviewbit
                                                   Operating System Interview Questions
          Kernel                       OS
          It is considered a central
                                       It is considered system so ware.
          component of OS
          It is generally
          responsible for
                                       It is generally responsible for
          converting user
                                       managing the resources of
          commands into
                                       system.
          machine-level
          commands.
          It simply acts as an
          interface between            It simply acts as an interface
          hardware and                 between hardware and user.
          applications.
          It also performs             It also performs functions like
          functions like process       providing security to data and
          management, file             files in the the system, providing
          management, device           access controls to users,
          management, I/O              maintaining the system privacy,
          communication, etc.          etc.
                                       Its type includes Single and
          Its type includes
                                       Multiprogramming batch
          Microkernel, Monolithic
                                       systems, Distributed OS, Real-
          kernel, etc.
                                       time OS.
39. What is difference between process and thread?
Page 32                                                       © Copyright by Interviewbit
                                                      Operating System Interview Questions
Process: It is basically a program that is currently under execution by one or more
threads. It is a very important part of the modern-day OS.
Thread: It is a path of execution that is composed of the program counter, thread id,
stack, and set of registers within the process.
Page 33                                                          © Copyright by Interviewbit
                                                   Operating System Interview Questions
          Process                           Thread
                                            It is the component or entity
          It is a computer program
                                            of the process that is the
          that is under execution.
                                            smallest execution unit.
          These are heavy-weight            These are lightweight
          operators.                        operators.
                                            It uses the memory of the
          It has its own memory space.
                                            process they belong to.
          It is more difficult to create a   It is easier to create a thread
          process as compared to            as compared to creating a
          creating a thread.                process.
          It requires more resources as     It requires fewer resources as
          compared to thread.               compared to processes.
          It takes more time to create      It takes less time to create
          and terminate a process as        and terminate a thread as
          compared to a thread.             compared to a process.
          It usually run-in separate        It usually run-in shared
          memory space.                     memory space.
                                            It shares data with each
          It does not share data.
                                            other.
          It can be divided into            It can’t be further
          multiple threads.                 subdivided.
Page 34                                                       © Copyright by Interviewbit
                                                        Operating System Interview Questions
40. What are various sections of the process?
There are basically four sections in the process as given below:
     Stack: It is used for local variables and returns addresses.
     Heap: It is used for dynamic memory allocation.
     Data: It stores global and static variables.
     Code or text: It comprises compiled program code.
41. What is a deadlock in OS? What are the necessary conditions
    for a deadlock?
Page 35                                                             © Copyright by Interviewbit
                                                      Operating System Interview Questions
Deadlock is generally a situation where a set of processes are blocked as each process
is holding resources and waits to acquire resources held by another process. In this
situation, two or more processes simply try to execute simultaneously and wait for
each to finish their execution because they are dependent on each other. We can see
a hand problem in our system whenever a deadlock occurs in a program. It is one of
the common problems you can see in multiprocessing.
Necessary Conditions for Deadlock
There are basically four necessary conditions for deadlock as given below:
     Mutual Exclusion
     Hold and Wait
     No Pre-emption
     Circular Wait or Resource Wait
42. What do you mean by Belady’s Anomaly?
In the Operating System, process data is loaded in fixed-sized chunks and each chunk
is referred to as a page. The processor loads these pages in the fixed-sized chunks of
memory called frames. Belady’s Anomaly is a phenomenon in which if we increase
the number of frames in memory, then the number of page faults also increases. It is
generally experienced when we use FIFO (First in First out) page replacement
algorithm.
43. What is spooling in OS?
Spooling simply stands for Simultaneous peripheral operations online. It is referred
to as putting data of various I/O jobs in a buffer. Here, buffer means a special area in
memory or hard disk that can be accessible to an I/O device. It is used for mediation
between a computer application and a slow peripheral. It is very useful and
important because devices access or acquire data at different rates. This operation
also uses disk as a very large buffer and is capable of overlapping I/O operations for
one task with processor operations for another task.
Page 36                                                          © Copyright by Interviewbit
Links to More Interview
Questions
 C Interview Questions         Php Interview Questions       C Sharp Interview Questions
 Web Api Interview             Hibernate Interview           Node Js Interview Questions
 Questions                     Questions
 Cpp Interview Questions       Oops Interview Questions      Devops Interview Questions
 Machine Learning Interview    Docker Interview Questions    Mysql Interview Questions
 Questions
 Css Interview Questions       Laravel Interview Questions   Asp Net Interview Questions
 Django Interview Questions    Dot Net Interview Questions   Kubernetes Interview
                                                             Questions
 Operating System Interview    React Native Interview        Aws Interview Questions
 Questions                     Questions
 Git Interview Questions       Java 8 Interview Questions    Mongodb Interview
                                                             Questions
 Dbms Interview Questions      Spring Boot Interview         Power Bi Interview Questions
                               Questions
 Pl Sql Interview Questions    Tableau Interview             Linux Interview Questions
                               Questions
 Ansible Interview Questions   Java Interview Questions      Jenkins Interview Questions
Page 37                                                            © Copyright by Interviewbit
SQL Interview Questions
To view the live version of the
page, click here.
© Copyright by Interviewbit
If you're preparing for your upcoming SQL interview, on top of the
interview questions, guidance from an expert can prove to be
extremely useful. One of our top instructors is hosting a FREE
Masterclass for aspirants like you! Feel free to register if you're
interested.
                       “As a regular attendee of the Masterclass, I feel the
                       most valuable part about Scaler Academy's
  Shubh                Masterclasses is the unparalleled content quality that
                       they deliver. A 3 hour Masterclass is very helpful and
 Agrawal               good enough for the teaching part and doubt clearing
                       sessions. I use the study material they provide before
  B.Tech, IIIT,
                       each Masterclass. In these times when nothing is for
  Bhagalpur
                       free, these classes are a life-savior!”
“The session was so well structured and simplified. 3
engaging hours of learning, interesting polls and lots
of doubt resolution! The best part was, he saw curious
                                                             Abhinav
learners and extended the session for another hour for       Koppula
people who wished to stay. Recommend it to all
beginners out there who are clueless about starting           Developer,
HLD themselves! This is a must!!”                             Mckinsey
    If interested, don't hesitate to
                                               REGISTER NOW
    attend this FREE session.
Contents
SQL Interview Questions
1. What is Database?
2. What is DBMS?
3. What is RDBMS? How is it different from DBMS?
4. What is SQL?
5. What is the difference between SQL and MySQL?
6. What are Tables and Fields?
7. What are Constraints in SQL?
8. What is a Primary Key?
9. What is a UNIQUE constraint?
10. What is a Foreign Key?
11. What is a Join? List its different types.
12. What is a Self-Join?
13. What is a Cross-Join?
14. What is an Index? Explain its different types.
15. What is the difference between Clustered and Non-clustered index?
16. What is Data Integrity?
17. What is a Query?
18. What is a Subquery? What are its types?
19. What is the SELECT statement?
20. What are some common clauses used with SELECT query in SQL?
Page 1                                                     © Copyright by Interviewbit
                                                                  SQL Interview Questions
SQL Interview Questions                                                  (.....Continued)
21. What are UNION, MINUS and INTERSECT commands?
22. What is Cursor? How to use a Cursor?
23. What are Entities and Relationships?
24. List the different types of relationships in SQL.
25. What is an Alias in SQL?
26. What is a View?
27. What is Normalization?
28. What is Denormalization?
29. What are the various forms of Normalization?
30. What are the TRUNCATE, DELETE and DROP statements?
31. What is the difference between DROP and TRUNCATE statements?
32. What is the difference between DELETE and TRUNCATE statements?
33. What are Aggregate and Scalar functions?
34. What is User-defined function? What are its various types?
35. What is OLTP?
36. What are the differences between OLTP and OLAP?
37. What is Collation? What are the different types of Collation Sensitivity?
38. What is a Stored Procedure?
39. What is a Recursive Stored Procedure?
40. How to create empty tables with the same structure as another table?
Page 2                                                           © Copyright by Interviewbit
                                                                 SQL Interview Questions
SQL Interview Questions                                                 (.....Continued)
41. What is Pattern Matching in SQL?
PostgreSQL Interview Questions
42. What is PostgreSQL?
43. How do you define Indexes in PostgreSQL?
44. How will you change the datatype of a column?
45. What is the command used for creating a database in PostgreSQL?
46. How can we start, restart and stop the PostgreSQL server?
47. What are partitioned tables called in PostgreSQL?
48. Define tokens in PostgreSQL?
49. What is the importance of the TRUNCATE statement?
50. What is the capacity of a table in PostgreSQL?
51. Define sequence.
52. What are string constants in PostgreSQL?
53. How can you get a list of all databases in PostgreSQL?
54. How can you delete a database in PostgreSQL?
55. What are ACID properties? Is PostgreSQL compliant with ACID?
56. Can you explain the architecture of PostgreSQL?
57. What do you understand by multi-version concurrency control?
58. What do you understand by command enable-debug?
Page 3                                                          © Copyright by Interviewbit
                                                                SQL Interview Questions
PostgreSQL Interview Questions                                        (.....Continued)
59. How do you check the rows affected as part of previous transactions?
60. What can you tell about WAL (Write Ahead Logging)?
61. What is the main disadvantage of deleting data from an existing table using the
    DROP TABLE command?
62. How do you perform case-insensitive searches using regular expressions in
    PostgreSQL?
63. How will you take backup of the database in PostgreSQL?
64. Does PostgreSQL support full text search?
65. What are parallel queries in PostgreSQL?
66. Differentiate between commit and checkpoint.
Page 4                                                        © Copyright by Interviewbit
Let's get Started
Are you preparing for your SQL developer interview?
Then you have come to the right place.
This guide will help you to brush up on your SQL skills, regain your confidence and be
job-ready!
Here, you will find a collection of real-world Interview questions asked in companies
like Google, Oracle, Amazon, and Microso , etc. Each question comes with a perfectly
written answer inline, saving your interview preparation time.
It also covers practice problems to help you understand the basic concepts of SQL.
We've divided this article into the following sections:
     SQL Interview Questions
     PostgreSQL Interview Questions
In the end, multiple-choice questions are provided to test your understanding.
                 SQL Interview Questions and Answers with Examples | SQL …
Page 5                                                          © Copyright by Interviewbit
                                                                  SQL Interview Questions
SQL Interview Questions
1. What is Database?
A database is an organized collection of data, stored and retrieved digitally from a
remote or local computer system. Databases can be vast and complex, and such
databases are developed using fixed design and modeling approaches.
2. What is DBMS?
DBMS stands for Database Management System. DBMS is a system so ware
responsible for the creation, retrieval, updation, and management of the database. It
ensures that our data is consistent, organized, and is easily accessible by serving as
an interface between the database and its end-users or application so ware.
3. What is RDBMS? How is it different from DBMS?
RDBMS stands for Relational Database Management System. The key difference here,
compared to DBMS, is that RDBMS stores data in the form of a collection of tables,
and relations can be defined between the common fields of these tables. Most
modern database management systems like MySQL, Microso SQL Server, Oracle,
IBM DB2, and Amazon Redshi are based on RDBMS.
4. What is SQL?
SQL stands for Structured Query Language. It is the standard language for relational
database management systems. It is especially useful in handling organized data
comprised of entities (variables) and relations between different entities of the data.
Page 6                                                           © Copyright by Interviewbit
                                                                    SQL Interview Questions
5. What is the difference between SQL and MySQL?
SQL is a standard language for retrieving and manipulating structured databases. On
the contrary, MySQL is a relational database management system, like SQL Server,
Oracle or IBM DB2, that is used to manage SQL databases.
6. What are Tables and Fields?
A table is an organized collection of data stored in the form of rows and columns.
Columns can be categorized as vertical and rows as horizontal. The columns in a
table are called fields while the rows can be referred to as records.
7. What are Constraints in SQL?
Constraints are used to specify the rules concerning data in the table. It can be
applied for single or multiple fields in an SQL table during the creation of the table or
a er creating using the ALTER TABLE command. The constraints are:
     NOT NULL - Restricts NULL value from being inserted into a column.
     CHECK - Verifies that all values in a field satisfy a condition.
     DEFAULT - Automatically assigns a default value if no value has been specified
     for the field.
     UNIQUE - Ensures unique values to be inserted into the field.
     INDEX - Indexes a field providing faster retrieval of records.
     PRIMARY KEY - Uniquely identifies each record in a table.
     FOREIGN KEY - Ensures referential integrity for a record in another table.
8. What is a Primary Key?
Page 7                                                            © Copyright by Interviewbit
                                                                     SQL Interview Questions
The PRIMARY KEY constraint uniquely identifies each row in a table. It must contain
UNIQUE values and has an implicit NOT NULL constraint.
A table in SQL is strictly restricted to have one and only one primary key, which is
comprised of single or multiple fields (columns).
  CREATE TABLE Students (   /* Create table with a single field as primary key */
     ID INT NOT NULL
     Name VARCHAR(255)
     PRIMARY KEY (ID)
  );
  CREATE TABLE Students (   /* Create table with multiple fields as primary key */
     ID INT NOT NULL
     LastName VARCHAR(255)
     FirstName VARCHAR(255) NOT NULL,
     CONSTRAINT PK_Student
     PRIMARY KEY (ID, FirstName)
  );
  ALTER TABLE Students   /* Set a column as primary key */
  ADD PRIMARY KEY (ID);
  ALTER TABLE Students   /* Set multiple columns as primary key */
  ADD CONSTRAINT PK_Student   /*Naming a Primary Key*/
  PRIMARY KEY (ID, FirstName);
write a sql statement to add primary key 't_id' to the table 'teachers'.
                       Check
Write a SQL statement to add primary key constraint 'pk_a' for table 'table_a'
and fields 'col_b, col_c'.
                       Check
9. What is a UNIQUE constraint?
A UNIQUE constraint ensures that all values in a column are different. This provides
uniqueness for the column(s) and helps identify each row uniquely. Unlike primary
key, there can be multiple unique constraints defined per table. The code syntax for
UNIQUE is quite similar to that of PRIMARY KEY and can be used interchangeably.
Page 8                                                           © Copyright by Interviewbit
                                                                   SQL Interview Questions
  CREATE TABLE Students (   /* Create table with a single field as unique */
     ID INT NOT NULL UNIQUE
     Name VARCHAR(255)
  );
  CREATE TABLE Students (   /* Create table with multiple fields as unique */
     ID INT NOT NULL
     LastName VARCHAR(255)
     FirstName VARCHAR(255) NOT NULL
     CONSTRAINT PK_Student
     UNIQUE (ID, FirstName)
  );
  ALTER TABLE Students   /* Set a column as unique */
  ADD UNIQUE (ID);
  ALTER TABLE Students   /* Set multiple columns as unique */
  ADD CONSTRAINT PK_Student   /* Naming a unique constraint */
  UNIQUE (ID, FirstName);
10. What is a Foreign Key?
A FOREIGN KEY comprises of single or collection of fields in a table that essentially
refers to the PRIMARY KEY in another table. Foreign key constraint ensures referential
integrity in the relation between two tables.
The table with the foreign key constraint is labeled as the child table, and the table
containing the candidate key is labeled as the referenced or parent table.
  CREATE TABLE Students (   /* Create table with foreign key - Way 1 */
     ID INT NOT NULL
     Name VARCHAR(255)
     LibraryID INT
     PRIMARY KEY (ID)
     FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
  );
  CREATE TABLE Students (   /* Create table with foreign key - Way 2 */
     ID INT NOT NULL PRIMARY KEY
     Name VARCHAR(255)
     LibraryID INT FOREIGN KEY (Library_ID) REFERENCES Library(LibraryID)
  );
  ALTER TABLE Students   /* Add a new foreign key */
  ADD FOREIGN KEY (LibraryID)
  REFERENCES Library (LibraryID);
Page 9                                                           © Copyright by Interviewbit
                                                                 SQL Interview Questions
What type of integrity constraint does the foreign key ensure?
                      Check
Write a SQL statement to add a FOREIGN KEY 'col_fk' in 'table_y' that references
'col_pk' in 'table_x'.
                      Check
11. What is a Join? List its different types.
The SQL Join clause is used to combine records (rows) from two or more tables in a
SQL database based on a related column between the two.
There are four different types of JOINs in SQL:
     (INNER) JOIN: Retrieves records that have matching values in both tables
     involved in the join. This is the widely used join for queries.
Page 10                                                       © Copyright by Interviewbit
                                                                    SQL Interview Questions
  SELECT *
  FROM Table_A
  JOIN Table_B;
  SELECT *
  FROM Table_A
  INNER JOIN Table_B;
     LEFT (OUTER) JOIN: Retrieves all the records/rows from the le and the
     matched records/rows from the right table.
  SELECT *
  FROM Table_A A
  LEFT JOIN Table_B B
  ON A.col = B.col;
     RIGHT (OUTER) JOIN: Retrieves all the records/rows from the right and the
     matched records/rows from the le table.
  SELECT *
  FROM Table_A A
  RIGHT JOIN Table_B B
  ON A.col = B.col;
     FULL (OUTER) JOIN: Retrieves all the records where there is a match in either
     the le or right table.
  SELECT *
  FROM Table_A A
  FULL JOIN Table_B B
  ON A.col = B.col;
12. What is a Self-Join?
A self JOIN is a case of regular join where a table is joined to itself based on some
relation between its own column(s). Self-join uses the INNER JOIN or LEFT JOIN
clause and a table alias is used to assign different names to the table within the
query.
Page 11                                                           © Copyright by Interviewbit
                                                                   SQL Interview Questions
  SELECT A.emp_id AS "Emp_ID",A.emp_name AS "Employee",
  B.emp_id AS "Sup_ID",B.emp_name AS "Supervisor"
  FROM employee A, employee B
  WHERE A.emp_sup = B.emp_id;
13. What is a Cross-Join?
Cross join can be defined as a cartesian product of the two tables included in the join.
The table a er join contains the same number of rows as in the cross-product of the
number of rows in the two tables. If a WHERE clause is used in cross join then the
query will work like an INNER JOIN.
  SELECT stu.name, sub.subject
  FROM students AS stu
  CROSS JOIN subjects AS sub;
Write a SQL statement to CROSS JOIN 'table_1' with 'table_2' and fetch 'col_1'
from table_1 & 'col_2' from table_2 respectively. Do not use alias.
                       Check
Page 12                                                          © Copyright by Interviewbit
                                                                   SQL Interview Questions
Write a SQL statement to perform SELF JOIN for 'Table_X' with alias 'Table_1'
and 'Table_2', on columns 'Col_1' and 'Col_2' respectively.
                       Check
14. What is an Index? Explain its different types.
A database index is a data structure that provides a quick lookup of data in a column
or columns of a table. It enhances the speed of operations accessing data from a
database table at the cost of additional writes and memory to maintain the index
data structure.
  CREATE INDEX index_name   /* Create Index */
  ON table_name (column_1, column_2);
  DROP INDEX index_name;   /* Drop Index */
There are different types of indexes that can be created for different purposes:
     Unique and Non-Unique Index:
Unique indexes are indexes that help maintain data integrity by ensuring that no two
rows of data in a table have identical key values. Once a unique index has been
defined for a table, uniqueness is enforced whenever keys are added or changed
within the index.
  CREATE UNIQUE INDEX myIndex
  ON students (enroll_no);
Non-unique indexes, on the other hand, are not used to enforce constraints on the
tables with which they are associated. Instead, non-unique indexes are used solely to
improve query performance by maintaining a sorted order of data values that are
used frequently.
     Clustered and Non-Clustered Index:
Clustered indexes are indexes whose order of the rows in the database corresponds
to the order of the rows in the index. This is why only one clustered index can exist in
a given table, whereas, multiple non-clustered indexes can exist in the table.
Page 13                                                           © Copyright by Interviewbit
                                                                    SQL Interview Questions
The only difference between clustered and non-clustered indexes is that the
database manager attempts to keep the data in the database in the same order as
the corresponding keys appear in the clustered index.
Clustering indexes can improve the performance of most query operations because
they provide a linear-access path to data stored in the database.
Write a SQL statement to create a UNIQUE INDEX "my_index" on "my_table" for
fields "column_1" & "column_2".
                       Check
15. What is the difference between Clustered and Non-clustered
    index?
As explained above, the differences can be broken down into three small factors -
     Clustered index modifies the way records are stored in a database based on the
     indexed column. A non-clustered index creates a separate entity within the table
     which references the original table.
     Clustered index is used for easy and speedy retrieval of data from the database,
     whereas, fetching records from the non-clustered index is relatively slower.
     In SQL, a table can have a single clustered index whereas it can have multiple
     non-clustered indexes.
16. What is Data Integrity?
Data Integrity is the assurance of accuracy and consistency of data over its entire life-
cycle and is a critical aspect of the design, implementation, and usage of any system
which stores, processes, or retrieves data. It also defines integrity constraints to
enforce business rules on the data when it is entered into an application or a
database.
17. What is a Query?
A query is a request for data or information from a database table or combination of
tables. A database query can be either a select query or an action query.
Page 14                                                           © Copyright by Interviewbit
                                                                  SQL Interview Questions
  SELECT fname, lname      /* select query */
  FROM myDb.students
  WHERE student_id = 1;
  UPDATE myDB.students    /* action query */
  SET fname = 'Captain', lname = 'America'
  WHERE student_id = 1;
18. What is a Subquery? What are its types?
A subquery is a query within another query, also known as a nested query or inner
query. It is used to restrict or enhance the data to be queried by the main query, thus
restricting or enhancing the output of the main query respectively. For example, here
we fetch the contact information for students who have enrolled for the maths
subject:
  SELECT name, email, mob, address
  FROM myDb.contacts
  WHERE roll_no IN (
   SELECT roll_no
   FROM myDb.students
   WHERE subject = 'Maths');
There are two types of subquery - Correlated and Non-Correlated.
     A correlated subquery cannot be considered as an independent query, but it can
     refer to the column in a table listed in the FROM of the main query.
     A non-correlated subquery can be considered as an independent query and the
     output of the subquery is substituted in the main query.
Write a SQL query to update the field "status" in table "applications" from 0 to
1.
                          Check
Page 15                                                         © Copyright by Interviewbit
                                                                 SQL Interview Questions
Write a SQL query to select the field "app_id" in table "applications" where
"app_id" less than 1000.
                       Check
Write a SQL query to fetch the field "app_name" from "apps" where "apps.id" is
equal to the above collection of "app_id".
                       Check
19. What is the SELECT statement?
SELECT operator in SQL is used to select data from a database. The data returned is
stored in a result table, called the result-set.
  SELECT * FROM myDB.students;
20. What are some common clauses used with SELECT query in
    SQL?
Some common SQL clauses used in conjuction with a SELECT query are as follows:
     WHERE clause in SQL is used to filter records that are necessary, based on
     specific conditions.
     ORDER BY clause in SQL is used to sort the records based on some field(s) in
     ascending (ASC) or descending order (DESC).
  SELECT *
  FROM myDB.students
  WHERE graduation_year = 2019
  ORDER BY studentID DESC;
Page 16                                                        © Copyright by Interviewbit
                                                                SQL Interview Questions
     GROUP BY clause in SQL is used to group records with identical data and can be
     used in conjunction with some aggregation functions to produce summarized
     results from the database.
     HAVING clause in SQL is used to filter records in combination with the GROUP BY
     clause. It is different from WHERE, since the WHERE clause cannot filter
     aggregated records.
  SELECT COUNT(studentId), country
  FROM myDB.students
  WHERE country != "INDIA"
  GROUP BY country
  HAVING COUNT(studentID) > 5;
21. What are UNION, MINUS and INTERSECT commands?
The UNION operator combines and returns the result-set retrieved by two or more
SELECT statements.
The MINUS operator in SQL is used to remove duplicates from the result-set obtained
by the second SELECT query from the result-set obtained by the first SELECT query
and then return the filtered results from the first.
The INTERSECT clause in SQL combines the result-set fetched by the two SELECT
statements where records from one match the other and then returns this
intersection of result-sets.
Certain conditions need to be met before executing either of the above statements in
SQL -
     Each SELECT statement within the clause must have the same number of
     columns
     The columns must also have similar data types
     The columns in each SELECT statement should necessarily have the same order
Page 17                                                       © Copyright by Interviewbit
                                                                      SQL Interview Questions
  SELECT name   FROM Students    /* Fetch the union of queries */
  UNION
  SELECT name   FROM Contacts;
  SELECT name   FROM Students    /* Fetch the union of queries with duplicates*/
  UNION ALL
  SELECT name   FROM Contacts;
  SELECT name FROM Students   /* Fetch names from students */
  MINUS     /* that aren't present in contacts */
  SELECT name FROM Contacts;
  SELECT name FROM Students   /* Fetch names from students */
  INTERSECT    /* that are present in contacts as well */
  SELECT name FROM Contacts;
Write a SQL query to fetch "names" that are present in either table "accounts" or
in table "registry".
                         Check
Write a SQL query to fetch "names" that are present in "accounts" but not in
table "registry".
                         Check
Write a SQL query to fetch "names" from table "contacts" that are neither
present in "accounts.name" nor in "registry.name".
                         Check
22. What is Cursor? How to use a Cursor?
A database cursor is a control structure that allows for the traversal of records in a
database. Cursors, in addition, facilitates processing a er traversal, such as retrieval,
addition, and deletion of database records. They can be viewed as a pointer to one
row in a set of rows.
Working with SQL Cursor:
Page 18                                                             © Copyright by Interviewbit
                                                                   SQL Interview Questions
  1. DECLARE a cursor a er any variable declaration. The cursor declaration must
     always be associated with a SELECT Statement.
  2. Open cursor to initialize the result set. The OPEN statement must be called
     before fetching rows from the result set.
  3. FETCH statement to retrieve and move to the next row in the result set.
  4. Call the CLOSE statement to deactivate the cursor.
  5. Finally use the DEALLOCATE statement to delete the cursor definition and
     release the associated resources.
  DECLARE @name VARCHAR(50)   /* Declare All Required Variables */
  DECLARE db_cursor CURSOR FOR   /* Declare Cursor Name*/
  SELECT name
  FROM myDB.students
  WHERE parent_name IN ('Sara', 'Ansh')
  OPEN db_cursor   /* Open cursor and Fetch data into @name */
  FETCH next
  FROM db_cursor
  INTO @name
  CLOSE db_cursor   /* Close the cursor and deallocate the resources */
  DEALLOCATE db_cursor
23. What are Entities and Relationships?
Entity: An entity can be a real-world object, either tangible or intangible, that can be
easily identifiable. For example, in a college database, students, professors, workers,
departments, and projects can be referred to as entities. Each entity has some
associated properties that provide it an identity.
Relationships: Relations or links between entities that have something to do with
each other. For example - The employee's table in a company's database can be
associated with the salary table in the same database.
Page 19                                                           © Copyright by Interviewbit
                                                                  SQL Interview Questions
24. List the different types of relationships in SQL.
     One-to-One - This can be defined as the relationship between two tables where
     each record in one table is associated with the maximum of one record in the
     other table.
     One-to-Many & Many-to-One - This is the most commonly used relationship
     where a record in a table is associated with multiple records in the other table.
     Many-to-Many - This is used in cases when multiple instances on both sides are
     needed for defining a relationship.
     Self-Referencing Relationships - This is used when a table needs to define a
     relationship with itself.
25. What is an Alias in SQL?
An alias is a feature of SQL that is supported by most, if not all, RDBMSs. It is a
temporary name assigned to the table or table column for the purpose of a particular
SQL query. In addition, aliasing can be employed as an obfuscation technique to
secure the real names of database fields. A table alias is also called a correlation
name.
Page 20                                                         © Copyright by Interviewbit
                                                                    SQL Interview Questions
An alias is represented explicitly by the AS keyword but in some cases, the same can
be performed without it as well. Nevertheless, using the AS keyword is always a good
practice.
  SELECT A.emp_name AS "Employee" /* Alias using AS keyword */
  B.emp_name AS "Supervisor"
  FROM employee A, employee B   /* Alias without AS keyword */
  WHERE A.emp_sup = B.emp_id;
Write an SQL statement to select all from table "Limited" with alias "Ltd".
                       Check
26. What is a View?
A view in SQL is a virtual table based on the result-set of an SQL statement. A view
contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.
27. What is Normalization?
Page 21                                                           © Copyright by Interviewbit
                                                                   SQL Interview Questions
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.
28. 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.
29. 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
Page 22                                                           © Copyright by Interviewbit
                                                                  SQL Interview Questions
          Student         Address           Books Issued            Salutation
                                            Until the Day I
                                            Die (Emily
                          Amanora
                                            Carpenter),
          Sara            Park                                      Ms.
                                            Inception
                          Town 94
                                            (Christopher
                                            Nolan)
                                            The
                                            Alchemist
                          62nd
                                            (Paulo
          Ansh            Sector A-                                 Mr.
                                            Coelho),
                          10
                                            Inferno (Dan
                                            Brown)
                                            Beautiful Bad
                          24th
                                            (Annie Ward),
                          Street
          Sara                              Woman 99                Mrs.
                          Park
                                            (Greer
                          Avenue
                                            Macallister)
                          Windsor
                                            Dracula
          Ansh            Street                                    Mr.
                                            (Bram Stoker)
                          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)
Page 23                                                         © Copyright by Interviewbit
                                                   SQL Interview Questions
          Student   Address     Books Issued          Salutation
                    Amanora     Until the Day I
          Sara      Park        Die (Emily            Ms.
                    Town 94     Carpenter)
                    Amanora     Inception
          Sara      Park        (Christopher          Ms.
                    Town 94     Nolan)
                                The
                    62nd
                                Alchemist
          Ansh      Sector A-                         Mr.
                                (Paulo
                    10
                                Coelho)
                    62nd
                                Inferno (Dan
          Ansh      Sector A-                         Mr.
                                Brown)
                    10
                    24th
                    Street      Beautiful Bad
          Sara                                        Mrs.
                    Park        (Annie Ward)
                    Avenue
                    24th
                                Woman 99
                    Street
          Sara                  (Greer                Mrs.
                    Park
                                Macallister)
                    Avenue
                    Windsor     Dracula
          Ansh      Street      (Bram                 Mr.
                    777         Stoker)
Page 24                                           © Copyright by Interviewbit
                                                                    SQL Interview Questions
     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. O en, 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)
Page 25                                                           © Copyright by Interviewbit
                                                        SQL Interview Questions
          Student_ID      Student       Address         Salutation
                                        Amanora
          1               Sara          Park            Ms.
                                        Town 94
                                        62nd
          2               Ansh          Sector A-       Mr.
                                        10
                                        24th
                                        Street
          3               Sara                          Mrs.
                                        Park
                                        Avenue
                                        Windsor
          4               Ansh          Street          Mr.
                                        777
                       Books Table (2nd Normal Form)
Page 26                                                © Copyright by Interviewbit
                                                                    SQL Interview Questions
          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.
Page 27                                                           © Copyright by Interviewbit
                                                                   SQL Interview Questions
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
                                                Amanora
          1                   Sara              Park               1
                                                Town 94
                                                62nd
          2                   Ansh              Sector A-          2
                                                10
                                                24th
                                                Street
          3                   Sara                                 3
                                                Park
                                                Avenue
                                                Windsor
          4                   Ansh              Street             1
                                                777
                           Books Table (3rd Normal Form)
Page 28                                                          © Copyright by Interviewbit
                                                                 SQL Interview Questions
          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)
Page 29                                                         © Copyright by Interviewbit
                                                                   SQL Interview Questions
   P -> QR     [P together determine C]
   RS -> T     [B and C together determine D]
   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, Le -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.
30. What are the TRUNCATE, DELETE and DROP statements?
DELETE statement is used to delete rows from a table.
  DELETE FROM Candidates
  WHERE CandidateId > 1000;
TRUNCATE command is used to delete all the rows from the table and free the space
containing the table.
  TRUNCATE TABLE Candidates;
DROP command is used to remove an object from the database. If you drop a table,
all the rows in the table are deleted and the table structure is removed from the
database.
  DROP TABLE Candidates;
Page 30                                                          © Copyright by Interviewbit
                                                                   SQL Interview Questions
Write a SQL statement to wipe a table 'Temporary' from memory.
                       Check
Write a SQL query to remove first 1000 records from table 'Temporary' based on
'id'.
                       Check
Write a SQL statement to delete the table 'Temporary' while keeping its relations
intact.
                       Check
31. What is the difference between DROP and TRUNCATE
    statements?
If a table is dropped, all things associated with the tables are dropped as well. This
includes - the relationships defined on the table with other tables, the integrity
checks and constraints, access privileges and other grants that the table has. To
create and use the table again in its original form, all these relations, checks,
constraints, privileges and relationships need to be redefined. However, if a table is
truncated, none of the above problems exist and the table retains its original
structure.
32. What is the difference between DELETE and TRUNCATE
    statements?
The TRUNCATE command is used to delete all the rows from the table and free the
space containing the table.
The DELETE command deletes only the rows from the table based on the condition
given in the where clause or deletes all the rows from the table if no condition is
specified. But it does not free the space containing the table.
33. What are Aggregate and Scalar functions?
Page 31                                                          © Copyright by Interviewbit
                                                                  SQL Interview Questions
An aggregate function performs operations on a collection of values to return a single
scalar value. Aggregate functions are o en 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.
34. What is User-defined function? What are its various types?
The user-defined functions in SQL are like functions in any other programming
language that accept parameters, perform complex calculations, and return a value.
They are written to use the logic repetitively whenever required. There are two types
of SQL user-defined functions:
Page 32                                                         © Copyright by Interviewbit
                                                                  SQL Interview Questions
     Scalar Function: As explained earlier, user-defined scalar functions return a
     single scalar value.
     Table-Valued Functions: User-defined table-valued functions return a table as
     output.
          Inline: returns a table data type based on a single SELECT statement.
          Multi-statement: returns a tabular result-set but, unlike inline, multiple
          SELECT statements can be used inside the function body.
35. What is OLTP?
OLTP stands for Online Transaction Processing, is a class of so ware applications
capable of supporting transaction-oriented programs. An essential attribute of an
OLTP system is its ability to maintain concurrency. To avoid single points of failure,
OLTP systems are o en decentralized. These systems are usually designed for a large
number of users who conduct short transactions. Database queries are usually
simple, require sub-second response times, and return relatively few records. Here is
an insight into the working of an OLTP system [ Note - The figure is not important for
interviews ] -
36. What are the differences between OLTP and OLAP?
Page 33                                                         © Copyright by Interviewbit
                                                                 SQL Interview Questions
OLTP stands for Online Transaction Processing, is a class of so ware applications
capable of supporting transaction-oriented programs. An important attribute of an
OLTP system is its ability to maintain concurrency. OLTP systems o en follow a
decentralized architecture to avoid single points of failure. These systems are
generally designed for a large audience of end-users who conduct short transactions.
Queries involved in such databases are generally simple, need fast response times,
and return relatively few records. A number of transactions per second acts as an
effective measure for such systems.
OLAP stands for Online Analytical Processing, a class of so ware programs that are
characterized by the relatively low frequency of online transactions. Queries are o en
too complex and involve a bunch of aggregations. For OLAP systems, the
effectiveness measure relies highly on response time. Such systems are widely used
for data mining or maintaining aggregated, historical data, usually in multi-
dimensional schemas.
37. What is Collation? What are the different types of Collation
    Sensitivity?
Page 34                                                        © Copyright by Interviewbit
                                                                  SQL Interview Questions
Collation refers to a set of rules that determine how data is sorted and compared.
Rules defining the correct character sequence are used to sort the character data. It
incorporates options for specifying case sensitivity, accent marks, kana character
types, and character width. Below are the different types of collation sensitivity:
     Case sensitivity: A and a are treated differently.
     Accent sensitivity: a and á are treated differently.
     Kana sensitivity: Japanese kana characters Hiragana and Katakana are treated
     differently.
     Width sensitivity: Same character represented in single-byte (half-width) and
     double-byte (full-width) are treated differently.
38. What is a Stored Procedure?
A stored procedure is a subroutine available to applications that access a relational
database management system (RDBMS). Such procedures are stored in the database
data dictionary. The sole disadvantage of stored procedure is that it can be executed
nowhere except in the database and occupies more memory in the database server.
It also provides a sense of security and functionality as users who can't access the
data directly can be granted access via stored procedures.
  DELIMITER $$
  CREATE PROCEDURE FetchAllStudents()
  BEGIN
  SELECT * FROM myDB.students;
  END $$
  DELIMITER ;
Page 35                                                         © Copyright by Interviewbit
                                                                   SQL Interview Questions
39. What is a Recursive Stored Procedure?
A stored procedure that calls itself until a boundary condition is reached, is called a
recursive stored procedure. This recursive function helps the programmers to deploy
the same set of code several times as and when required. Some SQL programming
languages limit the recursion depth to prevent an infinite loop of procedure calls
from causing a stack overflow, which slows down the system and may lead to system
crashes.
  DELIMITER $$     /* Set a new delimiter => $$ */
  CREATE PROCEDURE calctotal( /* Create the procedure */
     IN number INT,   /* Set Input and Ouput variables */
     OUT total INT
  ) BEGIN
  DECLARE score INT DEFAULT NULL;   /* Set the default value => "score" */
  SELECT awards FROM achievements   /* Update "score" via SELECT query */
  WHERE id = number INTO score;
  IF score IS NULL THEN SET total = 0;   /* Termination condition */
  ELSE
  CALL calctotal(number+1);   /* Recursive call */
  SET total = total + score;   /* Action after recursion */
  END IF;
  END $$     /* End of procedure */
  DELIMITER ;     /* Reset the delimiter */
Page 36                                                          © Copyright by Interviewbit
                                                                  SQL Interview Questions
40. How to create empty tables with the same structure as
    another table?
Creating empty tables with the same structure can be done smartly by fetching the
records of one table into a new table using the INTO operator while fixing a WHERE
clause to be false for all records. Hence, SQL prepares the new table with a duplicate
structure to accept the fetched records but since no records get fetched due to the
WHERE clause in action, nothing is inserted into the new table.
  SELECT * INTO Students_copy
  FROM Students WHERE 1 = 2;
41. What is Pattern Matching in SQL?
SQL pattern matching provides for pattern search in data if you have no clue as to
what that word should be. This kind of SQL query uses wildcards to match a string
pattern, rather than writing the exact word. The LIKE operator is used in conjunction
with SQL Wildcards to fetch the required information.
     Using the % wildcard to perform a simple search
The % wildcard matches zero or more characters of any type and can be used to
define wildcards both before and a er the pattern. Search a student in your database
with first name beginning with the letter K:
  SELECT *
  FROM students
  WHERE first_name LIKE 'K%'
     Omitting the patterns using the NOT keyword
Use the NOT keyword to select records that don't match the pattern. This query
returns all students whose first name does not begin with K.
  SELECT *
  FROM students
  WHERE first_name NOT LIKE 'K%'
Page 37                                                         © Copyright by Interviewbit
                                                                      SQL Interview Questions
     Matching a pattern anywhere using the % wildcard twice
Search for a student in the database where he/she has a K in his/her first name.
  SELECT *
  FROM students
  WHERE first_name LIKE '%Q%'
     Using the _ wildcard to match pattern at a specific position
The _ wildcard matches exactly one character of any type. It can be used in
conjunction with % wildcard. This query fetches all students with letter K at the third
position in their first name.
  SELECT *
  FROM students
  WHERE first_name LIKE '__K%'
     Matching patterns for a specific length
The _ wildcard plays an important role as a limitation when it matches exactly one
character. It limits the length and position of the matched results. For example -
  SELECT *   /* Matches first names with three or more letters */
  FROM students
  WHERE first_name LIKE '___%'
  SELECT *   /* Matches first names with exactly four characters */
  FROM students
  WHERE first_name LIKE '____'
PostgreSQL Interview Questions
42. What is PostgreSQL?
Page 38                                                             © Copyright by Interviewbit
                                                                 SQL Interview Questions
PostgreSQL was first called Postgres and was developed by a team led by Computer
Science Professor Michael Stonebraker in 1986. It was developed to help developers
build enterprise-level applications by upholding data integrity by making systems
fault-tolerant. PostgreSQL is therefore an enterprise-level, flexible, robust, open-
source, and object-relational DBMS that supports flexible workloads along with
handling concurrent users. It has been consistently supported by the global
developer community. Due to its fault-tolerant nature, PostgreSQL has gained
widespread popularity among developers.
43. How do you define Indexes in PostgreSQL?
Indexes are the inbuilt functions in PostgreSQL which are used by the queries to
perform search more efficiently on a table in the database. Consider that you have a
table with thousands of records and you have the below query that only a few records
can satisfy the condition, then it will take a lot of time to search and return those
rows that abide by this condition as the engine has to perform the search operation
on every single to check this condition. This is undoubtedly inefficient for a system
dealing with huge data. Now if this system had an index on the column where we are
applying search, it can use an efficient method for identifying matching rows by
walking through only a few levels. This is called indexing.
  Select * from some_table where table_col=120
44. How will you change the datatype of a column?
This can be done by using the ALTER TABLE statement as shown below:
Syntax:
  ALTER TABLE tname
  ALTER COLUMN col_name [SET DATA] TYPE new_data_type;
45. What is the command used for creating a database in
    PostgreSQL?
Page 39                                                        © Copyright by Interviewbit
                                                                  SQL Interview Questions
The first step of using PostgreSQL is to create a database. This is done by using the
createdb command as shown below: createdb db_name
A er running the above command, if the database creation was successful, then the
below message is shown:
  CREATE DATABASE
46. How can we start, restart and stop the PostgreSQL server?
     To start the PostgreSQL server, we run:
  service postgresql start
     Once the server is successfully started, we get the below message:
  Starting PostgreSQL: ok
     To restart the PostgreSQL server, we run:
  service postgresql restart
Once the server is successfully restarted, we get the message:
  Restarting PostgreSQL: server stopped
  ok
     To stop the server, we run the command:
  service postgresql stop
Once stopped successfully, we get the message:
  Stopping PostgreSQL: server stopped
  ok
Page 40                                                          © Copyright by Interviewbit
                                                                  SQL Interview Questions
47. What are partitioned tables called in PostgreSQL?
Partitioned tables are logical structures that are used for dividing large tables into
smaller structures that are called partitions. This approach is used for effectively
increasing the query performance while dealing with large database tables. To create
a partition, a key called partition key which is usually a table column or an
expression, and a partitioning method needs to be defined. There are three types of
inbuilt partitioning methods provided by Postgres:
     Range Partitioning: This method is done by partitioning based on a range of
     values. This method is most commonly used upon date fields to get monthly,
     weekly or yearly data. In the case of corner cases like value belonging to the end
     of the range, for example: if the range of partition 1 is 10-20 and the range of
     partition 2 is 20-30, and the given value is 10, then 10 belongs to the second
     partition and not the first.
     List Partitioning: This method is used to partition based on a list of known
     values. Most commonly used when we have a key with a categorical value. For
     example, getting sales data based on regions divided as countries, cities, or
     states.
     Hash Partitioning: This method utilizes a hash function upon the partition key.
     This is done when there are no specific requirements for data division and is
     used to access data individually. For example, you want to access data based on
     a specific product, then using hash partition would result in the dataset that we
     require.
The type of partition key and the type of method used for partitioning determines
how positive the performance and the level of manageability of the partitioned table
are.
48. Define tokens in PostgreSQL?
A token in PostgreSQL is either a keyword, identifier, literal, constant, quotes
identifier, or any symbol that has a distinctive personality. They may or may not be
separated using a space, newline or a tab. If the tokens are keywords, they are usually
commands with useful meanings. Tokens are known as building blocks of any
PostgreSQL code.
Page 41                                                          © Copyright by Interviewbit
                                                                  SQL Interview Questions
49. What is the importance of the TRUNCATE statement?
  TRUNCATE TABLE name_of_table    statement removes the data efficiently and quickly
from the table.
The truncate statement can also be used to reset values of the identity columns
along with data cleanup as shown below:
  TRUNCATE TABLE name_of_table
  RESTART IDENTITY;
We can also use the statement for removing data from multiple tables all at once by
mentioning the table names separated by comma as shown below:
  TRUNCATE TABLE
     table_1,
     table_2,
     table_3;
50. What is the capacity of a table in PostgreSQL?
The maximum size of PostgreSQL is 32TB.
51. Define sequence.
A sequence is a schema-bound, user-defined object which aids to generate a
sequence of integers. This is most commonly used to generate values to identity
columns in a table. We can create a sequence by using the CREATE SEQUENCE
statement as shown below:
  CREATE SEQUENCE serial_num START 100;
To get the next number 101 from the sequence, we use the nextval() method as
shown below:
  SELECT nextval('serial_num');
Page 42                                                          © Copyright by Interviewbit
                                                                   SQL Interview Questions
We can also use this sequence while inserting new records using the INSERT
command:
  INSERT INTO ib_table_name VALUES (nextval('serial_num'), 'interviewbit');
52. What are string constants in PostgreSQL?
They are character sequences bound within single quotes. These are using during
data insertion or updation to characters in the database.
There are special string constants that are quoted in dollars. Syntax:
  $tag$<string_constant>$tag$ The tag in the constant is optional and when we are
not specifying the tag, the constant is called a double-dollar string literal.
53. How can you get a list of all databases in PostgreSQL?
This can be done by using the command       \l   -> backslash followed by the lower-
case letter L.
54. How can you delete a database in PostgreSQL?
This can be done by using the DROP DATABASE command as shown in the syntax
below:
  DROP DATABASE database_name;
If the database has been deleted successfully, then the following message would be
shown:
  DROP DATABASE
55. What are ACID properties? Is PostgreSQL compliant with
    ACID?
ACID stands for Atomicity, Consistency, Isolation, Durability. They are database
transaction properties which are used for guaranteeing data validity in case of errors
and failures.
Page 43                                                          © Copyright by Interviewbit
                                                                    SQL Interview Questions
     Atomicity: This property ensures that the transaction is completed in all-or-
     nothing way.
     Consistency: This ensures that updates made to the database is valid and
     follows rules and restrictions.
     Isolation: This property ensures integrity of transaction that are visible to all
     other transactions.
     Durability: This property ensures that the committed transactions are stored
     permanently in the database.
PostgreSQL is compliant with ACID properties.
56. Can you explain the architecture of PostgreSQL?
     The architecture of PostgreSQL follows the client-server model.
     The server side comprises of background process manager, query processer,
     utilities and shared memory space which work together to build PostgreSQL’s
     instance that has access to the data. The client application does the task of
     connecting to this instance and requests data processing to the services. The
     client can either be GUI (Graphical User Interface) or a web application. The
     most commonly used client for PostgreSQL is pgAdmin.
Page 44                                                           © Copyright by Interviewbit
                                                                   SQL Interview Questions
57. What do you understand by multi-version concurrency
    control?
MVCC or Multi-version concurrency control is used for avoiding unnecessary database
locks when 2 or more requests tries to access or modify the data at the same time.
This ensures that the time lag for a user to log in to the database is avoided. The
transactions are recorded when anyone tries to access the content.
For more information regarding this, you can refer here.
58. What do you understand by command enable-debug?
The command enable-debug is used for enabling the compilation of all libraries and
applications. When this is enabled, the system processes get hindered and generally
also increases the size of the binary file. Hence, it is not recommended to switch this
on in the production environment. This is most commonly used by developers to
debug the bugs in their scripts and help them spot the issues. For more information
regarding how to debug, you can refer here.
59. How do you check the rows affected as part of previous
    transactions?
SQL standards state that the following three phenomena should be prevented whilst
concurrent transactions. SQL standards define 4 levels of transaction isolations to
deal with these phenomena.
Page 45                                                          © Copyright by Interviewbit
                                                                   SQL Interview Questions
     Dirty reads: If a transaction reads data that is written due to concurrent
     uncommitted transaction, these reads are called dirty reads.
     Phantom reads: This occurs when two same queries when executed separately
     return different rows. For example, if transaction A retrieves some set of rows
     matching search criteria. Assume another transaction B retrieves new rows in
     addition to the rows obtained earlier for the same search criteria. The results are
     different.
     Non-repeatable reads: This occurs when a transaction tries to read the same
     row multiple times and gets different values each time due to concurrency. This
     happens when another transaction updates that data and our current
     transaction fetches that updated data, resulting in different values.
To tackle these, there are 4 standard isolation levels defined by SQL standards. They
are as follows:
     Read Uncommitted – The lowest level of the isolations. Here, the transactions
     are not isolated and can read data that are not committed by other transactions
     resulting in dirty reads.
     Read Committed – This level ensures that the data read is committed at any
     instant of read time. Hence, dirty reads are avoided here. This level makes use of
     read/write lock on the current rows which prevents read/write/update/delete of
     that row when the current transaction is being operated on.
     Repeatable Read – The most restrictive level of isolation. This holds read and
     write locks for all rows it operates on. Due to this, non-repeatable reads are
     avoided as other transactions cannot read, write, update or delete the rows.
     Serializable – The highest of all isolation levels. This guarantees that the
     execution is serializable where execution of any concurrent operations are
     guaranteed to be appeared as executing serially.
The following table clearly explains which type of unwanted reads the levels avoid:
Page 46                                                          © Copyright by Interviewbit
                                                                    SQL Interview Questions
          Isolation levels          Dirty Reads           Phantom Reads                 Non-repe
          Read
                                    Might occur           Might occur                   Might occ
          Uncommitted
          Read
                                    Won’t occur           Might occur                   Might occ
          Committed
          Repeatable
                                    Won’t occur           Might occur                   Won’t occ
          Read
          Serializable              Won’t occur           Won’t occur                   Won’t occ
60. What can you tell about WAL (Write Ahead Logging)?
Write Ahead Logging is a feature that increases the database reliability by logging
changes before any changes are done to the database. This ensures that we have
enough information when a database crash occurs by helping to pinpoint to what
point the work has been complete and gives a starting point from the point where it
was discontinued.
For more information, you can refer here.
61. What is the main disadvantage of deleting data from an
    existing table using the DROP TABLE command?
  DROP TABLE  command deletes complete data from the table along with removing
the complete table structure too. In case our requirement entails just remove the
data, then we would need to recreate the table to store data in it. In such cases, it is
advised to use the TRUNCATE command.
62. How do you perform case-insensitive searches using regular
    expressions in PostgreSQL?
Page 47                                                            © Copyright by Interviewbit
                                                                   SQL Interview Questions
To perform case insensitive matches using a regular expression, we can use POSIX
  (~*) expression from pattern matching operators. For example:
  'interviewbit' ~* '.*INTervIewBit.*'
63. How will you take backup of the database in PostgreSQL?
We can achieve this by using the pg_dump tool for dumping all object contents in the
database into a single file. The steps are as follows:
Step 1: Navigate to the bin folder of the PostgreSQL installation path.
  C:\>cd C:\Program Files\PostgreSQL\10.0\bin
Step 2: Execute pg_dump program to take the dump of data to a .tar folder as shown
below:
  pg_dump -U postgres -W -F t sample_data > C:\Users\admin\pgbackup\sample_data.tar
The database dump will be stored in the sample_data.tar file on the location
specified.
64. Does PostgreSQL support full text search?
Full-Text Search is the method of searching single or collection of documents stored
on a computer in a full-text based database. This is mostly supported in advanced
database systems like SOLR or ElasticSearch. However, the feature is present but is
pretty basic in PostgreSQL.
65. What are parallel queries in PostgreSQL?
Parallel Queries support is a feature provided in PostgreSQL for devising query plans
capable of exploiting multiple CPU processors to execute the queries faster.
Page 48                                                          © Copyright by Interviewbit
                                                               SQL Interview Questions
66. Differentiate between commit and checkpoint.
The commit action ensures that the data consistency of the transaction is
maintained and it ends the current transaction in the section. Commit adds a new
record in the log that describes the COMMIT to the memory. Whereas, a checkpoint is
used for writing all changes that were committed to disk up to SCN which would be
kept in datafile headers and control files.
Conclusion:
Page 49                                                       © Copyright by Interviewbit
                                                                  SQL Interview Questions
SQL is a language for the database. It has a vast scope and robust capability of
creating and manipulating a variety of database objects using commands like
CREATE, ALTER, DROP, etc, and also in loading the database objects using commands
like INSERT. It also provides options for Data Manipulation using commands like
DELETE, TRUNCATE and also does effective retrieval of data using cursor commands
like FETCH, SELECT, etc. There are many such commands which provide a large
amount of control to the programmer to interact with the database in an efficient
way without wasting many resources. The popularity of SQL has grown so much that
almost every programmer relies on this to implement their application's storage
functionalities thereby making it an exciting language to learn. Learning this provides
the developer a benefit of understanding the data structures used for storing the
organization's data and giving an additional level of control and in-depth
understanding of the application.
PostgreSQL being an open-source database system having extremely robust and
sophisticated ACID, Indexing, and Transaction supports has found widespread
popularity among the developer community.
References and Resources:
Page 50                                                         © Copyright by Interviewbit
                                             SQL Interview Questions
     PostgreSQL Download
     PostgreSQL Tutorial
     SQL Guide
     SQL Server Interview Questions
     MySQL Interview Questions
     DBMS Interview Questions
     PL SQL Interview Questions
     MongoDB Interview Questions
     Database Testing Interview Questions
     SQL Vs MySQL
     PostgreSQL vs MySQL
     Difference Between SQL and PLSQL
     SQL Vs NoSQL
     SQL IDE
     SQL Projects
     MySQL Commands
Page 51                                     © Copyright by Interviewbit
If you're preparing for your upcoming SQL interview, on top of the
interview questions, guidance from an expert can prove to be
extremely useful. One of our top instructors is hosting a FREE
Masterclass for aspirants like you! Feel free to register if you're
interested.
                       “As a regular attendee of the Masterclass, I feel the
                       most valuable part about Scaler Academy's
  Shubh                Masterclasses is the unparalleled content quality that
                       they deliver. A 3 hour Masterclass is very helpful and
 Agrawal               good enough for the teaching part and doubt clearing
                       sessions. I use the study material they provide before
  B.Tech, IIIT,
                       each Masterclass. In these times when nothing is for
  Bhagalpur
                       free, these classes are a life-savior!”
“The session was so well structured and simplified. 3
engaging hours of learning, interesting polls and lots
of doubt resolution! The best part was, he saw curious
                                                             Abhinav
learners and extended the session for another hour for       Koppula
people who wished to stay. Recommend it to all
beginners out there who are clueless about starting           Developer,
HLD themselves! This is a must!!”                             Mckinsey
    If interested, don't hesitate to
                                               REGISTER NOW
    attend this FREE session.
Links to More Interview
Questions
 C Interview Questions         Php Interview Questions       C Sharp Interview Questions
 Web Api Interview             Hibernate Interview           Node Js Interview Questions
 Questions                     Questions
 Cpp Interview Questions       Oops Interview Questions      Devops Interview Questions
 Machine Learning Interview    Docker Interview Questions    Mysql Interview Questions
 Questions
 Css Interview Questions       Laravel Interview Questions   Asp Net Interview Questions
 Django Interview Questions    Dot Net Interview Questions   Kubernetes Interview
                                                             Questions
 Operating System Interview    React Native Interview        Aws Interview Questions
 Questions                     Questions
 Git Interview Questions       Java 8 Interview Questions    Mongodb Interview
                                                             Questions
 Dbms Interview Questions      Spring Boot Interview         Power Bi Interview Questions
                               Questions
 Pl Sql Interview Questions    Tableau Interview             Linux Interview Questions
                               Questions
 Ansible Interview Questions   Java Interview Questions      Jenkins Interview Questions
Page 52                                                            © Copyright by Interviewbit
JavaScript Interview Questions
To view the live version of the
page, click here.
© Copyright by Interviewbit
Contents
JavaScript Interview Questions for Freshers
1. What are the different data types present in javascript?
2. Explain Hoisting in javascript.
3. Why do we use the word “debugger” in javascript?
4. Difference between “ == “ and “ === “ operators.
5. Difference between var and let keyword in javascript.
6. Explain Implicit Type Coercion in javascript.
7. Is javascript a statically typed or a dynamically typed language?
8. What is NaN property in JavaScript?
9. Explain passed by value and passed by reference.
10. What is an Immediately Invoked Function in JavaScript?
11. What do you mean by strict mode in javascript and characteristics of javascript
    strict-mode?
12. Explain Higher Order Functions in javascript.
13. Explain “this” keyword.
14. What do you mean by Self Invoking Functions?
15. Explain call(), apply() and, bind() methods.
16. What is the difference between exec () and test () methods in javascript?
17. What is currying in JavaScript?
18. What are some advantages of using External JavaScript?
19. Explain Scope and Scope Chain in javascript.
20. Explain Closures in JavaScript.
Page 1                                                          © Copyright by Interviewbit
                                                               JavaScript Interview Questions
JavaScript Interview Questions for
Freshers                                                                   (.....Continued)
21. Mention some advantages of javascript.
22. What are object prototypes?
23. What are callbacks?
24. What are the types of errors in javascript?
25. What is memoization?
26. What is recursion in a programming language?
27. What is the use of a constructor function in javascript?
28. What is DOM?
29. Which method is used to retrieve a character from a certain index?
30. What do you mean by BOM?
31. What is the distinction between client-side and server-side JavaScript?
JavaScript Interview Questions for Experienced
32. What are arrow functions?
33. What do mean by prototype design pattern?
34. Differences between declaring variables using var, let and const.
35. What is the rest parameter and spread operator?
36. In JavaScript, how many different methods can you make an object?
37. What is the use of promises in javascript?
38. What are classes in javascript?
Page 2                                                             © Copyright by Interviewbit
                                                            JavaScript Interview Questions
JavaScript Interview Questions for
Experienced                                                             (.....Continued)
39. What are generator functions?
40. Explain WeakSet in javascript.
41. Why do we use callbacks?
42. Explain WeakMap in javascript.
43. What is Object Destructuring?
44. Difference between prototypal and classical inheritance
45. What is a Temporal Dead Zone?
46. What do you mean by JavaScript Design Patterns?
47. Is JavaScript a pass-by-reference or pass-by-value language?
48. Difference between Async/Await and Generators usage to achieve the same
    functionality.
49. What are the primitive data types in JavaScript?
50. What is the role of deferred scripts in JavaScript?
51. What has to be done in order to put Lexical Scoping into practice?
52. What is the purpose of the following JavaScript code?
JavaScript Coding Interview Questions
53. Guess the outputs of the following codes:
54. Guess the outputs of the following code:
55. Guess the output of the following code:
56. Guess the outputs of the following code:
Page 3                                                          © Copyright by Interviewbit
                                                           JavaScript Interview Questions
JavaScript Coding Interview Questions                                    (.....Continued)
57. Guess the outputs of the following code:
58. Write a function that performs binary search on a sorted array.
59. Implement a function that returns an updated array with r right rotations on an
    array of integers a .
60. Write the code for dynamically inserting new components.
61. Write the code given If two strings are anagrams of one another, then return
    true.
62. Write the code to find the vowels
63. In JavaScript, how do you turn an Object into an Array []?
64. What is the output of the following code?
Page 4                                                           © Copyright by Interviewbit
Let's get Started
JavaScript, created by Brendan Eich in 1995, is one of the most widely used web
development languages. It was designed to build dynamic web pages at first. A script
is a JS program that may be added to the HTML of any web page. When the page
loads, these scripts execute automatically.
A language that was originally designed to build dynamic web pages may now be run
on the server and on almost any device that has the JavaScript Engine installed.
A er HTML and CSS, JavaScript is the third biggest web technology. JavaScript is a
scripting language that may be used to construct online and mobile apps, web
servers, games, and more. JavaScript is an object-oriented programming language
that is used to generate websites and applications. It was created with the intention
of being used in a browser. Even today, the server-side version of JavaScript known as
Node.js may be used to create online and mobile apps, real-time applications, online
streaming applications, and videogames. Javascript frameworks, o en known as
inbuilt libraries, may be used to construct desktop and mobile programs. Developers
may save a lot of time on monotonous programming jobs by using these code
libraries, allowing them to focus on the production work of development.
Page 5                                                         © Copyright by Interviewbit
                                                              JavaScript Interview Questions
The InterviewBit team has compiled a thorough collection of top Javascript
Interview Questions and Answers to assist you in acing your interview and landing
your desired job as a Javascript Developer.
JavaScript Interview Questions for Freshers
1. What are the different data types present in javascript?
To know the type of a JavaScript variable, we can use the typeof operator.
1. Primitive types
String - It represents a series of characters and is written with quotes. A string can be
represented using a single or a double quote.
Example :
  var str = "Vivek Singh Bisht"; //using double quotes
  var str2 = 'John Doe'; //using single quotes
     Number - It represents a number and can be written with or without decimals.
Example :
Page 6                                                            © Copyright by Interviewbit
                                                                JavaScript Interview Questions
  var x = 3; //without decimal
  var y = 3.6; //with decimal
     BigInt - This data type is used to store numbers which are above the limitation
     of the Number data type. It can store large integers and is represented by adding
     “n” to an integer literal.
Example :
  var bigInteger =   234567890123456789012345678901234567890;
     Boolean - It represents a logical entity and can have only two values : true or
     false. Booleans are generally used for conditional testing.
Example :
  var a   = 2;
  var b   = 3;
  var c   = 2;
  (a ==   b) // returns false
  (a ==   c) //returns true
     Undefined - When a variable is declared but not assigned, it has the value of
     undefined and it’s type is also undefined.
Example :
  var x; // value of x is undefined
  var y = undefined; // we can also set the value of a variable as undefined
     Null - It represents a non-existent or a invalid value.
Example :
  var z = null;
Page 7                                                              © Copyright by Interviewbit
                                                               JavaScript Interview Questions
     Symbol - It is a new data type introduced in the ES6 version of javascript. It is
     used to store an anonymous and unique value.
Example :
  var symbol1 = Symbol('symbol');
     typeof of primitive types :
  typeof   "John Doe" // Returns "string"
  typeof   3.14 // Returns "number"
  typeof   true // Returns "boolean"
  typeof   234567890123456789012345678901234567890n // Returns bigint
  typeof   undefined // Returns "undefined"
  typeof   null // Returns "object" (kind of a bug in JavaScript)
  typeof   Symbol('symbol') // Returns Symbol
2. Non-primitive types
     Primitive data types can store only a single value. To store multiple and complex
     values, non-primitive data types are used.
     Object - Used to store collection of data.
     Example:
  // Collection of data in key-value pairs
  var obj1 = {
     x: 43,
     y: "Hello world!",
     z: function(){
        return this.x;
     }
  }
  // Collection of data as an ordered list
  var array1 = [5, "Hello", true, 4.1];
Page 8                                                             © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  Note- It is important to remember that any data type that is not a primitive
  data type, is of Object type in javascript.
2. Explain Hoisting in javascript.
Hoisting is the default behaviour of javascript where all the variable and function
declarations are moved on top.
This means that irrespective of where the variables and functions are declared, they
are moved on top of the scope. The scope can be both local and global.
Example 1:
  hoistedVariable = 3;
  console.log(hoistedVariable); // outputs 3 even when the variable is declared after it
  var hoistedVariable;
Example 2:
Page 9                                                           © Copyright by Interviewbit
                                                              JavaScript Interview Questions
  hoistedFunction();   // Outputs " Hello world! " even when the function is declared afte
  function hoistedFunction(){
    console.log(" Hello world! ");
  }
Example 3:
  // Hoisting takes place in the local scope as well
  function doSomething(){
    x = 33;
    console.log(x);
    var x;
  }
doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local
scope
  Note - Variable initializations are not hoisted, only variable declarations are
  hoisted:
  var x;
  console.log(x); // Outputs "undefined" since the initialization of "x" is not hoisted
  x = 23;
  Note - To avoid hoisting, you can run javascript in strict mode by using “use
  strict” on top of the code:
  "use strict";
  x = 23; // Gives an error since 'x' is not declared
  var x;
3. Why do we use the word “debugger” in javascript?
Page 10                                                           © Copyright by Interviewbit
                                                               JavaScript Interview Questions
The debugger for the browser must be activated in order to debug the code. Built-in
debuggers may be switched on and off, requiring the user to report faults. The
remaining section of the code should stop execution before moving on to the next
line while debugging.
4. Difference between “ == “ and “ === “ operators.
Both are comparison operators. The difference between both the operators is that
“==” is used to compare values whereas, “ === “ is used to compare both values and
types.
Example:
  var x = 2;
  var y = "2";
  (x == y) // Returns true since the value of both x and y is the same
  (x === y) // Returns false since the typeof x is "number" and typeof y is "string"
5. Difference between var and let keyword in javascript.
Some differences are
  1. From the very beginning, the 'var' keyword was used in JavaScript programming
     whereas the keyword 'let' was just added in 2015.
  2. The keyword 'Var' has function scope. Anywhere in the function, the variable
     specified using var is accessible but in ‘let’ the scope of a variable declared with
     the 'let' keyword is limited to the block in which it is declared. Let's start with a
     Block Scope.
  3. 'var' declares a variable that will be hoisted but 'let' declares a variable that will
     be hoisted.
6. Explain Implicit Type Coercion in javascript.
Implicit type coercion in javascript is the automatic conversion of value from one
data type to another. It takes place when the operands of an expression are of
different data types.
     String coercion
Page 11                                                            © Copyright by Interviewbit
                                                            JavaScript Interview Questions
String coercion takes place while using the ‘ + ‘ operator. When a number is added to
a string, the number type is always converted to the string type.
Example 1:
  var x = 3;
  var y = "3";
  x + y // Returns "33"
Example 2:
  var x = 24;
  var y = "Hello";
  x + y   // Returns "24Hello";
  Note - ‘ + ‘ operator when used to add two numbers, outputs a number. The
  same ‘ + ‘ operator when used to add two strings, outputs the concatenated
  string:
  var name = "Vivek";
  var surname = " Bisht";
  name + surname     // Returns "Vivek Bisht"
Let’s understand both the examples where we have added a number to a string,
When JavaScript sees that the operands of the expression x + y are of different types (
one being a number type and the other being a string type ), it converts the number
type to the string type and then performs the operation. Since a er conversion, both
the variables are of string type, the ‘ + ‘ operator outputs the concatenated string
“33” in the first example and “24Hello” in the second example.
Page 12                                                         © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  Note - Type coercion also takes place when using the ‘ - ‘ operator, but the
  difference while using ‘ - ‘ operator is that, a string is converted to a number
  and then subtraction takes place.
  var x = 3;
  Var y = "3";
  x - y    //Returns 0 since the variable y (string type) is converted to a number type
     Boolean Coercion
Boolean coercion takes place when using logical operators, ternary operators, if
statements, and loop checks. To understand boolean coercion in if statements and
operators, we need to understand truthy and falsy values.
Truthy values are those which will be converted (coerced) to true. Falsy values are
those which will be converted to false.
All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.
If statements:
Example:
  var x = 0;
  var y = 23;
  if(x) { console.log(x) }   // The code inside this block will not run since the value o
  if(y) { console.log(y) }   // The code inside this block will run since the value of y
     Logical operators:
Page 13                                                          © Copyright by Interviewbit
                                                                   JavaScript Interview Questions
Logical operators in javascript, unlike operators in other programming languages, do
not return true or false. They always return one of the operands.
OR ( | | ) operator - If the first value is truthy, then the first value is returned.
Otherwise, always the second value gets returned.
AND ( && ) operator - If both the values are truthy, always the second value is
returned. If the first value is falsy then the first value is returned or if the second value
is falsy then the second value is returned.
Example:
  var x = 220;
  var y = "Hello";
  var z = undefined;
  x | | y     // Returns 220 since the first value is truthy
  x | | z    // Returns 220 since the first value is truthy
  x && y     // Returns "Hello" since both the values are truthy
  y && z    // Returns undefined since the second value is falsy
  if( x && y ){
    console.log("Code runs" ); // This block runs because x && y returns "Hello" (Truthy)
  }
  if( x || z ){
    console.log("Code runs");    // This block runs because x || y returns 220(Truthy)
  }
     Equality Coercion
Page 14                                                                © Copyright by Interviewbit
                                                              JavaScript Interview Questions
Equality coercion takes place when using ‘ == ‘ operator. As we have stated before
The ‘ == ‘ operator compares values and not types.
While the above statement is a simple way to explain == operator, it’s not completely
true
The reality is that while using the ‘==’ operator, coercion takes place.
The ‘==’ operator, converts both the operands to the same type and then compares
them.
Example:
  var a = 12;
  var b = "12";
  a == b // Returns true because both 'a' and 'b' are converted to the same type and then
Coercion does not take place when using the ‘===’ operator. Both operands are not
converted to the same type in the case of ‘===’ operator.
Example:
  var a = 226;
  var b = "226";
  a === b // Returns false because coercion does not take place and the    operands are of
7. Is javascript a statically typed or a dynamically typed
   language?
JavaScript is a dynamically typed language. In a dynamically typed language, the
type of a variable is checked during run-time in contrast to a statically typed
language, where the type of a variable is checked during compile-time.
Page 15                                                           © Copyright by Interviewbit
                                                             JavaScript Interview Questions
Since javascript is a loosely(dynamically) typed language, variables in JS are not
associated with any type. A variable can hold the value of any data type.
For example, a variable that is assigned a number type can be converted to a string
type:
  var a = 23;
  var a = "Hello World!";
8. What is NaN property in JavaScript?
NaN property represents the “Not-a-Number” value. It indicates a value that is not a
legal number.
typeof of NaN will return a Number.
To check if a value is NaN, we use the isNaN() function,
  Note- isNaN() function converts the given value to a Number type, and then
  equates to NaN.
Page 16                                                          © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  isNaN("Hello") // Returns true
  isNaN(345)   // Returns false
  isNaN('1') // Returns false, since '1' is converted to Number type which results in 0
  isNaN(true) // Returns false, since true converted to Number type results in 1 ( a numb
  isNaN(false) // Returns false
  isNaN(undefined) // Returns true
9. Explain passed by value and passed by reference.
In JavaScript, primitive data types are passed by value and non-primitive data
types are passed by reference.
For understanding passed by value and passed by reference, we need to understand
what happens when we create a variable and assign a value to it,
  var x = 2;
In the above example, we created a variable x and assigned it a value of “2”. In the
background, the “=” (assign operator) allocates some space in the memory, stores
the value “2” and returns the location of the allocated memory space. Therefore, the
variable x in the above code points to the location of the memory space instead of
pointing to the value 2 directly.
Assign operator behaves differently when dealing with primitive and non-primitive
data types,
Assign operator dealing with primitive types:
Page 17                                                          © Copyright by Interviewbit
                                                                JavaScript Interview Questions
  var y = 234;
  var z = y;
In the above example, the assign operator knows that the value assigned to y is a
primitive type (number type in this case), so when the second line code executes,
where the value of y is assigned to z, the assign operator takes the value of y (234)
and allocates a new space in the memory and returns the address. Therefore,
variable z is not pointing to the location of variable y, instead, it is pointing to a new
location in the memory.
  var y = #8454; // y pointing to address of the value 234
  var z = y;
  var z = #5411; // z pointing to a completely new address of the value 234
  // Changing the value of y
  y = 23;
  console.log(z); // Returns 234, since z points to a new address in the memory so chang
Page 18                                                             © Copyright by Interviewbit
                                                              JavaScript Interview Questions
From the above example, we can see that primitive data types when passed to
another variable, are passed by value. Instead of just assigning the same address to
another variable, the value is passed and new space of memory is created.
Assign operator dealing with non-primitive types:
  var obj = { name: "Vivek", surname: "Bisht" };
  var obj2 = obj;
In the above example, the assign operator directly passes the location of the variable
obj to the variable obj2. In other words, the reference of the variable obj is passed to
the variable obj2.
Page 19                                                           © Copyright by Interviewbit
                                                              JavaScript Interview Questions
  var obj = #8711;   // obj pointing to address of { name: "Vivek", surname: "Bisht" }
  var obj2 = obj;
  var obj2 = #8711; // obj2 pointing to the same address
  // changing the value of obj1
  obj1.name = "Akki";
  console.log(obj2);
  // Returns {name:"Akki", surname:"Bisht"} since both the variables are pointing to the
From the above example, we can see that while passing non-primitive data types, the
assign operator directly passes the address (reference).
Therefore, non-primitive data types are always passed by reference.
10. What is an Immediately Invoked Function in JavaScript?
An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a
function that runs as soon as it is defined.
Syntax of IIFE :
  (function(){
    // Do something;
  })();
To understand IIFE, we need to understand the two sets of parentheses that are
added while creating an IIFE :
The first set of parenthesis:
  (function (){
     //Do something;
  })
Page 20                                                           © Copyright by Interviewbit
                                                              JavaScript Interview Questions
While executing javascript code, whenever the compiler sees the word “function”, it
assumes that we are declaring a function in the code. Therefore, if we do not use the
first set of parentheses, the compiler throws an error because it thinks we are
declaring a function, and by the syntax of declaring a function, a function should
always have a name.
  function() {
    //Do something;
  }
  // Compiler gives an error since the syntax of declaring a function is wrong in the cod
To remove this error, we add the first set of parenthesis that tells the compiler that
the function is not a function declaration, instead, it’s a function expression.
The second set of parenthesis:
  (function (){
    //Do something;
  })();
From the definition of an IIFE, we know that our code should run as soon as it is
defined. A function runs only when it is invoked. If we do not invoke the function, the
function declaration is returned:
  (function (){
    // Do something;
  })
  // Returns the function declaration
Therefore to invoke the function, we use the second set of parenthesis.
11. What do you mean by strict mode in javascript and
    characteristics of javascript strict-mode?
Page 21                                                           © Copyright by Interviewbit
                                                             JavaScript Interview Questions
In ECMAScript 5, a new feature called JavaScript Strict Mode allows you to write a
code or a function in a "strict" operational environment. In most cases, this language
is 'not particularly severe' when it comes to throwing errors. In 'Strict mode,'
however, all forms of errors, including silent errors, will be thrown. As a result,
debugging becomes a lot simpler. Thus programmer's chances of making an error
are lowered.
Characteristics of strict mode in javascript
  1. Duplicate arguments are not allowed by developers.
  2. In strict mode, you won't be able to use the JavaScript keyword as a parameter
     or function name.
  3. The 'use strict' keyword is used to define strict mode at the start of the script.
     Strict mode is supported by all browsers.
  4. Engineers will not be allowed to create global variables in 'Strict Mode.
12. Explain Higher Order Functions in javascript.
Functions that operate on other functions, either by taking them as arguments or
by returning them, are called higher-order functions.
Higher-order functions are a result of functions being first-class citizens in
javascript.
Examples of higher-order functions:
  function higherOrder(fn) {
    fn();
  }
  higherOrder(function() { console.log("Hello world") });
Page 22                                                          © Copyright by Interviewbit
                                                            JavaScript Interview Questions
  function higherOrder2() {
    return function() {
      return "Do something";
    }
  }
  var x = higherOrder2();
  x()   // Returns "Do something"
13. Explain “this” keyword.
The “this” keyword refers to the object that the function is a property of.
The value of the “this” keyword will always depend on the object that is invoking
the function.\
Confused? Let’s understand the above statements by examples:
  function doSomething() {
    console.log(this);
  }
  doSomething();
What do you think the output of the above code will be?
  Note - Observe the line where we are invoking the function.
Check the definition again:
  The “this” keyword refers to the object that the function is a property of.
In the above code, the function is a property of which object?
Since the function is invoked in the global context, the function is a property of the
global object.
Therefore, the output of the above code will be the global object. Since we ran the
above code inside the browser, the global object is the window object.
Example 2:
Page 23                                                          © Copyright by Interviewbit
                                                              JavaScript Interview Questions
  var obj = {
      name: "vivek",
      getName: function(){
      console.log(this.name);
    }
  }
  obj.getName();
In the above code, at the time of invocation, the getName function is a property of
the object obj , therefore, this keyword will refer to the object obj, and hence the
output will be “vivek”.
Example 3:
   var obj = {
      name: "vivek",
      getName: function(){
      console.log(this.name);
    }
  var getName = obj.getName;
  var obj2 = {name:"akshay", getName };
  obj2.getName();
Can you guess the output here?
The output will be “akshay”.
Although the getName function is declared inside the object obj, at the time of
invocation, getName() is a property of obj2, therefore the “this” keyword will refer to
obj2.
The silly way to understand the “this” keyword is, whenever the function is invoked,
check the object before the dot. The value of this . keyword will always be the object
before the dot.
If there is no object before the dot-like in example1, the value of this keyword will be
the global object.
Page 24                                                           © Copyright by Interviewbit
                                                                JavaScript Interview Questions
Example 4:
  var obj1 = {
      address : "Mumbai,India",
      getAddress: function(){
      console.log(this.address);
    }
  }
  var getAddress = obj1.getAddress;
  var obj2 = {name:"akshay"};
  obj2.getAddress();
Can you guess the output?
The output will be an error.
Although in the code above, this keyword refers to the object obj2, obj2 does not
have the property “address”‘, hence the getAddress function throws an error.
14. What do you mean by Self Invoking Functions?
Without being requested, a self-invoking expression is automatically invoked
(initiated). If a function expression is followed by (), it will execute automatically. A
function declaration cannot be invoked by itself.
Normally, we declare a function and call it, however, anonymous functions may be
used to run a function automatically when it is described and will not be called again.
And there is no name for these kinds of functions.
15. Explain call(), apply() and, bind() methods.
1. call():
     It’s a predefined method in javascript.
     This method invokes a method (function) by specifying the owner object.
     Example 1:
Page 25                                                             © Copyright by Interviewbit
                                                            JavaScript Interview Questions
  function sayHello(){
    return "Hello " + this.name;
  }
  var obj = {name: "Sandy"};
  sayHello.call(obj);
  // Returns "Hello Sandy"
     call() method allows an object to use the method (function) of another object.
     Example 2:
  var person = {
    age: 23,
    getAge: function(){
      return this.age;
    }
  }
  var person2 = {age: 54};
  person.getAge.call(person2);
  // Returns 54
     call() accepts arguments:
  function saySomething(message){
    return this.name + " is " + message;
  }
  var person4 = {name: "John"};
  saySomething.call(person4, "awesome");
  // Returns "John is awesome"
apply()
The apply method is similar to the call() method. The only difference is that,
call() method takes arguments separately whereas, apply() method takes
arguments as an array.
Page 26                                                         © Copyright by Interviewbit
                                                                   JavaScript Interview Questions
  function saySomething(message){
    return this.name + " is " + message;
  }
  var person4 = {name: "John"};
  saySomething.apply(person4, ["awesome"]);
2. bind():
     This method returns a new function, where the value of “this” keyword will be
     bound to the owner object, which is provided as a parameter.
     Example with arguments:
  var bikeDetails = {
      displayDetails: function(registrationNumber,brandName){
      return this.name+ " , "+ "bike details: "+ registrationNumber + " , " + brandName;
    }
  }
  var person1 = {name:    "Vivek"};
  var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, "TS0122", "Bullet");
  // Binds the displayDetails function to the person1 object
  detailsOfPerson1();
  // Returns Vivek, bike details: TS0452, Thunderbird
16. What is the difference between exec () and test () methods in
    javascript?
     test () and exec () are RegExp expression methods used in javascript.
     We'll use exec () to search a string for a specific pattern, and if it finds it, it'll
     return the pattern directly; else, it'll return an 'empty' result.
     We will use a test () to find a string for a specific pattern. It will return the
     Boolean value 'true' on finding the given text otherwise, it will return 'false'.
17. What is currying in JavaScript?
Currying is an advanced technique to transform a function of arguments n, to n
functions of one or fewer arguments.
Page 27                                                                © Copyright by Interviewbit
                                                             JavaScript Interview Questions
Example of a curried function:
  function add (a) {
    return function(b){
      return a + b;
    }
  }
  add(3)(4)
For Example, if we have a function f(a,b), then the function a er currying, will be
transformed to f(a)(b).
By using the currying technique, we do not change the functionality of a function, we
just change the way it is invoked.
Let’s see currying in action:
  function multiply(a,b){
    return a*b;
  }
  function currying(fn){
    return function(a){
      return function(b){
        return fn(a,b);
      }
    }
  }
  var curriedMultiply = currying(multiply);
  multiply(4, 3); // Returns 12
  curriedMultiply(4)(3); // Also returns 12
As one can see in the code above, we have transformed the function multiply(a,b) to
a function curriedMultiply , which takes in one parameter at a time.
18. What are some advantages of using External JavaScript?
Page 28                                                          © Copyright by Interviewbit
                                                              JavaScript Interview Questions
External JavaScript is the JavaScript Code (script) written in a separate file with the
extension.js, and then we link that file inside the <head> or <body> element of the
HTML file where the code is to be placed.
Some advantages of external javascript are
  1. It allows web designers and developers to collaborate on HTML and javascript
     files.
  2. We can reuse the code.
  3. Code readability is simple in external javascript.
19. Explain Scope and Scope Chain in javascript.
Scope in JS determines the accessibility of variables and functions at various parts of
one’s code.
In general terms, the scope will let us know at a given part of code, what are variables
and functions we can or cannot access.
There are three types of scopes in JS:
     Global Scope
     Local or Function Scope
     Block Scope
Global Scope: Variables or functions declared in the global namespace have global
scope, which means all the variables and functions having global scope can be
accessed from anywhere inside the code.
  var globalVariable = "Hello world";
  function sendMessage(){
    return globalVariable; // can access globalVariable since it's written in global spac
  }
  function sendMessage2(){
    return sendMessage(); // Can access sendMessage function since it's written in global
  }
  sendMessage2(); // Returns “Hello world”
Page 29                                                           © Copyright by Interviewbit
                                                               JavaScript Interview Questions
Function Scope: Any variables or functions declared inside a function have
local/function scope, which means that all the variables and functions declared
inside a function, can be accessed from within the function and not outside of it.
  function awesomeFunction(){
    var a = 2;
      var multiplyBy2 = function(){
        console.log(a*2); // Can access variable "a" since a and multiplyBy2 both are writt
      }
  }
  console.log(a); // Throws reference error since a is written in local scope and cannot
  multiplyBy2(); // Throws reference error since multiplyBy2 is written in local scope
Block Scope: Block scope is related to the variables declared using let and const.
Variables declared with var do not have block scope. Block scope tells us that any
variable declared inside a block { }, can be accessed only inside that block and cannot
be accessed outside of it.
  {
      let x = 45;
  }
  console.log(x); // Gives reference error since x cannot be accessed outside of the bloc
  for(let i=0; i<2; i++){
    // do something
  }
  console.log(i); // Gives reference error since i cannot be accessed outside of the for
Scope Chain: JavaScript engine also uses Scope to find variables. Let’s understand
that using an example:
Page 30                                                            © Copyright by Interviewbit
                                                               JavaScript Interview Questions
  var y = 24;
  function favFunction(){
    var x = 667;
    var anotherFavFunction = function(){
      console.log(x); // Does not find x inside anotherFavFunction, so looks for variable
    }
      var yetAnotherFavFunction = function(){
        console.log(y); // Does not find y inside yetAnotherFavFunction, so looks for varia
      }
      anotherFavFunction();
      yetAnotherFavFunction();
  }
  favFunction();
As you can see in the code above, if the javascript engine does not find the
variable in local scope, it tries to check for the variable in the outer scope. If the
variable does not exist in the outer scope, it tries to find the variable in the global
scope.
If the variable is not found in the global space as well, a reference error is thrown.
20. Explain Closures in JavaScript.
Closures are an ability of a function to remember the variables and functions that are
declared in its outer scope.
  var Person = function(pName){
    var name = pName;
      this.getName = function(){
        return name;
      }
  }
  var person = new Person("Neelesh");
  console.log(person.getName());
Let’s understand closures by example:
Page 31                                                            © Copyright by Interviewbit
                                                                JavaScript Interview Questions
  function randomFunc(){
    var obj1 = {name:"Vivian", age:45};
      return function(){
        console.log(obj1.name + " is "+ "awesome"); // Has access to obj1 even when the ran
      }
  }
  var initialiseClosure = randomFunc(); // Returns a function
  initialiseClosure();
Let’s understand the code above,
The function randomFunc() gets executed and returns a function when we assign it
to a variable:
  var initialiseClosure = randomFunc();
The returned function is then executed when we invoke initialiseClosure:
  initialiseClosure();
The line of code above outputs “Vivian is awesome” and this is possible because of
closure.
  console.log(obj1.name + " is "+ "awesome");
When the function randomFunc() runs, it seems that the returning function is using
the variable obj1 inside it:
Page 32                                                             © Copyright by Interviewbit
                                                             JavaScript Interview Questions
Therefore randomFunc(), instead of destroying the value of obj1 a er execution,
saves the value in the memory for further reference. This is the reason why the
returning function is able to use the variable declared in the outer scope even a er
the function is already executed.
This ability of a function to store a variable for further reference even a er it is
executed is called Closure.
21. Mention some advantages of javascript.
There are many advantages of javascript. Some of them are
  1. Javascript is executed on the client-side as well as server-side also. There are a
     variety of Frontend Frameworks that you may study and utilize. However, if you
     want to use JavaScript on the backend, you'll need to learn NodeJS. It is
     currently the only JavaScript framework that may be used on the backend.
  2. Javascript is a simple language to learn.
  3. Web pages now have more functionality because of Javascript.
  4. To the end-user, Javascript is quite quick.
22. What are object prototypes?
All javascript objects inherit properties from a prototype. For example,
     Date objects inherit properties from the Date prototype
     Math objects inherit properties from the Math prototype
     Array objects inherit properties from the Array prototype.
     On top of the chain is Object.prototype. Every prototype inherits properties and
     methods from the Object.prototype.
     A prototype is a blueprint of an object. The prototype allows us to use
     properties and methods on an object even if the properties and methods do not
     exist on the current object.
Let’s see prototypes help us use methods and properties:
Page 33                                                          © Copyright by Interviewbit
                                                               JavaScript Interview Questions
  var arr = [];
  arr.push(2);
  console.log(arr); // Outputs [2]
In the code above, as one can see, we have not defined any property or method
called push on the array “arr” but the javascript engine does not throw an error.
The reason is the use of prototypes. As we discussed before, Array objects inherit
properties from the Array prototype.
The javascript engine sees that the method push does not exist on the current array
object and therefore, looks for the method push inside the Array prototype and it
finds the method.
Whenever the property or method is not found on the current object, the javascript
engine will always try to look in its prototype and if it still does not exist, it looks
inside the prototype's prototype and so on.
23. What are callbacks?
Page 34                                                            © Copyright by Interviewbit
                                                            JavaScript Interview Questions
A callback is a function that will be executed a er another function gets executed. In
javascript, functions are treated as first-class citizens, they can be used as an
argument of another function, can be returned by another function, and can be used
as a property of an object.
Functions that are used as an argument to another function are called callback
functions. Example:
  function divideByHalf(sum){
    console.log(Math.floor(sum / 2));
  }
  function multiplyBy2(sum){
    console.log(sum * 2);
  }
  function operationOnSum(num1,num2,operation){
    var sum = num1 + num2;
    operation(sum);
  }
  operationOnSum(3, 3, divideByHalf); // Outputs 3
  operationOnSum(5, 5, multiplyBy2); // Outputs 20
     In the code above, we are performing mathematical operations on the sum of
     two numbers. The operationOnSum function takes 3 arguments, the first
     number, the second number, and the operation that is to be performed on their
     sum (callback).
     Both divideByHalf and multiplyBy2 functions are used as callback functions in
     the code above.
     These callback functions will be executed only a er the function
     operationOnSum is executed.
     Therefore, a callback is a function that will be executed a er another function
     gets executed.
24. What are the types of errors in javascript?
There are two types of errors in javascript.
Page 35                                                         © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  1. Syntax error: Syntax errors are mistakes or spelling problems in the code that
     cause the program to not execute at all or to stop running halfway through.
     Error messages are usually supplied as well.
  2. Logical error: Reasoning mistakes occur when the syntax is proper but the logic
     or program is incorrect. The application executes without problems in this case.
     However, the output findings are inaccurate. These are sometimes more difficult
     to correct than syntax issues since these applications do not display error signals
     for logic faults.
25. What is memoization?
Memoization is a form of caching where the return value of a function is cached
based on its parameters. If the parameter of that function is not changed, the cached
version of the function is returned.
Let’s understand memoization, by converting a simple function to a memoized
function:
  Note- Memoization is used for expensive function calls but in the following
  example, we are considering a simple function for understanding the concept of
  memoization better.
Consider the following function:
  function addTo256(num){
    return num + 256;
  }
  addTo256(20); // Returns 276
  addTo256(40); // Returns 296
  addTo256(20); // Returns 276
Page 36                                                          © Copyright by Interviewbit
                                                           JavaScript Interview Questions
In the code above, we have written a function that adds the parameter to 256 and
returns it.
When we are calling the function addTo256 again with the same parameter (“20” in
the case above), we are computing the result again for the same parameter.
Computing the result with the same parameter, again and again, is not a big deal in
the above case, but imagine if the function does some heavy-duty work, then,
computing the result again and again with the same parameter will lead to wastage
of time.
This is where memoization comes in, by using memoization we can store(cache) the
computed results based on the parameters. If the same parameter is used again
while invoking the function, instead of computing the result, we directly return the
stored (cached) value.
Let’s convert the above function addTo256, to a memoized function:
  function memoizedAddTo256(){
    var cache = {};
    return function(num){
      if(num in cache){
        console.log("cached value");
        return cache[num]
      }
      else{
        cache[num] = num + 256;
        return cache[num];
      }
    }
  }
  var memoizedFunc = memoizedAddTo256();
  memoizedFunc(20); // Normal return
  memoizedFunc(20); // Cached return
In the code above, if we run the memoizedFunc function with the same parameter,
instead of computing the result again, it returns the cached result.
Page 37                                                        © Copyright by Interviewbit
                                                              JavaScript Interview Questions
  Note- Although using memoization saves time, it results in larger consumption
  of memory since we are storing all the computed results.
26. What is recursion in a programming language?
Recursion is a technique to iterate over an operation by having a function call itself
repeatedly until it arrives at a result.
  function add(number) {
    if (number <= 0) {
      return 0;
    } else {
      return number + add(number - 1);
    }
  }
  add(3) => 3 + add(2)
            3 + 2 + add(1)
            3 + 2 + 1 + add(0)
            3 + 2 + 1 + 0 = 6
Example of a recursive function:
The following function calculates the sum of all the elements in an array by using
recursion:
  function computeSum(arr){
    if(arr.length === 1){
      return arr[0];
    }
    else{
      return arr.pop() + computeSum(arr);
    }
  }
  computeSum([7, 8, 9, 99]); // Returns 123
27. What is the use of a constructor function in javascript?
Constructor functions are used to create objects in javascript.
When do we use constructor functions?
Page 38                                                           © Copyright by Interviewbit
                                                            JavaScript Interview Questions
If we want to create multiple objects having similar properties and methods,
constructor functions are used.
  Note- The name of a constructor function should always be written in Pascal
  Notation: every word should start with a capital letter.
Example:
  function Person(name,age,gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
  }
  var person1 = new Person("Vivek", 76, "male");
  console.log(person1);
  var person2 = new Person("Courtney", 34, "female");
  console.log(person2);
In the code above, we have created a constructor function named Person. Whenever
we want to create a new object of the type Person, We need to create it using the new
keyword:
  var person3 = new Person("Lilly", 17, "female");
The above line of code will create a new object of the type Person. Constructor
functions allow us to group similar objects.
28. What is DOM?
Page 39                                                         © Copyright by Interviewbit
                                                            JavaScript Interview Questions
     DOM stands for Document Object Model. DOM is a programming interface for
     HTML and XML documents.
     When the browser tries to render an HTML document, it creates an object based
     on the HTML document called DOM. Using this DOM, we can manipulate or
     change various elements inside the HTML document.
     Example of how HTML code gets converted to DOM:
29. Which method is used to retrieve a character from a certain
    index?
The charAt() function of the JavaScript string finds a char element at the supplied
index. The index number begins at 0 and continues up to n-1, Here n is the string
length. The index value must be positive, higher than, or the same as the string
length.
30. What do you mean by BOM?
Browser Object Model is known as BOM. It allows users to interact with the browser. A
browser's initial object is a window. As a result, you may call all of the window's
functions directly or by referencing the window. The document, history, screen,
navigator, location, and other attributes are available in the window object.
Page 40                                                         © Copyright by Interviewbit
                                                              JavaScript Interview Questions
31. What is the distinction between client-side and server-side
    JavaScript?
Client-side JavaScript is made up of two parts, a fundamental language and
predefined objects for performing JavaScript in a browser. JavaScript for the client is
automatically included in the HTML pages. At runtime, the browser understands this
script.
Client-side JavaScript is similar to server-side JavaScript. It includes JavaScript that
will execute on a server. Only a er processing is the server-side JavaScript deployed.
JavaScript Interview Questions for Experienced
32. What are arrow functions?
Arrow functions were introduced in the ES6 version of javascript. They provide us
with a new and shorter syntax for declaring functions. Arrow functions can only be
used as a function expression.
Let’s compare the normal function declaration and the arrow function declaration in
detail:
Page 41                                                           © Copyright by Interviewbit
                                                            JavaScript Interview Questions
  // Traditional Function Expression
  var add = function(a,b){
    return a + b;
  }
  // Arrow Function Expression
  var arrowAdd = (a,b) => a + b;
Arrow functions are declared without the function keyword. If there is only one
returning expression then we don’t need to use the return keyword as well in an
arrow function as shown in the example above. Also, for functions having just one
line of code, curly braces { } can be omitted.
  // Traditional function expression
  var multiplyBy2 = function(num){
    return num * 2;
  }
  // Arrow function expression
  var arrowMultiplyBy2 = num => num * 2;
If the function takes in only one argument, then the parenthesis () around the
parameter can be omitted as shown in the code above.
  var obj1 = {
    valueOfThis: function(){
      return this;
    }
  }
  var obj2 = {
    valueOfThis: ()=>{
      return this;
    }
  }
  obj1.valueOfThis(); // Will return the object obj1
  obj2.valueOfThis(); // Will return window/global object
Page 42                                                         © Copyright by Interviewbit
                                                               JavaScript Interview Questions
The biggest difference between the traditional function expression and the arrow
function is the handling of this keyword. By general definition, this keyword always
refers to the object that is calling the function. As you can see in the code above,
obj1.valueOfThis() returns obj1 since this keyword refers to the object calling the
function.
In the arrow functions, there is no binding of this keyword. This keyword inside an
arrow function does not refer to the object calling it. It rather inherits its value from
the parent scope which is the window object in this case. Therefore, in the code
above, obj2.valueOfThis() returns the window object.
33. What do mean by prototype design pattern?
The Prototype Pattern produces different objects, but instead of returning
uninitialized objects, it produces objects that have values replicated from a template
– or sample – object. Also known as the Properties pattern, the Prototype pattern is
used to create prototypes.
The introduction of business objects with parameters that match the database's
default settings is a good example of where the Prototype pattern comes in handy.
The default settings for a newly generated business object are stored in the
prototype object.
The Prototype pattern is hardly used in traditional languages, however, it is used in
the development of new objects and templates in JavaScript, which is a prototypal
language.
34. Differences between declaring variables using var, let and
    const.
Before the ES6 version of javascript, only the keyword var was used to declare
variables. With the ES6 Version, keywords let and const were introduced to declare
variables.
Page 43                                                            © Copyright by Interviewbit
                                                             JavaScript Interview Questions
          keyword                   const          let         var
          global scope              no             no          yes
          function scope            yes            yes         yes
          block scope               yes            yes         no
          can be reassigned         no             yes         yes
Let’s understand the differences with examples:
  var variable1 = 23;
  let variable2 = 89;
  function catchValues(){
    console.log(variable1);
    console.log(variable2);
  // Both the variables can be accessed anywhere since they are declared in the global sc
  }
  window.variable1; // Returns the value 23
  window.variable2; // Returns undefined
Page 44                                                          © Copyright by Interviewbit
                                                           JavaScript Interview Questions
     The variables declared with the let keyword in the global scope behave just like
     the variable declared with the var keyword in the global scope.
     Variables declared in the global scope with var and let keywords can be accessed
     from anywhere in the code.
     But, there is one difference! Variables that are declared with the var keyword in
     the global scope are added to the window/global object. Therefore, they can be
     accessed using window.variableName.
     Whereas, the variables declared with the let keyword are not added to the global
     object, therefore, trying to access such variables using window.variableName
     results in an error.
var vs let in functional scope
  function varVsLetFunction(){
    let awesomeCar1 = "Audi";
    var awesomeCar2 = "Mercedes";
  }
  console.log(awesomeCar1); // Throws an error
  console.log(awesomeCar2); // Throws an error
Variables are declared in a functional/local scope using var and let keywords behave
exactly the same, meaning, they cannot be accessed from outside of the scope.
Page 45                                                        © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  {
      var variable3 = [1, 2, 3, 4];
  }
  console.log(variable3); // Outputs [1,2,3,4]
  {
      let variable4 = [6, 55, -1, 2];
  }
  console.log(variable4); // Throws error
  for(let i = 0; i < 2; i++){
    //Do something
  }
  console.log(i); // Throws error
  for(var j = 0; j < 2; i++){
    // Do something
  }
  console.log(j) // Outputs 2
      In javascript, a block means the code written inside the curly braces {}.
      Variables declared with var keyword do not have block scope. It means a
      variable declared in block scope {} with the var keyword is the same as declaring
      the variable in the global scope.
      Variables declared with let keyword inside the block scope cannot be accessed
      from outside of the block.
Const keyword
      Variables with the const keyword behave exactly like a variable declared with
      the let keyword with only one difference, any variable declared with the const
      keyword cannot be reassigned.
      Example:
Page 46                                                          © Copyright by Interviewbit
                                                            JavaScript Interview Questions
  const x = {name:"Vivek"};
  x = {address: "India"}; // Throws an error
  x.name = "Nikhil"; // No error is thrown
  const y = 23;
  y = 44; // Throws an error
In the code above, although we can change the value of a property inside the variable
declared with const keyword, we cannot completely reassign the variable itself.
35. What is the rest parameter and spread operator?
Both rest parameter and spread operator were introduced in the ES6 version of
javascript.
Rest parameter ( … ):
     It provides an improved way of handling the parameters of a function.
     Using the rest parameter syntax, we can create functions that can take a variable
     number of arguments.
     Any number of arguments will be converted into an array using the rest
     parameter.
     It also helps in extracting all or some parts of the arguments.
     Rest parameters can be used by applying three dots (...) before the parameters.
Page 47                                                         © Copyright by Interviewbit
                                                          JavaScript Interview Questions
  function extractingArgs(...args){
    return args[1];
  }
  // extractingArgs(8,9,1); // Returns 9
  function addAllArgs(...args){
    let sumOfArgs = 0;
    let i = 0;
    while(i < args.length){
      sumOfArgs += args[i];
      i++;
    }
    return sumOfArgs;
  }
  addAllArgs(6, 5, 7, 99); // Returns 117
  addAllArgs(1, 3, 4); // Returns 8
**Note- Rest parameter should always be used at the last parameter of a
function:
  // Incorrect way to use rest parameter
  function randomFunc(a,...args,c){
  //Do something
  }
  // Correct way to use rest parameter
  function randomFunc2(a,b,...args){
  //Do something
  }
     Spread operator (…): Although the syntax of the spread operator is exactly the
     same as the rest parameter, the spread operator is used to spreading an array,
     and object literals. We also use spread operators where one or more arguments
     are expected in a function call.
Page 48                                                       © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  function addFourNumbers(num1,num2,num3,num4){
    return num1 + num2 + num3 + num4;
  }
  let fourNumbers = [5, 6, 7, 8];
  addFourNumbers(...fourNumbers);
  // Spreads [5,6,7,8] as 5,6,7,8
  let array1 = [3, 4, 5, 6];
  let clonedArray1 = [...array1];
  // Spreads the array into 3,4,5,6
  console.log(clonedArray1); // Outputs [3,4,5,6]
  let obj1 = {x:'Hello', y:'Bye'};
  let clonedObj1 = {...obj1}; // Spreads and clones obj1
  console.log(obj1);
  let obj2 = {z:'Yes', a:'No'};
  let mergedObj = {...obj1, ...obj2}; // Spreads both the objects and merges it
  console.log(mergedObj);
  // Outputs {x:'Hello', y:'Bye',z:'Yes',a:'No'};
  ***Note- Key differences between rest parameter and spread operator:
          Rest parameter is used to take a variable number of arguments and turns
          them into an array while the spread operator takes an array or an object
          and spreads it
          Rest parameter is used in function declaration whereas the spread operator
          is used in function calls.
36. In JavaScript, how many different methods can you make an
    object?
In JavaScript, there are several ways to declare or construct an object.
Page 49                                                          © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  1. Object.
  2. using Class.
  3. create Method.
  4. Object Literals.
  5. using Function.
  6. Object Constructor.
37. What is the use of promises in javascript?
Promises are used to handle asynchronous operations in javascript.
Before promises, callbacks were used to handle asynchronous operations. But due to
the limited functionality of callbacks, using multiple callbacks to handle
asynchronous code can lead to unmanageable code.
Promise object has four states -
     Pending - Initial state of promise. This state represents that the promise has
     neither been fulfilled nor been rejected, it is in the pending state.
     Fulfilled - This state represents that the promise has been fulfilled, meaning the
     async operation is completed.
     Rejected - This state represents that the promise has been rejected for some
     reason, meaning the async operation has failed.
     Settled - This state represents that the promise has been either rejected or
     fulfilled.
A promise is created using the Promise constructor which takes in a callback
function with two parameters, resolve and reject respectively.
Page 50                                                          © Copyright by Interviewbit
                                                              JavaScript Interview Questions
resolve is a function that will be called when the async operation has been
successfully completed.
reject is a function that will be called, when the async operation fails or if some error
occurs.
Example of a promise:
Promises are used to handle asynchronous operations like server requests, for
ease of understanding, we are using an operation to calculate the sum of three
elements.
In the function below, we are returning a promise inside a function:
Page 51                                                           © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  function sumOfThreeElements(...elements){
    return new Promise((resolve,reject)=>{
      if(elements.length > 3 ){
        reject("Only three elements or less are allowed");
      }
      else{
        let sum = 0;
        let i = 0;
        while(i < elements.length){
          sum += elements[i];
          i++;
        }
        resolve("Sum has been calculated: "+sum);
      }
    })
  }
In the code above, we are calculating the sum of three elements, if the length of the
elements array is more than 3, a promise is rejected, or else the promise is resolved
and the sum is returned.
We can consume any promise by attaching then() and catch() methods to the
consumer.
then() method is used to access the result when the promise is fulfilled.
Page 52                                                          © Copyright by Interviewbit
                                                             JavaScript Interview Questions
catch() method is used to access the result/error when the promise is rejected. In the
code below, we are consuming the promise:
  sumOfThreeElements(4, 5, 6)
  .then(result=> console.log(result))
  .catch(error=> console.log(error));
  // In the code above, the promise is fulfilled so the then() method gets executed
  sumOfThreeElements(7, 0, 33, 41)
  .then(result => console.log(result))
  .catch(error=> console.log(error));
  // In the code above, the promise is rejected hence the catch() method gets executed
38. What are classes in javascript?
Introduced in the ES6 version, classes are nothing but syntactic sugars for
constructor functions. They provide a new way of declaring constructor functions in
javascript. Below are the examples of how classes are declared and used:
Page 53                                                          © Copyright by Interviewbit
                                                               JavaScript Interview Questions
  // Before ES6 version, using constructor functions
  function Student(name,rollNumber,grade,section){
    this.name = name;
    this.rollNumber = rollNumber;
    this.grade = grade;
    this.section = section;
  }
  // Way to add methods to a constructor function
  Student.prototype.getDetails = function(){
    return 'Name: ${this.name}, Roll no: ${this.rollNumber}, Grade: ${this.grade}, Sectio
  }
  let student1 = new Student("Vivek", 354, "6th", "A");
  student1.getDetails();
  // Returns Name: Vivek, Roll no:354, Grade: 6th, Section:A
  // ES6 version classes
  class Student{
    constructor(name,rollNumber,grade,section){
      this.name = name;
      this.rollNumber = rollNumber;
      this.grade = grade;
      this.section = section;
    }
      // Methods can be directly added inside the class
      getDetails(){
        return 'Name: ${this.name}, Roll no: ${this.rollNumber}, Grade:${this.grade}, Secti
      }
  }
  let student2 = new Student("Garry", 673, "7th", "C");
  student2.getDetails();
  // Returns Name: Garry, Roll no:673, Grade: 7th, Section:C
Key points to remember about classes:
      Unlike functions, classes are not hoisted. A class cannot be used before it is
      declared.
      A class can inherit properties and methods from other classes by using the
      extend keyword.
      All the syntaxes inside the class must follow the strict mode(‘use strict’) of
      javascript. An error will be thrown if the strict mode rules are not followed.
Page 54                                                            © Copyright by Interviewbit
                                                             JavaScript Interview Questions
39. What are generator functions?
Introduced in the ES6 version, generator functions are a special class of functions.
They can be stopped midway and then continue from where they had stopped.
Generator functions are declared with the function* keyword instead of the normal
function keyword:
  function* genFunc(){
    // Perform operation
  }
In normal functions, we use the return keyword to return a value and as soon as the
return statement gets executed, the function execution stops:
  function normalFunc(){
    return 22;
    console.log(2); // This line of code does not get executed
  }
In the case of generator functions, when called, they do not execute the code,
instead, they return a generator object. This generator object handles the execution.
  function* genFunc(){
    yield 3;
    yield 4;
  }
  genFunc(); // Returns Object [Generator] {}
The generator object consists of a method called next(), this method when called,
executes the code until the nearest yield statement, and returns the yield value.
For example, if we run the next() method on the above code:
  genFunc().next(); // Returns {value: 3, done:false}
Page 55                                                          © Copyright by Interviewbit
                                                              JavaScript Interview Questions
As one can see the next method returns an object consisting of a value and done
properties. Value property represents the yielded value. Done property tells us
whether the function code is finished or not. (Returns true if finished).
Generator functions are used to return iterators. Let’s see an example where an
iterator is returned:
  function* iteratorFunc() {
    let count = 0;
    for (let i = 0; i < 2; i++) {
        count++;
        yield i;
    }
    return count;
  }
  let iterator = iteratorFunc();
  console.log(iterator.next()); // {value:0,done:false}
  console.log(iterator.next()); // {value:1,done:false}
  console.log(iterator.next()); // {value:2,done:true}
As you can see in the code above, the last line returns done:true, since the code
reaches the return statement.
40. Explain WeakSet in javascript.
In javascript, a Set is a collection of unique and ordered elements. Just like Set,
WeakSet is also a collection of unique and ordered elements with some key
differences:
     Weakset contains only objects and no other type.
     An object inside the weakset is referenced weakly. This means, that if the object
     inside the weakset does not have a reference, it will be garbage collected.
     Unlike Set, WeakSet only has three methods, add() , delete() and has() .
Page 56                                                           © Copyright by Interviewbit
                                                              JavaScript Interview Questions
  const newSet = new Set([4, 5, 6, 7]);
  console.log(newSet);// Outputs Set {4,5,6,7}
  const newSet2 = new WeakSet([3, 4, 5]); //Throws an error
  let obj1 = {message:"Hello world"};
  const newSet3 = new WeakSet([obj1]);
  console.log(newSet3.has(obj1)); // true
41. Why do we use callbacks?
A callback function is a method that is sent as an input to another function (now let
us name this other function "thisFunction"), and it is performed inside the
thisFunction a er the function has completed execution.
JavaScript is a scripting language that is based on events. Instead of waiting for a
reply before continuing, JavaScript will continue to run while monitoring for
additional events. Callbacks are a technique of ensuring that a particular code does
not run until another code has completed its execution.
42. Explain WeakMap in javascript.
In javascript, Map is used to store key-value pairs. The key-value pairs can be of both
primitive and non-primitive types. WeakMap is similar to Map with key differences:
     The keys and values in weakmap should always be an object.
     If there are no references to the object, the object will be garbage collected.
  const map1 = new Map();
  map1.set('Value', 1);
  const map2 = new WeakMap();
  map2.set('Value', 2.3); // Throws an error
  let obj = {name:"Vivek"};
  const map3 = new WeakMap();
  map3.set(obj, {age:23});
43. What is Object Destructuring?
Object destructuring is a new way to extract elements from an object or an array.
Page 57                                                           © Copyright by Interviewbit
                                                             JavaScript Interview Questions
     Object destructuring: Before ES6 version:
  const classDetails = {
    strength: 78,
    benches: 39,
    blackBoard:1
  }
  const classStrength = classDetails.strength;
  const classBenches = classDetails.benches;
  const classBlackBoard = classDetails.blackBoard;
The same example using object destructuring:
  const classDetails = {
    strength: 78,
    benches: 39,
    blackBoard:1
  }
  const {strength:classStrength, benches:classBenches,blackBoard:classBlackBoard} = class
  console.log(classStrength); // Outputs 78
  console.log(classBenches); // Outputs 39
  console.log(classBlackBoard); // Outputs 1
As one can see, using object destructuring we have extracted all the elements inside
an object in one line of code. If we want our new variable to have the same name as
the property of an object we can remove the colon:
  const {strength:strength} = classDetails;
  // The above line of code can be written as:
  const {strength} = classDetails;
     Array destructuring: Before ES6 version:
  const   arr = [1, 2, 3, 4];
  const   first = arr[0];
  const   second = arr[1];
  const   third = arr[2];
  const   fourth = arr[3];
Page 58                                                          © Copyright by Interviewbit
                                                              JavaScript Interview Questions
The same example using object destructuring:
  const arr = [1, 2, 3, 4];
  const [first,second,third,fourth] = arr;
  console.log(first); // Outputs 1
  console.log(second); // Outputs 2
  console.log(third); // Outputs 3
  console.log(fourth); // Outputs 4
44. Difference between prototypal and classical inheritance
Programers build objects, which are representations of real-time entities, in
traditional OO programming. Classes and objects are the two sorts of abstractions. A
class is a generalization of an object, whereas an object is an abstraction of an actual
thing. A Vehicle, for example, is a specialization of a Car. As a result, automobiles
(class) are descended from vehicles (object).
Classical inheritance differs from prototypal inheritance in that classical inheritance
is confined to classes that inherit from those remaining classes, but prototypal
inheritance allows any object to be cloned via an object linking method. Despite
going into too many specifics, a prototype essentially serves as a template for those
other objects, whether they extend the parent object or not.
45. What is a Temporal Dead Zone?
Temporal Dead Zone is a behaviour that occurs with variables declared using let and
const keywords. It is a behaviour where we try to access a variable before it is
initialized. Examples of temporal dead zone:
  x = 23; // Gives reference error
  let x;
  function anotherRandomFunc(){
    message = "Hello"; // Throws a reference error
    let message;
  }
  anotherRandomFunc();
Page 59                                                           © Copyright by Interviewbit
                                                              JavaScript Interview Questions
In the code above, both in the global scope and functional scope, we are trying to
access variables that have not been declared yet. This is called the Temporal Dead
Zone.
46. What do you mean by JavaScript Design Patterns?
JavaScript design patterns are repeatable approaches for errors that arise
sometimes when building JavaScript browser applications. They truly assist us in
making our code more stable.
They are divided mainly into 3 categories
  1. Creational Design Pattern
  2. Structural Design Pattern
  3. Behavioral Design Pattern.
     Creational Design Pattern: The object generation mechanism is addressed by
     the JavaScript Creational Design Pattern. They aim to make items that are
     appropriate for a certain scenario.
     Structural Design Pattern: The JavaScript Structural Design Pattern explains
     how the classes and objects we've generated so far can be combined to
     construct bigger frameworks. This pattern makes it easier to create
     relationships between items by defining a straightforward way to do so.
     Behavioral Design Pattern: This design pattern highlights typical patterns of
     communication between objects in JavaScript. As a result, the communication
     may be carried out with greater freedom.
47. Is JavaScript a pass-by-reference or pass-by-value
    language?
The variable's data is always a reference for objects, hence it's always pass by value.
As a result, if you supply an object and alter its members inside the method, the
changes continue outside of it. It appears to be pass by reference in this case.
However, if you modify the values of the object variable, the change will not last,
demonstrating that it is indeed passed by value.
Page 60                                                           © Copyright by Interviewbit
                                                               JavaScript Interview Questions
48. Difference between Async/Await and Generators usage to
    achieve the same functionality.
     Generator functions are run by their generator yield by yield which means one
     output at a time, whereas Async-await functions are executed sequentially one
     a er another.
     Async/await provides a certain use case for Generators easier to execute.
     The output result of the Generator function is always value: X, done: Boolean,
     but the return value of the Async function is always an assurance or throws an
     error.
49. What are the primitive data types in JavaScript?
A primitive is a data type that isn't composed of other data types. It's only capable of
displaying one value at a time. By definition, every primitive is a built-in data type
(the compiler must be knowledgeable of them) nevertheless, not all built-in datasets
are primitives. In JavaScript, there are 5 different forms of basic data. The following
values are available:
  1. Boolean
  2. Undefined
  3. Null
  4. Number
  5. String
50. What is the role of deferred scripts in JavaScript?
The processing of HTML code while the page loads are disabled by nature till the
script hasn't halted. Your page will be affected if your network is a bit slow, or if the
script is very he y. When you use Deferred, the script waits for the HTML parser to
finish before executing it. This reduces the time it takes for web pages to load,
allowing them to appear more quickly.
51. What has to be done in order to put Lexical Scoping into
    practice?
Page 61                                                            © Copyright by Interviewbit
                                                            JavaScript Interview Questions
To support lexical scoping, a JavaScript function object's internal state must include
not just the function's code but also a reference to the current scope chain.
52. What is the purpose of the following JavaScript code?
  var scope = "global scope";
  function check()
  {
      var scope = "local scope";
      function f()
      {
           return scope;
      }
      return f;
  }
Every executing function, code block, and script as a whole in JavaScript has a
related object known as the Lexical Environment. The preceding code line returns
the value in scope.
JavaScript Coding Interview Questions
53. Guess the outputs of the following codes:
Page 62                                                         © Copyright by Interviewbit
                                                              JavaScript Interview Questions
  // Code 1:
  function func1(){
    setTimeout(()=>{
      console.log(x);
      console.log(y);
    },3000);
    var x = 2;
    let y = 12;
  }
  func1();
  // Code 2:
  function func2(){
    for(var i = 0; i < 3; i++){
      setTimeout(()=> console.log(i),2000);
  }
  }
  func2();
  // Code 3:
  (function(){
    setTimeout(()=> console.log(1),2000);
    console.log(2);
    setTimeout(()=> console.log(3),0);
    console.log(4);
  })();
Answers:
     Code 1 - Outputs 2 and 12. Since, even though let variables are not hoisted, due
     to the async nature of javascript, the complete function code runs before the
     setTimeout function. Therefore, it has access to both x and y.
     Code 2 - Outputs 3, three times since variable declared with var keyword does
     not have block scope. Also, inside the for loop, the variable i is incremented first
     and then checked.
     Code 3 - Output in the following order:
Page 63                                                           © Copyright by Interviewbit
                                                          JavaScript Interview Questions
  2
  4
  3
  1 // After two seconds
Even though the second timeout function has a waiting time of zero seconds, the
javascript engine always evaluates the setTimeout function using the Web API, and
therefore, the complete function executes before the setTimeout function can
execute.
54. Guess the outputs of the following code:
  // Code 1:
  let x= {}, y = {name:"Ronny"},z = {name:"John"};
  x[y] = {name:"Vivek"};
  x[z] = {name:"Akki"};
  console.log(x[y]);
  // Code 2:
  function runFunc(){
    console.log("1" + 1);
    console.log("A" - 1);
    console.log(2 + "-2" + "2");
    console.log("Hello" - "World" + 78);
    console.log("Hello"+ "78");
  }
  runFunc();
  // Code 3:
  let a = 0;
  let b = false;
  console.log((a == b));
  console.log((a === b));
Page 64                                                       © Copyright by Interviewbit
                                                               JavaScript Interview Questions
Answers:
Code 1 - Output will be {name: “Akki”}.
Adding objects as properties of another object should be done carefully.
Writing x[y] = {name:”Vivek”} , is same as writing x[‘object Object’] =
{name:”Vivek”} ,
While setting a property of an object, javascript coerces the parameter into a
string.
Therefore, since y is an object, it will be converted to ‘object Object’.
Both x[y] and x[z] are referencing the same property.
Code 2 - Outputs in the following order:
  11
  Nan
  2-22
  NaN
  Hello78
Code 3 - Output in the following order due to equality coercion:
  true
  false
55. Guess the output of the following code:
Page 65                                                            © Copyright by Interviewbit
                                                                JavaScript Interview Questions
  var x = 23;
  (function(){
    var x = 43;
    (function random(){
      x++;
      console.log(x);
      var x = 21;
    })();
  })();
Answer:
Output is NaN.
random() function has functional scope since x is declared and hoisted in the
functional scope.
Rewriting the random function will give a better idea about the output:
  function random(){
    var x; // x is hoisted
    x++; // x is not a number since it is not initialized yet
    console.log(x); // Outputs NaN
    x = 21; // Initialization of x
  }
56. Guess the outputs of the following code:
Page 66                                                             © Copyright by Interviewbit
                                          JavaScript Interview Questions
  // Code 1
    let hero = {
      powerLevel: 99,
      getPower(){
        return this.powerLevel;
      }
    }
    let getPower = hero.getPower;
    let hero2 = {powerLevel:42};
    console.log(getPower());
    console.log(getPower.apply(hero2));
    // Code 2
    const a = function(){
      console.log(this);
        const b = {
          func1: function(){
            console.log(this);
          }
        }
        const c = {
          func2: ()=>{
            console.log(this);
          }
        }
        b.func1();
        c.func2();
    }
    a();
    // Code 3
    const b = {
      name:"Vivek",
      f: function(){
        var self = this;
        console.log(this.name);
        (function(){
          console.log(this.name);
          console.log(self.name);
        })();
      }
    }
    b.f();
Page 67                                       © Copyright by Interviewbit
                                                             JavaScript Interview Questions
Answers:
Code 1 - Output in the following order:
  undefined
  42
Reason - The first output is undefined since when the function is invoked, it is
invoked referencing the global object:
  window.getPower() = getPower();
Code 2 - Outputs in the following order:
  global/window object
  object "b"
  global/window object
Since we are using the arrow function inside func2, this keyword refers to the global
object.
Code 3 - Outputs in the following order:
  "Vivek"
  undefined
  "Vivek"
Only in the IIFE inside the function f, this keyword refers to the global/window
object.
57. Guess the outputs of the following code:
Page 68                                                          © Copyright by Interviewbit
                                                             JavaScript Interview Questions
**Note - Code 2 and Code 3 require you to modify the code, instead of guessing
the output.
  // Code 1
  (function(a){
    return (function(){
      console.log(a);
      a = 23;
    })()
  })(45);
  // Code 2
  // Each time bigFunc is called, an array of size 700 is being created,
  // Modify the code so that we don't create the same array again and again
  function bigFunc(element){
    let newArray = new Array(700).fill('♥');
    return newArray[element];
  }
  console.log(bigFunc(599)); // Array is created
  console.log(bigFunc(670)); // Array is created again
  // Code 3
  // The following code outputs 2 and 2 after waiting for one second
  // Modify the code to output 0 and 1 after one second.
  function randomFunc(){
    for(var i = 0; i < 2; i++){
      setTimeout(()=> console.log(i),1000);
    }
  }
  randomFunc();
Page 69                                                          © Copyright by Interviewbit
                                                              JavaScript Interview Questions
Answers -
Code 1 - Outputs 45.
Even though a is defined in the outer function, due to closure the inner functions
have access to it.
Code 2 - This code can be modified by using closures,
  function bigFunc(){
    let newArray = new Array(700).fill('♥');
    return (element) => newArray[element];
  }
  let getElement = bigFunc(); // Array is created only once
  getElement(599);
  getElement(670);
Code 3 - Can be modified in two ways:
Using let keyword:
  function randomFunc(){
    for(let i = 0; i < 2; i++){
      setTimeout(()=> console.log(i),1000);
    }
  }
  randomFunc();
Using closure:
  function randomFunc(){
    for(var i = 0; i < 2; i++){
    (function(i){
        setTimeout(()=>console.log(i),1000);
      })(i);
    }
  }
  randomFunc();
Page 70                                                           © Copyright by Interviewbit
                                                                 JavaScript Interview Questions
58. Write a function that performs binary search on a sorted
    array.
  function binarySearch(arr,value,startPos,endPos){
    if(startPos > endPos) return -1;
      let middleIndex = Math.floor(startPos+endPos)/2;
      if(arr[middleIndex] === value) return middleIndex;
      elsif(arr[middleIndex > value]){
        return binarySearch(arr,value,startPos,middleIndex-1);
      }
      else{
        return binarySearch(arr,value,middleIndex+1,endPos);
      }
  }
59. Implement a function that returns an updated array with r
    right rotations on an array of integers a .
Example:
Given the following array: [2,3,4,5,7]
Perform 3 right rotations:
First rotation : [7,2,3,4,5] , Second rotation : [5,7,2,3,4] and, Third rotation: [4,5,7,2,3]
return [4,5,7,2,3]
Answer:
  function rotateRight(arr,rotations){
    if(rotations == 0) return arr;
    for(let i = 0; i < rotations;i++){
      let element = arr.pop();
      arr.unshift(element);
    }
    return arr;
  }
  rotateRight([2, 3, 4, 5, 7], 3); // Return [4,5,7,2,3]
  rotateRight([44, 1, 22, 111], 5); // Returns [111,44,1,22]
60. Write the code for dynamically inserting new components.
Page 71                                                              © Copyright by Interviewbit
                                                                JavaScript Interview Questions
  <html>
  <head>
  <title>inserting new components dynamically</title>
  <script type="text/javascript">
      function addNode () { var newP = document. createElement("p");
      var textNode = document.createTextNode(" This is other node");
      newP.appendChild(textNode); document.getElementById("parent1").appendChild(newP); }
  </script>
  </head>
  <body> <p id="parent1">firstP<p> </body>
  </html>
61. Write the code given If two strings are anagrams of one
    another, then return true.
  var firstWord = "Deepak";
  var secondWord = "Aman";
  isAnagram(wordOne, wordTwo); // true
  function isAnagram(one, two) {
    //Change both words to lowercase for case insensitivity..
    var a = one.toLowerCase();
    var b = two.toLowerCase();
      // Sort the strings, then combine the array to a string. Examine the outcomes.
      a = a.split("").sort().join("");
      b = b.split("").sort().join("");
      return a === b;
  }
62. Write the code to find the vowels
Page 72                                                             © Copyright by Interviewbit
                                                                JavaScript Interview Questions
  const findVowels = str => {
    let count = 0
    const vowels = ['a', 'e', 'i', 'o', 'u']
    for(let char of str.toLowerCase()) {
      if(vowels.includes(char)) {
        count++
      }
    }
    return count
  }
63. In JavaScript, how do you turn an Object into an Array []?
  let obj = { id: "1", name: "user22", age: "26", work: "programmer" };
  //Method 1: Convert the keys to Array using - Object.keys()
  console.log(Object.keys(obj));
  // ["id", "name", "age", "work"]
  // Method 2 Converts the Values to Array using - Object.values()
  console.log(Object.values(obj));
  // ["1", "user22r", "26", "programmer"]
  // Method 3 Converts both keys and values using - Object.entries()
  console.log(Object.entries(obj));
  //[["id", "1"],["name", "user22"],["age", "26"],["work", “programmer"]]
64. What is the output of the following code?
  const b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  for (let i = 0; i < 10; i++) {
    setTimeout(() => console.log(b[i]), 1000);
  }
  for (var i = 0; i < 10; i++) {
    setTimeout(() => console.log(b[i]), 1000);
  }
Ans.
Page 73                                                             © Copyright by Interviewbit
                                                             JavaScript Interview Questions
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  undefined
  undefined
  undefined
  undefined
  undefined
  undefined
  undefined
  undefined
  undefined
  undefined
Conclusion
It is preferable to keep the JavaScript, CSS, and HTML in distinct Separate 'javascript'
files. Dividing the code and HTML sections will make them easier to understand and
deal with. This strategy is also simpler for several programmers to use at the same
time. JavaScript code is simple to update. Numerous pages can utilize the same
group of JavaScript Codes. If we utilize External JavaScript scripts and need to alter
the code, we must do it just once. So that we may utilize a number and maintain it
much more easily. Remember that professional experience and expertise are only
one aspect of recruitment. Previous experience and personal skills are both vital in
landing (or finding the ideal applicant for the job.
Remember that many JavaScript structured interviews are free and have no one
proper answer. Interviewers would like to know why you answered the way you did,
not if you remembered the answer. Explain your answer process and be prepared to
address it.
Page 74                                                          © Copyright by Interviewbit
                                                         JavaScript Interview Questions
Recommended Resources
     https://www.interviewbit.com/javascript-cheat-sheet/
     https://www.interviewbit.com/online-javascript-compiler/
     https://www.interviewbit.com/blog/javascript-features/
     https://www.interviewbit.com/javascript-mcq/
     https://www.interviewbit.com/blog/javascript-projects/
     https://www.interviewbit.com/blog/javascript-ide/
     https://www.interviewbit.com/es6-interview-questions/
     https://www.interviewbit.com/blog/best-javascript-books/
     https://www.interviewbit.com/node-js-interview-questions/
Interview Guides
     https://www.interviewbit.com/technical-interview-questions/
     https://www.interviewbit.com/coding-interview-questions/
     https://www.interviewbit.com/mock-interview/
     https://www.interviewbit.com/blog/
Page 75                                                      © Copyright by Interviewbit
Links to More Interview
Questions
 C Interview Questions         Php Interview Questions       C Sharp Interview Questions
 Web Api Interview             Hibernate Interview           Node Js Interview Questions
 Questions                     Questions
 Cpp Interview Questions       Oops Interview Questions      Devops Interview Questions
 Machine Learning Interview    Docker Interview Questions    Mysql Interview Questions
 Questions
 Css Interview Questions       Laravel Interview Questions   Asp Net Interview Questions
 Django Interview Questions    Dot Net Interview Questions   Kubernetes Interview
                                                             Questions
 Operating System Interview    React Native Interview        Aws Interview Questions
 Questions                     Questions
 Git Interview Questions       Java 8 Interview Questions    Mongodb Interview
                                                             Questions
 Dbms Interview Questions      Spring Boot Interview         Power Bi Interview Questions
                               Questions
 Pl Sql Interview Questions    Tableau Interview             Linux Interview Questions
                               Questions
 Ansible Interview Questions   Java Interview Questions      Jenkins Interview Questions
Page 76                                                            © Copyright by Interviewbit
OOPs Interview Questions
To view the live version of the
page, click here.
© Copyright by Interviewbit
If you want a more personalized rundown of Object Oriented
Programming, you might find our upcoming live masterclass on the
topic, hosted by one of our top instructors, beneficial. The session is
free, so don't hesitate to sign up if you're interested!
                       “As a regular attendee of the Masterclass, I feel the
                       most valuable part about Scaler Academy's
  Shubh                Masterclasses is the unparalleled content quality that
                       they deliver. A 3 hour Masterclass is very helpful and
 Agrawal               good enough for the teaching part and doubt clearing
                       sessions. I use the study material they provide before
  B.Tech, IIIT,
                       each Masterclass. In these times when nothing is for
  Bhagalpur
                       free, these classes are a life-savior!”
“The session was so well structured and simplified. 3
engaging hours of learning, interesting polls and lots
of doubt resolution! The best part was, he saw curious
                                                             Abhinav
learners and extended the session for another hour for       Koppula
people who wished to stay. Recommend it to all
beginners out there who are clueless about starting           Developer,
HLD themselves! This is a must!!”                             Mckinsey
    If interested, don't hesitate to
                                               REGISTER NOW
    attend this FREE session.
Contents
Basic OOPs Interview Questions
1. What is meant by the term OOPs?
2. What is the need for OOPs?
3. What are some major Object Oriented Programming languages?
4. What are some other programming paradigms other than OOPs?
5. What is meant by Structured Programming?
6. What are the main features of OOPs?
7. What are some advantages of using OOPs?
8. Why is OOPs so popular?
Advanced OOPs Interview Questions
9. What is a class?
10. What is an object?
11. What is encapsulation?
12. What is Polymorphism?
13. What is Compile time Polymorphism and how is it different from Runtime
    Polymorphism?
14. How does C++ support Polymorphism?
15. What is meant by Inheritance?
16. What is Abstraction?
17. How much memory does a class occupy?
18. Is it always necessary to create objects from class?
Page 1                                                     © Copyright by Interviewbit
                                                                 OOPs Interview Questions
Advanced OOPs Interview Questions                                        (.....Continued)
19. What is a constructor?
20. What are the various types of constructors in C++?
21. What is a copy constructor?
22. What is a destructor?
23. Are class and structure the same? If not, what's the difference between a class
    and a structure?
24. Explain Inheritance with an example?
25. Are there any limitations of Inheritance?
26. What are the various types of inheritance?
27. What is a subclass?
28. Define a superclass?
29. What is an interface?
30. What is meant by static polymorphism?
31. What is meant by dynamic polymorphism?
32. What is the difference between overloading and overriding?
33. How is data abstraction accomplished?
34. What is an abstract class?
35. How is an abstract class different from an interface?
36. What are access specifiers and what is their significance?
37. What is an exception?
38. What is meant by exception handling?
Page 2                                                           © Copyright by Interviewbit
                                                           OOPs Interview Questions
Advanced OOPs Interview Questions                                  (.....Continued)
39. What is meant by Garbage Collection in OOPs world?
40. Can we run a Java application without implementing the OOPs concept?
OOPs Coding Problems
41. What is the output of the below code?
42. What will be the output of the below code?
43. Predict the output?
44. What will be the output in below code?
45. Predict the output?
46. What is the output of the below program?
Page 3                                                     © Copyright by Interviewbit
Let's get Started
OOPs, or Object-Oriented Programming is a programming model or paradigm which
revolves around the concept of “OBJECTS”. Objects can be considered as real-world
instances of entities like class, that contain some characteristics and behaviors
specified in the class template.
In simple language, a class can be considered as the blueprint or template, based on
which objects can be created. So the Objects are considered the instance of a class,
and are therefore sometimes called “instances”. The term “characteristics” refers to
the “what” about the Object, and the term “behavior” refers to the “how” about the
Object.
For example, if we consider a car, then based on the OOPs model:
     Class = A specific car model, such as Audi A4, BMW I8, Maruti Suzuki Vitara
     Brezza, etc.
     Object = A specific car of any model, like the car you own
     Characteristics = What is the color of your car? What is the Chassis number of
     your car? etc
     Behavior = How to start the car? How to change the gear of the car? etc.
Characteristics are also known as data, attributes, or properties, and Behaviours are
also known as the functions, procedures or methods, in the programming language.
The concept of “objects” allows the OOPs model to easily access, use and modify the
instance data and methods, interact with other objects, and define methods in
runtime (during the execution of the program). This gives the OOPs model
significance and makes it diverse in its implementation.
In fact, the OOPs model is so popular, that many of the most widely used
programming languages support and use this Object Oriented Programming or OOPs
model, such as Java, C++, Python, C#, etc.
Page 4                                                          © Copyright by Interviewbit
                                                                  OOPs Interview Questions
         OOPs Interview Questions Solved Step by Step | Coding Inte…
                                                               Inte…
Basic OOPs Interview Questions
1. What is meant by the term OOPs?
OOPs refers to Object-Oriented Programming. It is the programming paradigm that is
defined using objects. Objects can be considered as real-world instances of entities
like class, that have some characteristics and behaviors.
2. What is the need for OOPs?
There are many reasons why OOPs is mostly preferred, but the most important
among them are:
     OOPs helps users to understand the so ware easily, although they don’t know
     the actual implementation.
     With OOPs, the readability, understandability, and maintainability of the code
     increase multifold.
     Even very big so ware can be easily written and managed easily using OOPs.
3. What are some major Object Oriented Programming
   languages?
Page 5                                                           © Copyright by Interviewbit
                                                             OOPs Interview Questions
The programming languages that use and follow the Object-Oriented Programming
paradigm or OOPs, are known as Object-Oriented Programming languages. Some of
the major Object-Oriented Programming languages include:
     Java
     C++
     Javascript
     Python
     PHP
And many more.
4. What are some other programming paradigms other than
   OOPs?
Programming paradigms refers to the method of classification of programming
languages based on their features. There are mainly two types of Programming
Paradigms:
     Imperative Programming Paradigm
     Declarative Programming Paradigm
Page 6                                                      © Copyright by Interviewbit
                                                               OOPs Interview Questions
Now, these paradigms can be further classified based:
1. Imperative Programming Paradigm: Imperative programming focuses on HOW
to execute program logic and defines control flow as statements that change a
program state. This can be further classified as:
a) Procedural Programming Paradigm: Procedural programming specifies the steps a
program must take to reach the desired state, usually read in order from top to
bottom.
b) Object-Oriented Programming or OOP: Object-oriented programming (OOP)
organizes programs as objects, that contain some data and have some behavior.
c) Parallel Programming: Parallel programming paradigm breaks a task into subtasks
and focuses on executing them simultaneously at the same time.
2. Declarative Programming Paradigm: Declarative programming focuses on WHAT
to execute and defines program logic, but not a detailed control flow. Declarative
paradigm can be further classified into:
a) Logical Programming Paradigm: Logical programming paradigm is based on
formal logic, which refers to a set of sentences expressing facts and rules about how
to solve a problem
b) Functional Programming Paradigm: Functional programming is a programming
paradigm where programs are constructed by applying and composing functions.
c) Database Programming Paradigm: Database programming model is used to
manage data and information structured as fields, records, and files.
Page 7                                                         © Copyright by Interviewbit
                                                                  OOPs Interview Questions
5. What is meant by Structured Programming?
Structured Programming refers to the method of programming which consists of a
completely structured control flow. Here structure refers to a block, which contains a
set of rules, and has a definitive control flow, such as (if/then/else), (while and for),
block structures, and subroutines.
Nearly all programming paradigms include Structured programming, including the
OOPs model.
6. What are the main features of OOPs?
OOPs or Object Oriented Programming mainly comprises of the below four features,
and make sure you don't miss any of these:
     Inheritance
     Encapsulation
     Polymorphism
     Data Abstraction
Page 8                                                            © Copyright by Interviewbit
                                                                OOPs Interview Questions
7. What are some advantages of using OOPs?
     OOPs is very helpful in solving very complex level of problems.
     Highly complex programs can be created, handled, and maintained easily using
     object-oriented programming.
     OOPs, promote code reuse, thereby reducing redundancy.
     OOPs also helps to hide the unnecessary details with the help of Data
     Abstraction.
     OOPs, are based on a bottom-up approach, unlike the Structural programming
     paradigm, which uses a top-down approach.
     Polymorphism offers a lot of flexibility in OOPs.
8. Why is OOPs so popular?
OOPs programming paradigm is considered as a better style of programming. Not
only it helps in writing a complex piece of code easily, but it also allows users to
handle and maintain them easily as well. Not only that, the main pillar of OOPs - Data
Abstraction, Encapsulation, Inheritance, and Polymorphism, makes it easy for
programmers to solve complex scenarios. As a result of these, OOPs is so popular.
Advanced OOPs Interview Questions
Page 9                                                          © Copyright by Interviewbit
                                                                   OOPs Interview Questions
9. What is a class?
A class can be understood as a template or a blueprint, which contains some values,
known as member data or member, and some set of rules, known as behaviors or
functions. So when an object is created, it automatically takes the data and functions
that are defined in the class.
Therefore the class is basically a template or blueprint for objects. Also one can
create as many objects as they want based on a class.
For example, first, a car’s template is created. Then multiple units of car are created
based on that template.
10. What is an object?
An object refers to the instance of the class, which contains the instance of the
members and behaviors defined in the class template. In the real world, an object is
an actual entity to which a user interacts, whereas class is just the blueprint for that
object. So the objects consume space and have some characteristic behavior.
For example, a specific car.
11. What is encapsulation?
Page 10                                                           © Copyright by Interviewbit
                                                                OOPs Interview Questions
One can visualize Encapsulation as the method of putting everything that is required
to do the job, inside a capsule and presenting that capsule to the user. What it means
is that by Encapsulation, all the necessary data and methods are bind together and
all the unnecessary details are hidden to the normal user. So Encapsulation is the
process of binding data members and methods of a program together to do a specific
job, without revealing unnecessary details.
Encapsulation can also be defined in two different ways:
1) Data hiding: Encapsulation is the process of hiding unwanted information, such as
restricting access to any member of an object.
2) Data binding: Encapsulation is the process of binding the data members and the
methods together as a whole, as a class.
12. What is Polymorphism?
Polymorphism is composed of two words - “poly” which means “many”, and “morph”
which means “shapes”. Therefore Polymorphism refers to something that has many
shapes.
Page 11                                                        © Copyright by Interviewbit
                                                               OOPs Interview Questions
In OOPs, Polymorphism refers to the process by which some code, data, method, or
object behaves differently under different circumstances or contexts. Compile-time
polymorphism and Run time polymorphism are the two types of polymorphisms in
OOPs languages.
13. What is Compile time Polymorphism and how is it different
    from Runtime Polymorphism?
Compile Time Polymorphism: Compile time polymorphism, also known as Static
Polymorphism, refers to the type of Polymorphism that happens at compile time.
What it means is that the compiler decides what shape or value has to be taken by
the entity in the picture.
Example:
Page 12                                                       © Copyright by Interviewbit
                                                                  OOPs Interview Questions
  // In this program, we will see how multiple functions are created with the same name,
  // but the compiler decides which function to call easily at the compile time itself.
  class CompileTimePolymorphism{
     // 1st method with name add
     public int add(int x, int y){
     return x+y;
     }
     // 2nd method with name add
     public int add(int x, int y, int z){
     return x+y+z;
     }
     // 3rd method with name add
     public int add(double x, int y){
     return (int)x+y;
     }
     // 4th method with name add
     public int add(int x, double y){
     return x+(int)y;
     }
  }
  class Test{
     public static void main(String[] args){
     CompileTimePolymorphism demo=new CompileTimePolymorphism();
     // In the below statement, the Compiler looks at the argument types and decides to c
     System.out.println(demo.add(2,3));
     // Similarly, in the below statement, the compiler calls method 2
     System.out.println(demo.add(2,3,4));
     // Similarly, in the below statement, the compiler calls method 4
     System.out.println(demo.add(2,3.4));
     // Similarly, in the below statement, the compiler calls method 3
     System.out.println(demo.add(2.5,3));
     }
  }
Page 13                                                          © Copyright by Interviewbit
                                                                  OOPs Interview Questions
In the above example, there are four versions of add methods. The first method takes
two parameters while the second one takes three. For the third and fourth methods,
there is a change of order of parameters. The compiler looks at the method signature
and decides which method to invoke for a particular method call at compile time.
Runtime Polymorphism: Runtime polymorphism, also known as Dynamic
Polymorphism, refers to the type of Polymorphism that happens at the run time.
What it means is it can't be decided by the compiler. Therefore what shape or value
has to be taken depends upon the execution. Hence the name Runtime
Polymorphism.
Example:
  class AnyVehicle{
     public void move(){
     System.out.println(“Any vehicle should move!!”);
     }
  }
  class Bike extends AnyVehicle{
     public void move(){
     System.out.println(“Bike can move too!!”);
     }
  }
  class Test{
     public static void main(String[] args){
     AnyVehicle vehicle = new Bike();
     // In the above statement, as you can see, the object vehicle is of type AnyVehicle
     // But the output of the below statement will be “Bike can move too!!”,
     // because the actual implementation of object ‘vehicle’ is decided during runtime v
     vehicle = new AnyVehicle();
     // Now, the output of the below statement will be “Any vehicle should move!!”,
     vehicle.move();
     }
  }
As the method to call is determined at runtime, as shown in the above code, this is
called runtime polymorphism.
14. How does C++ support Polymorphism?
C++ is an Object-oriented programming language and it supports Polymorphism as
well:
Page 14                                                          © Copyright by Interviewbit
                                                                  OOPs Interview Questions
     Compile Time Polymorphism: C++ supports compile-time polymorphism with
     the help of features like templates, function overloading, and default
     arguments.
     Runtime Polymorphism: C++ supports Runtime polymorphism with the help of
     features like virtual functions. Virtual functions take the shape of the functions
     based on the type of object in reference and are resolved at runtime.
15. What is meant by Inheritance?
The term “inheritance” means “receiving some quality or behavior from a parent to
an offspring.” In object-oriented programming, inheritance is the mechanism by
which an object or class (referred to as a child) is created using the definition of
another object or class (referred to as a parent). Inheritance not only helps to keep
the implementation simpler but also helps to facilitate code reuse.
16. What is Abstraction?
If you are a user, and you have a problem statement, you don't want to know how the
components of the so ware work, or how it's made. You only want to know how the
so ware solves your problem. Abstraction is the method of hiding unnecessary
details from the necessary ones. It is one of the main features of OOPs.
For example, consider a car. You only need to know how to run a car, and not how the
wires are connected inside it. This is obtained using Abstraction.
17. How much memory does a class occupy?
Classes do not consume any memory. They are just a blueprint based on which
objects are created. Now when objects are created, they actually initialize the class
members and methods and therefore consume memory.
18. Is it always necessary to create objects from class?
No. An object is necessary to be created if the base class has non-static methods. But
if the class has static methods, then objects don’t need to be created. You can call the
class method directly in this case, using the class name.
19. What is a constructor?
Page 15                                                           © Copyright by Interviewbit
                                                               OOPs Interview Questions
Constructors are special methods whose name is the same as the class name. The
constructors serve the special purpose of initializing the objects.
For example, suppose there is a class with the name “MyClass”, then when you
instantiate this class, you pass the syntax:
  MyClass myClassObject = new MyClass();
Now here, the method called a er “new” keyword - MyClass(), is the constructor of
this class. This will help to instantiate the member data and methods and assign
them to the object myClassObject.
20. What are the various types of constructors in C++?
The most common classification of constructors includes:
Default constructor: The default constructor is the constructor which doesn’t take
any argument. It has no parameters.
Page 16                                                        © Copyright by Interviewbit
                                                                OOPs Interview Questions
  class ABC
  {
     int x;
      ABC()
      {
          x = 0;
      }
  }
Parameterized constructor: The constructors that take some arguments are known
as parameterized constructors.
   class ABC
  {
     int x;
      ABC(int y)
      {
          x = y;
      }
  }
Copy constructor: A copy constructor is a member function that initializes an object
using another object of the same class.
  class ABC
  {
     int x;
      ABC(int   y)
      {
          x =   y;
      }
      // Copy   constructor
      ABC(ABC   abc)
      {
          x =   abc.x;
      }
  }
21. What is a copy constructor?
Page 17                                                        © Copyright by Interviewbit
                                                                  OOPs Interview Questions
Copy Constructor is a type of constructor, whose purpose is to copy an object to
another. What it means is that a copy constructor will clone an object and its values,
into another object, is provided that both the objects are of the same class.
22. What is a destructor?
Contrary to constructors, which initialize objects and specify space for them,
Destructors are also special methods. But destructors free up the resources and
memory occupied by an object. Destructors are automatically called when an object
is being destroyed.
23. Are class and structure the same? If not, what's the
    difference between a class and a structure?
No, class and structure are not the same. Though they appear to be similar, they have
differences that make them apart. For example, the structure is saved in the stack
memory, whereas the class is saved in the heap memory. Also, Data Abstraction
cannot be achieved with the help of structure, but with class, Abstraction is majorly
used.
24. Explain Inheritance with an example?
Inheritance is one of the major features of object-oriented programming, by which an
entity inherits some characteristics and behaviors of some other entity and makes
them their own. Inheritance helps to improve and facilitate code reuse.
Let me explain to you with a common example. Let's take three different vehicles - a
car, truck, or bus. These three are entirely different from one another with their own
specific characteristics and behavior. But. in all three, you will find some common
elements, like steering wheel, accelerator, clutch, brakes, etc. Though these
elements are used in different vehicles, still they have their own features which are
common among all vehicles. This is achieved with inheritance. The car, the truck, and
the bus have all inherited the features like steering wheel, accelerator, clutch, brakes,
etc, and used them as their own. Due to this, they did not have to create these
components from scratch, thereby facilitating code reuse.
Page 18                                                           © Copyright by Interviewbit
                                                                   OOPs Interview Questions
25. Are there any limitations of Inheritance?
Yes, with more powers comes more complications. Inheritance is a very powerful
feature in OOPs, but it has some limitations too. Inheritance needs more time to
process, as it needs to navigate through multiple classes for its implementation. Also,
the classes involved in Inheritance - the base class and the child class, are very tightly
coupled together. So if one needs to make some changes, they might need to do
nested changes in both classes. Inheritance might be complex for implementation, as
well. So if not correctly implemented, this might lead to unexpected errors or
incorrect outputs.
26. What are the various types of inheritance?
The various types of inheritance include:
     Single inheritance
     Multiple inheritances
     Multi-level inheritance
     Hierarchical inheritance
     Hybrid inheritance
Page 19                                                           © Copyright by Interviewbit
                                                                  OOPs Interview Questions
27. What is a subclass?
The subclass is a part of Inheritance. The subclass is an entity, which inherits from
another class. It is also known as the child class.
28. Define a superclass?
Superclass is also a part of Inheritance. The superclass is an entity, which allows
subclasses or child classes to inherit from itself.
Page 20                                                           © Copyright by Interviewbit
                                                                 OOPs Interview Questions
29. What is an interface?
An interface refers to a special type of class, which contains methods, but not their
definition. Only the declaration of methods is allowed inside an interface. To use an
interface, you cannot create objects. Instead, you need to implement that interface
and define the methods for their implementation.
30. What is meant by static polymorphism?
Static Polymorphism is commonly known as the Compile time polymorphism. Static
polymorphism is the feature by which an object is linked with the respective function
or operator based on the values during the compile time. Static or Compile time
Polymorphism can be achieved through Method overloading or operator
overloading.
31. What is meant by dynamic polymorphism?
Dynamic Polymorphism or Runtime polymorphism refers to the type of
Polymorphism in OOPs, by which the actual implementation of the function is
decided during the runtime or execution. The dynamic or runtime polymorphism can
be achieved with the help of method overriding.
32. What is the difference between overloading and overriding?
Page 21                                                         © Copyright by Interviewbit
                                                                 OOPs Interview Questions
Overloading is a compile-time polymorphism feature in which an entity has multiple
implementations with the same name. For example, Method overloading and
Operator overloading.
Whereas Overriding is a runtime polymorphism feature in which an entity has the
same name, but its implementation changes during execution. For example, Method
overriding.
Image
33. How is data abstraction accomplished?
Data abstraction is accomplished with the help of abstract methods or abstract
classes.
34. What is an abstract class?
An abstract class is a special class containing abstract methods. The significance of
abstract class is that the abstract methods inside it are not implemented and only
declared. So as a result, when a subclass inherits the abstract class and needs to use
its abstract methods, they need to define and implement them.
35. How is an abstract class different from an interface?
Interface and abstract class both are special types of classes that contain only the
methods declaration and not their implementation. But the interface is entirely
different from an abstract class. The main difference between the two is that, when
an interface is implemented, the subclass must define all its methods and provide its
implementation. Whereas when an abstract class is inherited, the subclass does not
need to provide the definition of its abstract method, until and unless the subclass is
using it.
Also, an abstract class can contain abstract methods as well as non-abstract
methods.
36. What are access specifiers and what is their significance?
Page 22                                                          © Copyright by Interviewbit
                                                                  OOPs Interview Questions
Access specifiers, as the name suggests, are a special type of keywords, which are
used to control or specify the accessibility of entities like classes, methods, etc. Some
of the access specifiers or access modifiers include “private”, “public”, etc. These
access specifiers also play a very vital role in achieving Encapsulation - one of the
major features of OOPs.
37. What is an exception?
An exception can be considered as a special event, which is raised during the
execution of a program at runtime, that brings the execution to a halt. The reason for
the exception is mainly due to a position in the program, where the user wants to do
something for which the program is not specified, like undesirable input.
38. What is meant by exception handling?
No one wants its so ware to fail or crash. Exceptions are the major reason for
so ware failure. The exceptions can be handled in the program beforehand and
prevent the execution from stopping. This is known as exception handling.
So exception handling is the mechanism for identifying the undesirable states that
the program can reach and specifying the desirable outcomes of such states.
Try-catch is the most common method used for handling exceptions in the program.
39. What is meant by Garbage Collection in OOPs world?
Object-oriented programming revolves around entities like objects. Each object
consumes memory and there can be multiple objects of a class. So if these objects
and their memories are not handled properly, then it might lead to certain memory-
related errors and the system might fail.
Garbage collection refers to this mechanism of handling the memory in the program.
Through garbage collection, the unwanted memory is freed up by removing the
objects that are no longer needed.
40. Can we run a Java application without implementing the
    OOPs concept?
No. Java applications are based on Object-oriented programming models or OOPs
concept, and hence they cannot be implemented without it.
Page 23                                                           © Copyright by Interviewbit
                                                                OOPs Interview Questions
However, on the other hand, C++ can be implemented without OOPs, as it also
supports the C-like structural programming model.
OOPs Coding Problems
41. What is the output of the below code?
  #include<iostream>
  using namespace std;
  class BaseClass1 {
  public:
      BaseClass1()
      { cout << " BaseClass1 constructor called" << endl;   }
  };
  class BaseClass2 {
  public:
      BaseClass2()
      { cout << "BaseClass2 constructor called" << endl;    }
  };
  class DerivedClass: public BaseClass1, public BaseClass2 {
    public:
     DerivedClass()
      { cout << "DerivedClass constructor called" << endl; }
  };
  int main()
  {
    DerivedClass derived_class;
    return 0;
  }
Output:
  BaseClass1 constructor called
  BaseClass2 constructor called
  DerivedClass constructor called
Page 24                                                         © Copyright by Interviewbit
                                                                OOPs Interview Questions
Reason:
The above program demonstrates Multiple inheritances. So when the Derived class’s
constructor is called, it automatically calls the Base class's constructors from le to
right order of inheritance.
42. What will be the output of the below code?
  class Scaler
  {
     static int i;
      static
      {
          System.out.println(“a”);
          i = 100;
      }
  }
  public class StaticBlock
  {
     static
     {
         System.out.println(“b”);
     }
      public static void main(String[] args)
      {
          System.out.println(“c”);
          System.out.println(Scaler.i);
      }
  }
Output:
  b
  c
  a
  100
Page 25                                                         © Copyright by Interviewbit
                                                               OOPs Interview Questions
Reason:
Firstly the static block inside the main-method calling class will be implemented.
Hence ‘b’ will be printed first. Then the main method is called, and now the sequence
is kept as expected.
43. Predict the output?
  #include<iostream>
  using namespace std;
  class ClassA {
  public:
     ClassA(int ii = 0) : i(ii) {}
     void show() { cout << "i = " << i << endl;}
  private:
     int i;
  };
  class ClassB {
  public:
     ClassB(int xx) : x(xx) {}
     operator ClassA() const { return ClassA(x); }
  private:
     int x;
  };
  void g(ClassA a)
  { a.show(); }
  int main() {
   ClassB b(10);
   g(b);
   g(20);
   getchar();
   return 0;
  }
Output:
  i = 10
  i = 20
Page 26                                                        © Copyright by Interviewbit
                                                                OOPs Interview Questions
Reason:
ClassA contains a conversion constructor. Due to this, the objects of ClassA can have
integer values. So the statement g(20) works. Also, ClassB has a conversion operator
overloaded. So the statement g(b) also works.
44. What will be the output in below code?
  public class Demo{
     public static void main(String[] arr){
           System.out.println(“Main1”);
     }
     public static void main(String arr){
           System.out.println(“Main2”);
     }
  }
Output:
  Main1
Reason:
Here the main() method is overloaded. But JVM only understands the main method
which has a String[] argument in its definition. Hence Main1 is printed and the
overloaded main method is ignored.
45. Predict the output?
Page 27                                                         © Copyright by Interviewbit
                                                                  OOPs Interview Questions
  #include<iostream>
  using namespace std;
  class BaseClass{
     int arr[10];
  };
  class DerivedBaseClass1: public BaseClass { };
  class DerivedBaseClass2: public BaseClass { };
  class DerivedClass: public DerivedBaseClass1, public DerivedBaseClass2{};
  int main(void)
  {
   cout<<sizeof(DerivedClass);
   return 0;
  }
Output:
  If the size of the integer is 4 bytes, then the output will be 80.
Reason:
Since DerivedBaseClass1 and DerivedBaseClass1 both inherit from class BaseClass,
DerivedClass contains two copies of BaseClass. Hence it results in wastage of space
and a large size output. It can be reduced with the help of a virtual base class.
46. What is the output of the below program?
Page 28                                                          © Copyright by Interviewbit
                                                                 OOPs Interview Questions
  #include<iostream>
  using namespace std;
  class A {
  public:
    void print()
    { cout <<" Inside A::"; }
  };
  class B : public A {
  public:
    void print()
    { cout <<" Inside B"; }
  };
  class C: public B {
  };
  int main(void)
  {
   C c;
   c.print();
   return 0;
  }
Output:
  Inside B
Reason:
The above program implements a Multi-level hierarchy. So the program is linearly
searched up until a matching function is found. Here, it is present in both classes A
and B. So class B’s print() method is called.
Useful Resource
Features of OOPS
Page 29                                                          © Copyright by Interviewbit
If you want a more personalized rundown of Object Oriented
Programming, you might find our upcoming live masterclass on the
topic, hosted by one of our top instructors, beneficial. The session is
free, so don't hesitate to sign up if you're interested!
                       “As a regular attendee of the Masterclass, I feel the
                       most valuable part about Scaler Academy's
  Shubh                Masterclasses is the unparalleled content quality that
                       they deliver. A 3 hour Masterclass is very helpful and
 Agrawal               good enough for the teaching part and doubt clearing
                       sessions. I use the study material they provide before
  B.Tech, IIIT,
                       each Masterclass. In these times when nothing is for
  Bhagalpur
                       free, these classes are a life-savior!”
“The session was so well structured and simplified. 3
engaging hours of learning, interesting polls and lots
of doubt resolution! The best part was, he saw curious
                                                             Abhinav
learners and extended the session for another hour for       Koppula
people who wished to stay. Recommend it to all
beginners out there who are clueless about starting           Developer,
HLD themselves! This is a must!!”                             Mckinsey
    If interested, don't hesitate to
                                               REGISTER NOW
    attend this FREE session.
Links to More Interview
Questions
 C Interview Questions         Php Interview Questions       C Sharp Interview Questions
 Web Api Interview             Hibernate Interview           Node Js Interview Questions
 Questions                     Questions
 Cpp Interview Questions       Oops Interview Questions      Devops Interview Questions
 Machine Learning Interview    Docker Interview Questions    Mysql Interview Questions
 Questions
 Css Interview Questions       Laravel Interview Questions   Asp Net Interview Questions
 Django Interview Questions    Dot Net Interview Questions   Kubernetes Interview
                                                             Questions
 Operating System Interview    React Native Interview        Aws Interview Questions
 Questions                     Questions
 Git Interview Questions       Java 8 Interview Questions    Mongodb Interview
                                                             Questions
 Dbms Interview Questions      Spring Boot Interview         Power Bi Interview Questions
                               Questions
 Pl Sql Interview Questions    Tableau Interview             Linux Interview Questions
                               Questions
 Ansible Interview Questions   Java Interview Questions      Jenkins Interview Questions
Page 30                                                            © Copyright by Interviewbit
DBMS Interview Questions
To view the live version of the
page, click here.
© Copyright by Interviewbit
Contents
Basic DBMS Interview Questions
1. What is meant by DBMS and what is its utility? Explain RDBMS with examples.
2. What is meant by a database?
3. Mention the issues with traditional file-based systems that make DBMS a better
   choice?
4. Explain a few advantages of a DBMS.
5. Explain different languages present in DBMS.
6. What is meant by ACID properties in DBMS?
7. Are NULL values in a database the same as that of blank space or zero?
Intermediate DBMS Interview Questions
8. What is meant by Data Warehousing?
9. Explain different levels of data abstraction in a DBMS.
10. What is meant by an entity-relationship (E-R) model? Explain the terms Entity,
    Entity Type, and Entity Set in DBMS.
11. Explain different types of relationships amongst tables in a DBMS.
12. Explain the difference between intension and extension in a database.
13. Explain the difference between the DELETE and TRUNCATE command in a
    DBMS.
14. What is a lock. Explain the major difference between a shared lock and an
    exclusive lock during a transaction in a database.
15. What is meant by normalization and denormalization?
Advanced DBMS Interview Questions
16. Explain different types of Normalization forms in a DBMS.
17. Explain different types of keys in a database.
Page 1                                                         © Copyright by Interviewbit
                                                               DBMS Interview Questions
Advanced DBMS Interview Questions                                      (.....Continued)
18. Explain the difference between a 2-tier and 3-tier architecture in a DBMS.
Page 2                                                         © Copyright by Interviewbit
Let's get Started
To consolidate your knowledge and concepts in DBMS, here we've listed the most
commonly asked DBMS interview questions to help you ace your interview!
Basic DBMS Interview Questions
1. What is meant by DBMS and what is its utility? Explain RDBMS
   with examples.
As the name suggests DBMS or Database Management System is a set of applications
or programs that enable users to create and maintain a database. DBMS provides a
tool or an interface for performing various operations such as inserting, deleting,
updating, etc. into a database. It is so ware that enables the storage of data more
compactly and securely as compared to a file-based system. A DBMS system helps a
user to overcome problems like data inconsistency, data redundancy, etc. in a
database and makes it more convenient and organized to use it.
Examples of popular DBMS systems are file systems, XML, Windows Registry, etc.
Page 3                                                        © Copyright by Interviewbit
                                                                   DBMS Interview Questions
RDBMS stands for Relational Database Management System and was introduced in
the 1970s to access and store data more efficiently than DBMS. RDBMS stores data in
the form of tables as compared to DBMS which stores data as files. Storing data as
rows and columns makes it easier to locate specific values in the database and makes
it more efficient as compared to DBMS.
Examples of popular RDBMS systems are MySQL, Oracle DB, etc.
2. What is meant by a database?
A Database is an organized, consistent, and logical collection of data that can easily
be updated, accessed, and managed. Database mostly contains sets of tables or
objects (anything created using create command is a database object) which consist
of records and fields. A tuple or a row represents a single entry in a table. An attribute
or a column represents the basic units of data storage, which contain information
about a particular aspect of the table. DBMS extracts data from a database in the
form of queries given by the user.
3. Mention the issues with traditional file-based systems that
   make DBMS a better choice?
The absence of indexing in a traditional file-based system leaves us with the only
option of scanning the full page and hence making the access of content tedious and
super slow. The other issue is redundancy and inconsistency as files have many
duplicate and redundant data and changing one of them makes all of them
inconsistent. Accessing data is harder in traditional file-based systems because data
is unorganized in them.
Another issue is the lack of concurrency control, which leads to one operation locking
the entire page, as compared to DBMS where multiple operations can work on a
single file simultaneously.
Integrity check, data isolation, atomicity, security, etc. are some other issues with
traditional file-based systems for which DBMSs have provided some good solutions.
4. Explain a few advantages of a DBMS.
Following are the few advantages of using a DBMS.
Page 4                                                             © Copyright by Interviewbit
                                                                DBMS Interview Questions
     Data Sharing: Data from a single database can be simultaneously shared by
     multiple users. Such sharing also enables end-users to react to changes quickly
     in the database environment.
     Integrity constraints: The existence of such constraints allows storing of data in
     an organized and refined manner.
     Controlling redundancy in a database: Eliminates redundancy in a database by
     providing a mechanism that integrates all the data in a single database.
     Data Independence: This allows changing the data structure without altering
     the composition of any of the executing application programs.
     Provides backup and recovery facility: It can be configured to automatically
     create the backup of the data and restore the data in the database whenever
     required.
     Data Security: DBMS provides the necessary tools to make the storage and
     transfer of data more reliable and secure. Authentication (the process of giving
     restricted access to a user) and encryption (encrypting sensitive data such as
     OTP, credit card information, etc.) are some popular tools used to secure data in
     a DBMS.
5. Explain different languages present in DBMS.
Page 5                                                          © Copyright by Interviewbit
                                                                DBMS Interview Questions
Following are various languages present in DBMS:
     DDL(Data Definition Language): It contains commands which are required to
     define the database.
     E.g., CREATE, ALTER, DROP, TRUNCATE, RENAME, etc.
     DML(Data Manipulation Language): It contains commands which are required
     to manipulate the data present in the database.
     E.g., SELECT, UPDATE, INSERT, DELETE, etc.
     DCL(Data Control Language): It contains commands which are required to
     deal with the user permissions and controls of the database system.
     E.g., GRANT and REVOKE.
     TCL(Transaction Control Language): It contains commands which are required
     to deal with the transaction of the database.
     E.g., COMMIT, ROLLBACK, and SAVEPOINT.
6. What is meant by ACID properties in DBMS?
ACID stands for Atomicity, Consistency, Isolation, and Durability in a DBMS these are
those properties that ensure a safe and secure way of sharing data among multiple
users.
Page 6                                                          © Copyright by Interviewbit
                                                               DBMS Interview Questions
     Atomicity: This property reflects the concept of either executing the whole
     query or executing nothing at all, which implies that if an update occurs in a
     database then that update should either be reflected in the whole database or
     should not be reflected at all.
Page 7                                                         © Copyright by Interviewbit
                                                                DBMS Interview Questions
     Consistency: This property ensures that the data remains consistent before and
     a er a transaction in a database.
     Isolation: This property ensures that each transaction is occurring
     independently of the others. This implies that the state of an ongoing
     transaction doesn’t affect the state of another ongoing transaction.
Page 8                                                          © Copyright by Interviewbit
                                                                 DBMS Interview Questions
     Durability: This property ensures that the data is not lost in cases of a system
     failure or restart and is present in the same state as it was before the system
     failure or restart.
7. Are NULL values in a database the same as that of blank space
   or zero?
No, a NULL value is very different from that of zero and blank space as it represents a
value that is assigned, unknown, unavailable, or not applicable as compared to blank
space which represents a character and zero represents a number.
Example: NULL value in “number_of_courses” taken by a student represents that its
value is unknown whereas 0 in it means that the student hasn’t taken any courses.
Intermediate DBMS Interview Questions
8. What is meant by Data Warehousing?
Page 9                                                           © Copyright by Interviewbit
                                                                DBMS Interview Questions
The process of collecting, extracting, transforming, and loading data from multiple
sources and storing them into one database is known as data warehousing. A data
warehouse can be considered as a central repository where data flows from
transactional systems and other relational databases and is used for data analytics. A
data warehouse comprises a wide variety of organization’s historical data that
supports the decision-making process in an organization.
9. Explain different levels of data abstraction in a DBMS.
The process of hiding irrelevant details from users is known as data abstraction. Data
abstraction can be divided into 3 levels:
Page 10                                                         © Copyright by Interviewbit
                                                                DBMS Interview Questions
     Physical Level: it is the lowest level and is managed by DBMS. This level
     consists of data storage descriptions and the details of this level are typically
     hidden from system admins, developers, and users.
     Conceptual or Logical level: it is the level on which developers and system
     admins work and it determines what data is stored in the database and what is
     the relationship between the data points.
     External or View level: it is the level that describes only part of the database
     and hides the details of the table schema and its physical storage from the users.
     The result of a query is an example of View level data abstraction. A view is a
     virtual table created by selecting fields from one or more tables present in the
     database.
10. What is meant by an entity-relationship (E-R) model?
    Explain the terms Entity, Entity Type, and Entity Set in
    DBMS.
An entity-relationship model is a diagrammatic approach to a database design where
real-world objects are represented as entities and relationships between them are
mentioned.
Page 11                                                         © Copyright by Interviewbit
                                                                  DBMS Interview Questions
     Entity: An entity is defined as a real-world object having attributes that
     represent characteristics of that particular object. For example, a student, an
     employee, or a teacher represents an entity.
     Entity Type: An entity type is defined as a collection of entities that have the
     same attributes. One or more related tables in a database represent an entity
     type. Entity type or attributes can be understood as a characteristic which
     uniquely identifies the entity. For example, a student represents an entity that
     has attributes such as student_id, student_name, etc.
     Entity Set: An entity set can be defined as a set of all the entities present in a
     specific entity type in a database. For example, a set of all the students,
     employees, teachers, etc. represent an entity set.
11. Explain different types of relationships amongst tables in a
    DBMS.
Following are different types of relationship amongst tables in a DBMS system:
     One to One Relationship: This type of relationship is applied when a particular
     row in table X is linked to a singular row in table Y.
Page 12                                                           © Copyright by Interviewbit
                                                               DBMS Interview Questions
     One to Many Relationship: This type of relationship is applied when a single
     row in table X is related to many rows in table Y.
     Many to Many Relationship: This type of relationship is applied when multiple
     rows in table X can be linked to multiple rows in table Y.
     Self Referencing Relationship: This type of relationship is applied when a
     particular row in table X is associated with the same table.
Page 13                                                        © Copyright by Interviewbit
                                                                DBMS Interview Questions
12. Explain the difference between intension and extension in a
    database.
Following is the major difference between intension and extension in a database:
     Intension: Intension or popularly known as database schema is used to define
     the description of the database and is specified during the design of the
     database and mostly remains unchanged.
     Extension: Extension on the other hand is the measure of the number of tuples
     present in the database at any given point in time. The extension of a database
     is also referred to as the snapshot of the database and its value keeps changing
     as and when the tuples are created, updated, or destroyed in a database.
13. Explain the difference between the DELETE and TRUNCATE
    command in a DBMS.
DELETE command: this command is needed to delete rows from a table based on
the condition provided by the WHERE clause.
Page 14                                                         © Copyright by Interviewbit
                                                                  DBMS Interview Questions
     It deletes only the rows which are specified by the WHERE clause.
     It can be rolled back if required.
     It maintains a log to lock the row of the table before deleting it and hence it’s
     slow.
TRUNCATE command: this command is needed to remove complete data from a
table in a database. It is like a DELETE command which has no WHERE clause.
     It removes complete data from a table in a database.
     It can be rolled back even if required.
     It doesn’t maintain a log and deletes the whole table at once and hence it’s fast.
14. What is a lock. Explain the major difference between a
    shared lock and an exclusive lock during a transaction in a
    database.
A database lock is a mechanism to protect a shared piece of data from getting
updated by two or more database users at the same time. When a single database
user or session has acquired a lock then no other database user or session can modify
that data until the lock is released.
     Shared Lock: A shared lock is required for reading a data item and many
     transactions may hold a lock on the same data item in a shared lock. Multiple
     transactions are allowed to read the data items in a shared lock.
     Exclusive lock: An exclusive lock is a lock on any transaction that is about to
     perform a write operation. This type of lock doesn’t allow more than one
     transaction and hence prevents any inconsistency in the database.
15. What is meant by normalization and denormalization?
Normalization is a process of reducing redundancy by organizing the data into
multiple tables. Normalization leads to better usage of disk spaces and makes it
easier to maintain the integrity of the database.
Page 15                                                           © Copyright by Interviewbit
                                                               DBMS Interview Questions
Denormalization is the reverse process of normalization as it combines the tables
which have been normalized into a single table so that data retrieval becomes faster.
JOIN operation allows us to create a denormalized form of the data by reversing the
normalization.
Advanced DBMS Interview Questions
16. Explain different types of Normalization forms in a DBMS.
Following are the major normalization forms in a DBMS:
Page 16                                                        © Copyright by Interviewbit
                                                              DBMS Interview Questions
Considering the above Table-1 as the reference example for understanding
different normalization forms.
     1NF: It is known as the first normal form and is the simplest type of
     normalization that you can implement in a database. A table to be in its first
     normal form should satisfy the following conditions:
          Every column must have a single value and should be atomic.
          Duplicate columns from the same table should be removed.
          Separate tables should be created for each group of related data and each
          row should be identified with a unique column.
Page 17                                                       © Copyright by Interviewbit
                                                               DBMS Interview Questions
Table-1 converted to 1NF form
     2NF: It is known as the second normal form. A table to be in its second normal
     form should satisfy the following conditions:
         The table should be in its 1NF i.e. satisfy all the conditions of 1NF.
         Every non-prime attribute of the table should be fully functionally
         dependent on the primary key i.e. every non-key attribute should be
         dependent on the primary key in such a way that if any key element is
         deleted then even the non_key element will be saved in the database.
Page 18                                                        © Copyright by Interviewbit
                                                                DBMS Interview Questions
Breaking Table-1 into 2 different tables to move it to 2NF.
     3NF: It is known as the third normal form. A table to be in its second normal
     form should satisfy the following conditions:
          The table should be in its 2NF i.e. satisfy all the conditions of 2NF.
          There is no transitive functional dependency of one attribute on any
          attribute in the same table.
Page 19                                                         © Copyright by Interviewbit
                                                                  DBMS Interview Questions
Breaking Table-1 into 3 different tables to move it to 3NF.
     BCNF: BCNF stands for Boyce-Codd Normal Form and is an advanced form of
     3NF. It is also referred to as 3.5NF for the same reason. A table to be in its BCNF
     normal form should satisfy the following conditions:
          The table should be in its 3NF i.e. satisfy all the conditions of 3NF.
          For every functional dependency of any attribute A on B
          (A->B), A should be the super key of the table. It simply implies that A can’t
          be a non-prime attribute if B is a prime attribute.
Page 20                                                           © Copyright by Interviewbit
                                                                DBMS Interview Questions
17. Explain different types of keys in a database.
There are mainly 7 types of keys in a database:
     Candidate Key: The candidate key represents a set of properties that can
     uniquely identify a table. Each table may have multiple candidate keys. One key
     amongst all candidate keys can be chosen as a primary key. In the below
     example since studentId and firstName can be considered as a Candidate Key
     since they can uniquely identify every tuple.
     Super Key: The super key defines a set of attributes that can uniquely identify a
     tuple. Candidate key and primary key are subsets of the super key, in other
     words, the super key is their superset.
Page 21                                                         © Copyright by Interviewbit
                                                              DBMS Interview Questions
     Primary Key: The primary key defines a set of attributes that are used to
     uniquely identify every tuple. In the below example studentId and firstName are
     candidate keys and any one of them can be chosen as a Primary Key. In the given
     example studentId is chosen as the primary key for the student table.
     Unique Key: The unique key is very similar to the primary key except that
     primary keys don’t allow NULL values in the column but unique keys allow them.
     So essentially unique keys are primary keys with NULL values.
     Alternate Key: All the candidate keys which are not chosen as primary keys are
     considered as alternate Keys. In the below example, firstname and lastname are
     alternate keys in the database.
     Foreign Key: The foreign key defines an attribute that can only take the values
     present in one table common to the attribute present in another table. In the
     below example courseId from the Student table is a foreign key to the Course
     table, as both, the tables contain courseId as one of their attributes.
     Composite Key: A composite key refers to a combination of two or more
     columns that can uniquely identify each tuple in a table. In the below example
     the studentId and firstname can be grouped to uniquely identify every tuple in
     the table.
Page 22                                                       © Copyright by Interviewbit
                                                                DBMS Interview Questions
18. Explain the difference between a 2-tier and 3-tier
    architecture in a DBMS.
The 2-tier architecture refers to the client-server architecture in which applications
at the client end directly communicate with the database at the server end without
any middleware involved.
Example – Contact Management System created using MS-Access or Railway
Reservation System, etc.
          The above picture represents a 2-tier architecture in a DBMS.
The 3-tier architecture contains another layer between the client and the server to
provide GUI to the users and make the system much more secure and accessible. In
this type of architecture, the application present on the client end interacts with an
application on the server end which further communicates with the database system.
Example – Designing registration form which contains a text box, label, button or a
large website on the Internet, etc.
Page 23                                                         © Copyright by Interviewbit
                                                            DBMS Interview Questions
          The above picture represents a 3-tier architecture in a DBMS.
Recommended Tutorials:
SQL Interview Questions
SQL Server Interview Questions
MySQL Interview Questions
MongoDB Interview Questions
PL SQL Interview Questions
Page 24                                                     © Copyright by Interviewbit
Links to More Interview
Questions
 C Interview Questions         Php Interview Questions       C Sharp Interview Questions
 Web Api Interview             Hibernate Interview           Node Js Interview Questions
 Questions                     Questions
 Cpp Interview Questions       Oops Interview Questions      Devops Interview Questions
 Machine Learning Interview    Docker Interview Questions    Mysql Interview Questions
 Questions
 Css Interview Questions       Laravel Interview Questions   Asp Net Interview Questions
 Django Interview Questions    Dot Net Interview Questions   Kubernetes Interview
                                                             Questions
 Operating System Interview    React Native Interview        Aws Interview Questions
 Questions                     Questions
 Git Interview Questions       Java 8 Interview Questions    Mongodb Interview
                                                             Questions
 Dbms Interview Questions      Spring Boot Interview         Power Bi Interview Questions
                               Questions
 Pl Sql Interview Questions    Tableau Interview             Linux Interview Questions
                               Questions
 Ansible Interview Questions   Java Interview Questions      Jenkins Interview Questions
Page 25                                                            © Copyright by Interviewbit