Question Groupwise
Question Groupwise
Question Groupwise
Group_VBNet_WINForm
Group_VBNet_WebForm
Group_ASPNetCore_MVC +C#
Group_React_AspNetCore
Group_VC++_MFC
Group_Java
Group_WPF
SQL
OOP’S Concept Question and Answer
Question 1: - What is OOP’s?
Ans: OOP stands for Object Oriented Programming. It is a programming
methodology that uses Objects to build a system or web applications using
programming languages like C#, Vb.net etc.
Question 2: -Main Pillars of OOP’s?
Ans: There are list of top 6 OOPS concepts that we can implement in all major
programming languages like c#, vb.net etc.
1- Class
2- Object
3- Abstraction
4- Encapsulation
5- Inheritance
6- Polymorphism
---------------------------------------------------------------------------------------------------------------------------------- -
//accessible outside
Console.Read();
}
}
class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar
object
myCar.honk();
// Display the value of the brand field (from the Vehicle class)
and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
using System;
class GFG {
// Main Method
public static void Main (String [] args)
{
// Creating Object
GFG ob = new GFG ();
Example: -
using System;
namespace Calculator {
class Calculator {
class EntryPoint
{
// Driver Code
static void Main (String []args)
{
calc = -calc;
SOLID
SOLID is a set of guidelines or rules that help software developers write clean, maintainable,
and flexible code.
The following five concepts make up our SOLID principles/SOLID is an acronym that stands
for:
Single Responsibility
Open/Closed
Liskov Substitution
Interface Segregation
Dependency Inversion
• Single Responsibility Principle (SRP): This principle says that each class or object
should have only one job or responsibility. It's like a person doing only one task really
well. For example, if you have a toy robot, it should only do things related to being a
robot, like moving and making sounds, but not things like cooking or cleaning.
• Open/Closed Principle (OCP): This principle means that once a class is written and
working, it should be closed for modification, but open for extension. It's like a toy car
that you can change and add new parts to, but you don't have to change the whole
car to do it. You can add new wheels or change the colour without modifying the
entire car.
• Dependency Inversion Principle (DIP): This principle states that classes should
depend on abstractions (more general things) rather than concrete implementations
(specific things). It's like playing with building blocks. You don't need to know exactly
how each block is made; you just need to know how they fit together to build
something cool.
=> To ensure adherence to the Liskov Substitution Principle (LSP) when designing a
new class hierarchy, we need to ensure that any subclass can be used in place of its
parent class without affecting the correctness of the program. Here are some
guidelines:
• Each subclass should implement all the methods of its parent class.
• The preconditions of the overridden methods in the subclass should not be
stronger than those in the parent class.
• The postconditions of the overridden methods in the subclass should not be
weaker than those in the parent class.
• The invariants of the parent class should be preserved in the subclass.
Q11) How would you refactor a codebase to adhere to the Interface
Segregation Principle (ISP)?
=> To adhere to the Interface Segregation Principle (ISP), we should break down
large interfaces into smaller and more specialised ones so that clients only need to
depend on the interfaces that they actually use. Here are some steps we can take to
refactor a codebase to adhere to ISP:
19. Identify interfaces that are too large or that have methods that are not being
used by their clients.
20. Break down those interfaces into smaller and more specialised ones, based
on the needs of the clients that use them.
21. Make sure that clients only depend on the interfaces that they actually use.
Q12) How would you design a dependency injection container to adhere to the
Dependency Inversion Principle (DIP)?
=> A dependency injection container is a tool used to implement the Dependency
Inversion Principle (DIP) by providing a mechanism for loosely coupling objects and
their dependencies. To design a dependency injection container that adheres to the
DIP, you can define interfaces for your dependencies and then use those interfaces
to inject concrete implementations.
WPF Question
1. What is WPF?
1. XAML (eXtensible Application Markup Language): WPF uses XAML as its markup
language. XAML allows developers to define the user interface and the visual elements of an
application in a declarative manner, separate from the application logic. It provides a clean
separation between the UI and the code-behind.
2. Controls and Styles: WPF provides controls that can be easily customized and styled to
achieve a consistent and visually appealing look. Controls such as buttons, textboxes, list
boxes, menus, and more are available, and developers can define their own styles and
templates as per their need.
3. Data Binding: WPF provides data binding capabilities, allowing developers to establish a
connection between the UI elements and the data sources. It supports different types of data
binding modes (one-way, two-way, etc.) and facilitates automatic synchronization between
the UI and the data.
1. Model:
- The Model represents the data and business logic of your application.
- It could be classes that define the data structure, retrieve data from a database, or
perform calculations.
- The Model is independent of the UI and does not know anything about how the data will
be presented.
2. View:
- The View represents the user interface, including the visual elements and controls that
users interact with.
- It is responsible for displaying the data from the ViewModel and capturing user input.
- In WPF, the View is typically defined using XAML, which describes the structure and
appearance of the UI elements.
3. ViewModel:
- The ViewModel acts as a bridge between the Model and the View.
- It provides the data and behaviors required by the View, exposing properties and
commands.
- The ViewModel transforms the data from the Model into a format that the View can easily
bind to and display.
- It also handles user interactions and performs actions by invoking commands in the
Model.
4. Data Binding:
- Data binding is a key component of the MVVM pattern.
- It allows you to establish a connection between the properties in the ViewModel and the
UI elements in the View.
- Through data binding, changes in the ViewModel are automatically reflected in the View,
and user input is captured and propagated to the ViewModel.
5. Separation of Concerns:
- The MVVM pattern promotes the separation of concerns, allowing different team
members (such as designers and developers) to work on their specific areas.
- The Model focuses on data and business logic, the View on the visual representation,
and the ViewModel on providing data and behavior to the View.
The MVVM pattern helps improve the maintainability, testability, and reusability of WPF
applications. It enables a clear separation between the UI and business logic, making it
easier to modify and enhance the application without affecting other parts. The ViewModel
acts as a mediator, allowing the View to remain independent of the Model and facilitating
efficient development and testing workflows.
Data binding in WPF is a way to connect data from a source (such as variables, properties,
or collections) to the user interface (UI) elements of your application. It ensures that changes
in the data are automatically reflected in the UI, and vice versa. Let's understand how data
binding works in simple language:
Imagine you have a textbox in your application, and you want its content to be synchronized
with a variable or property. Data binding allows you to establish a connection between the
textbox and the data source. Here's how it works:
4. Change Notification:
- For two-way binding to work properly, the data source (such as the ViewModel) should
implement the INotifyPropertyChanged interface.
- This interface provides a way for the data source to notify the UI about changes in the
bound properties.
- When a property changes, the data source raises an event, notifying the UI to update the
bound elements.
5. Value Converters:
- Sometimes, you may need to convert the data from the source to a different format or
vice versa.
- WPF provides value converters that allow you to perform such conversions.
- For example, you can convert a DateTime object to a formatted string for display in a
textbox.
By using data binding in WPF, you eliminate the need to manually synchronize data between
the UI and your data source. Any changes made in the UI or the data source are
automatically reflected in the other, resulting in a responsive and dynamically updated user
interface. Data binding simplifies UI development, promotes separation of concerns, and
ensures consistency between data and UI elements.
4. What are the different types of panels available in WPF for layout management?
In WPF, panels are used for organizing and arranging controls in a specific layout. Think of
panels as containers that hold controls and determine how they are positioned and displayed
on the screen. Here are a few types of panels available in WPF, explained in simple
language:
1. StackPanel:
- Imagine a stack of items, one on top of another or side by side.
- A StackPanel arranges controls either vertically or horizontally, depending on its
orientation.
- Controls added to a StackPanel are placed one after another in the stacking direction.
2. Grid:
- Picture a table with rows and columns.
- A Grid allows you to divide the available space into rows and columns to position
controls.
- Controls can be placed in specific cells of the grid, allowing for precise layout and
alignment.
3. DockPanel:
- Think of a dock where you can anchor objects to different edges.
- A DockPanel allows controls to be "docked" to the top, bottom, left, or right edges.
- Docked controls occupy the full width or height along the specified edge, while remaining
space is filled by other controls.
4. WrapPanel:
- Imagine a horizontal or vertical strip that wraps to the next line when space runs out.
- A WrapPanel arranges controls in a flow-like manner, wrapping to the next line when
necessary.
- Controls are placed one after another, and when the available space is filled, they wrap
to the next line.
5. Canvas:
- Think of a blank canvas where you can freely position controls at specific coordinates.
- A Canvas allows controls to be positioned at precise X and Y coordinates within the
panel.
- Controls are placed wherever you specify, giving you complete control over their
placement.
These panel types offer different ways to manage the layout and positioning of controls in
your WPF application. StackPanel allows for simple stacking, Grid provides a structured
table-like layout, DockPanel enables anchoring controls to edges, WrapPanel allows for
flexible wrapping, and Canvas offers absolute positioning. By choosing the appropriate panel
type, you can achieve the desired layout and arrangement of controls in your user interface.
In WPF, resource dictionaries play a significant role in managing and organizing reusable
resources such as styles, templates, brushes, data templates, and more. A resource
dictionary is a XAML file that contains a collection of resources that can be shared and
accessed by multiple elements in an application.
Commands in WPF provide a way to encapsulate and handle user actions or application
functionality in a decoupled and reusable manner. They enable a separation between the UI
controls that trigger actions and the logic that performs those actions. The purpose of
commands is to provide a consistent and extensible approach to handle user interactions.
1. Styles:
- Styles are like predefined sets of properties that you can apply to one or more controls.
- Think of styles as a way to give controls a specific look and feel.
- For example, you can create a style that sets the background color, font size, and other
properties of buttons.
- Once you define a style, you can easily apply it to multiple buttons or other controls to
make them all look the same.
- It's like applying a predefined design to multiple elements in one go.
2. Templates:
- Templates allow you to completely change the structure and appearance of a control.
- Think of a template as a blueprint or skeleton for a control.
- With a template, you can redefine how a control looks, including its layout, visual
elements, and behavior.
- For example, you can create a template for a ListBox that changes the way items are
displayed or adds additional visual elements.
- Templates let you go beyond changing properties and enable you to create a unique and
custom design for controls.
By applying styles and templates, you can easily change the appearance and behavior of
controls in your WPF application. Styles help you maintain a consistent design across
multiple controls, while templates allow you to create unique and custom designs for
controls. It's like giving controls a new look and feel or changing their structure to suit your
specific design requirements.
In WPF, routed events provide a way to handle and respond to user interactions or other
events that occur in the UI. Routed events follow a hierarchical route, allowing multiple
elements to participate in the event handling process. Here's a simplified explanation of the
concept of routed events in WPF:
Imagine you have a button inside a grid, which is inside a window. When you click the
button, a "Click" event is raised. Routed events enable this "Click" event to travel through a
route, involving multiple elements in the UI hierarchy.
Tunnelling Phase:
The event starts from the top-most element (the window) and travels down the visual tree
towards the target element (the button).
During the tunneling phase, the event is known as a "tunneling event" and uses a predefined
tunneling route.
Parent elements can choose to handle the event at this stage, even before reaching the
target element.
Target Phase:
Once the event reaches the target element (the button), it enters the target phase.
The event is raised and handled by the target element itself.
This phase is also known as the "direct event" phase.
Bubbling Phase:
After the target phase, the event starts to travel back up the visual tree, from the target
element towards the top-most element.
During the bubbling phase, the event is known as a "bubbling event" and uses a predefined
bubbling route.
Parent elements can handle the event at this stage, reacting to it as it bubbles up.
The key idea behind routed events is that multiple elements can handle the same event
along the event route, allowing for flexible event handling and interaction. Elements can
choose to handle events at different phases, enabling customization and intervention at
various levels of the UI hierarchy.
Converters in WPF data binding are used to convert data from one format to another during
the binding process. They allow you to modify the data before it is displayed in the UI or
before it is passed back to the data source.
Imagine you have a numeric value in your data source that you want to display as a
formatted string in a TextBlock. However, the numeric value itself cannot be directly
displayed as desired. Here's where converters come into play:
1. Purpose of Converters:
- Converters provide a way to customize the conversion logic between the data source and
the UI elements.
- They allow you to transform the data to a different format, such as changing the data
type, applying formatting, or performing calculations.
- Converters can be useful in scenarios where the data needs to be modified before being
displayed or when the input provided by the user needs to be transformed before being
stored.
2. Implementing a Converter:
- To create a converter, you need to implement the IValueConverter interface provided by
WPF.
- The IValueConverter interface has two methods: Convert and ConvertBack.
- The Convert method is called when data flows from the data source to the UI, converting
the source value to the desired format.
- The ConvertBack method is called when data flows from the UI back to the data source,
converting the UI value to the source format.
- You can customize the logic within these methods to perform the necessary conversions.
```csharp
using System;
using System.Globalization;
using System.Windows.Data;
```xaml
<Window.Resources>
<local:NumericToStringConverter x:Key="NumericConverter" />
</Window.Resources>
By using converters in WPF data binding, you have the flexibility to modify the data format,
apply custom logic, or perform calculations before it is displayed or stored. Converters help
customize the data conversion process and allow you to present data in a more suitable and
meaningful way in the UI.
9- How can you create custom controls in WPF? Explain the steps involved.
Creating custom controls in WPF allows you to build reusable UI components tailored to
your specific needs. Here are the steps involved in creating custom controls in simple
language:
10- What are dependency properties in WPF? How do they differ from regular
properties?
In WPF, dependency properties are a specialized type of property that provide several
additional capabilities compared to regular properties. They are a fundamental concept in
WPF and offer enhanced features for data binding, property value inheritance, and change
notifications. Let's understand dependency properties and how they differ from regular
properties:
3. Data Binding:
- Dependency properties are designed to work seamlessly with data binding in WPF.
- They support two-way data binding, allowing data to flow between the property value and
the data source.
- By defining a dependency property, you can easily bind it to other elements, properties,
or data sources in your application.
4. Change Notification:
- Dependency properties provide a built-in change notification mechanism.
- When a dependency property value changes, the property system automatically notifies
any registered listeners, such as data binding expressions or event handlers.
- This enables UI updates, recalculations, or any other action that needs to be performed
when a property changes.
5. Property Metadata:
- Dependency properties support metadata, which allows you to specify additional
information about the property.
- Metadata can include default values, property change callbacks, validation rules, or other
custom behavior.
- Metadata helps define the behavior and characteristics of the dependency property.
1. Flow documents-Flow format document alters the content to fit the screen size.
They are designed to optimize viewing and readability.
EXAMPLE
A Web page is a simple example of a flow document where the page content is dynamically
formatted to fit in the current window.
2.Fixed documents-document present content irrespective of the screen size.
They are intended for applications that require a precise "what you see is what you
get"
Example: Flow documents optimize the viewing and reading experience for the user,
based on the runtime environment.
A dependency property can reference a value through data binding. Data binding works
through a specific markup extension syntax in XAML, or the Binding object in code.
Q6. How can the size of StatusBar be increased proportionally?
Answer-By overruling the ItemsPanel attribute of StatusBar with a grid. The grid’s columns
can be appropriately configured to get the desired result.
A status bar is a graphical control element which poses an information area typically found
at the window's bottom. It can be divided into sections to group information.
1. SetValue-This function allows you to dynamically set the value of a registered field and
have the options to validate and update the form state.
2.ClearValue- Clear the value of an input or textarea element. Make sure you can interact
with the element before using this command.
PRISM utilizes MVVM, IC, Command Patterns, DI and Separation of Concerns to get loose
coupling.
In computing and systems design, a loosely coupled system is one in which components
are weakly associated with each other, and thus changes in one component least affect
existence or performance of another component
The controls of this Window form can be placed besides WPF controls in a WPF page by
utilizing the functions of the WindowsFormsHost control that comes preinstalled.
Windows Forms is a free and open-source graphical class library included as a part of
Microsoft .NET, .NET Framework or Mono, providing a platform to write client applications
for desktop, laptop, and tablet PCs.
a) WindowsBase.dll:- This is the core type constituting the infrastructure of WPF API.
Animation is a method by which still figures are manipulated so that they appear to be
moving images.
A list box is a graphical control element that allows the user to select one or more items
from a list contained within a static, multiple line text box
For instance, this code sorts elements of ContentControl on the basis of their word
count property:
myItemsControl.Items.SortDescriptions.Add(new SortDescription(“WordCount”,
ListSortDirection.Descending));
In MVVM, View Model is used instead of a controller. This View Model is present beneath
the UI layer. It reveals the command objects and data that the view requires. It acts like
a container object from which the view gets its actions and data.
Model–view–controller (MVC) is a software design pattern commonly used for developing
user interfaces that divides the related program logic into three interconnected elements.
Grid Panel- A Grid panel can be used to design complicated user interfaces where we need
to place multiple elements in a tabular form of rows and columns layout.
Canvas Panel-A Canvas panel is used to position child elements by using coordinates that
are relative to the canvas area.
Dock Panel-The DockPanel makes it easy to dock content in all four directions (top, bottom,
left and right.
Wrap Panel- WPF WrapPanel control is a panel that positions child elements in sequential
position from left to right by default.
Q23. Name the important subsystems in WPF
Answer-The major subsystems are:
Windows.Controls.Control
Windows.DependancyObject
Windows.FrameworkElement
Windows.Media.Visuals
Object
Threading.DispatcherObject
Windows.UIElements
BAML is a compressed declarative language, which gets loaded and parsed quicker than
XAML.
Q25. What is the Difference between Page and Window Controls in WPF?
Answer-
The basic difference is that Window Control presides over Windows Application while Page
Control presides over the hosted Browser Applications. Also, Window control may
contain Page Control, but the reverse cannot happen.
Q28. What is the basic difference between Events and Commands in the MVVM
Model?
Answer-Commands are more powerful and are advantageous to use instead of
events. Actions are deeply connected with the event’s source and, therefore, the events
cannot be reused easily.
But commands make it possible to efficiently maintain multiple actions at one place
and then reuse them as per our requirement.
Q29. What is the method to force close a ToolTip, which is currently visible?
Answer-It can be closed by setting the tooltip’s IsOpen property to false.
And due to this reason, Dynamic Resource is heavy on the system but it makes pages
or windows load faster
View – It is the code that agrees with the visual representation of the data.
ViewModel – It is the layer that binds View and Model together. It presents this data in a
manner, which is easy to understand. It also controls how View interacts with the application.
These logical pixels are always mentioned as double, this enables them to have a
fractional value too.
Adorners are bound to the UIElement and are rendered on a surface that lies above
the element, which is adorned.
This surface is called an AdornerLayer. Adorners are mostly placed relatively to the
bounded element.
But hosted applications are not given full admission to the client’s machine and are
executed in a sandbox environment. Using WPF, such applications can also be created,
which run directly in the browser. These applications are called XBAP.
Q41. How to make a ToolTip appear while hovering over a disabled element?
Answer-For this purpose, the ShowOnDisabled property can be used. It belongs to the
ToolTipService class.
Tunneling – This event is first raised by the element in which it was originated and then it
gets raised by each consecutive container in the visual tree.
Bubbling – This event is first raised by the uppermost container in the visual tree and then
gets raised by each consecutive container lying below the uppermost one, till it reaches the
element it where it was originated.
ComboBoxItem is a content control and is thus very useful for adding simple strings
to a ComboBox.
Q47. How to get Automation IDs of items in an ItemsControl?
Answer-The best way to do this is by setting it Name property as it is utilized for automation
purposes by default.
But if you require to give an ID to an element, other than it’s name, then the
AutomationProperties.AutomationID property can be set as per need.
Q49. State the name of the classes, which contain arbitrary content.
Answer-
Content Control
HeaderedContent Control
Items Control
HeaderedItems Control
Q51. Explain what is XAML? What is the difference between XML and XAML?
Answer-XAML stands for eXtensible Application Markup Language. It is the language used
to instantiate.NET objects. It is the language developed by Microsoft to write user
interface for next generation applications.
XML is designed to store data or to work with the stored data, whereas XAML is the
extended version of XML used for.NET programming.
<TextBlock>
Hello, World!
</TextBlock>
</Page>
Click
</Button>
For example,
XAML
The purpose of the mark up extension is to process a string and return an object.
Some of the standard markup extensions are xNull, x: Array, :StaticResource and
DynamicResource.
Root Elements
Panel Elements
Control Elements
Geometric Elements
x: Class It specifies the CLR ( Common Language Runtime) namespace and class name for
the class that provides code
x: Name It specifies a run-time object name for the instance that exist in run time code after
an object element is processed
x: Static It enables a reference that returns a static value which otherwise an XAML
compatible property
x: Type It constructs a Type reference based on the type name
Q61. How can you set a property attribute as a literal string and not a markup
extension?
Answer-To avoid markup extension you have to use an empty pair of curly braces like
Q62. What are the types of children does object element can have in XAML?
Answer-Three types of children an object element can have
Collection Items
A value for the content property
The value that can be type-converted to the object element
CanConvertTo
CanConvertFrom
ConvertTo
ConvertFrom
Q65. What are the ways you can declare objects in XAML?
Answer-To declare objects in XAML, there are three ways-
Directly, using object element syntax: This syntax is used to declare root objects or nested
objects that set property values
Indirectly by using attribute syntax: This syntax uses an inline string value which has
an instruction on how to create an object. To set the value of the property to a newly
created reference, the XAML parser uses this string
Using a markup extension
Q66. What should a root element of an XAML document contain?
Answer-In XAML document, the root element consists only certain elements, and these
elements are Window, a Canvas or panels.
Q68. Explain how you can display different data at run time and design time?
Answer-One way of displaying data at run time and design time is to declare your data in
XAML
Another way of doing it is by declaring it in XAML by using various data attributes from the
designer XML namespace. With a d: prefix, this namespace is typically declared.
xmlns: d= http://schemas.microsoft.com/expression/blend/2008
Static Resource We should use the StaticResource markup extension to define the
resource as a static resource.
Dynamic Resource We use in a situation where we want to change the value of property at
run time.
Q76 How can you explain the view and view model in MVVM?
Answer: The View is the client interface, input-output interface or the user interface. It
collects all the user interface elements of the window, navigation page, user control,
resource file, style and themes, custom tools and controls.
The view is unaware of the ViewModel and the Model, and vice versa the ViewModel
and Model is unaware of the View and control is tightly decoupled.
Q 78 What is the Data Binding concept and How Binding works in WPF?
Answer: Data Binding is one of the greatest and most powerful features of XAML (WPF,
Silverlight, Windows Phone or Windows 8) compared to other traditional web and Windows
app technology in .NET. There was simple data binding for displaying single values, and
complex data binding for displaying and formatting a bunch of data.
For example, you would use a Trigger on IsMouseOver to respond to the mouse being over
the control, and the setters might update a brush to show a "hot" effect.
For example, you can set the background property on several elements in a WPF
application using a single resource. The best way of defining the resources is on a Window
or Page element level. Any resource that you define for an element also applies to their child
elements of that element.
If you define a resource for the grid element, then the resource applies only to the child
elements of the grid element.
Group_VBNet_WINForm
Model business layer, the part of the application that handles the logic for the application
data lies between View and Controller.
View represents User interface for MVC application where we HTML controls to interact
with User. We use HTML Helper Classes to design UI.
Controller It’s the major building block in MVC, inherited by “Controller” Class Which
provides features like Action Filter, Partial View, View Data, Temp Data etc.
Q2> How is it different from ASp.Net ?
Comparison to its Predecessor ASP.Net (Active Server Pages) which is Page Controller
pattern, which is also used for creating Web Applications. Note: ASP is also ServerSide
Technology
In MVC we integrate other technologies like JavaScript, jQuery, Bootstrap Entity framework
etc to create Responsive Web Pages.
=>
Solution-
The top-level container that represents the entire project solution. It contains one or more
projects and solution files (.sln)
Root –The "wwwroot" folder is where static files such as CSS, JavaScript, images, and other
client-side assets are stored. These files are directly accessible by the client browser.
Controller –
This folder or project section contains the controller classes that handle the incoming HTTP
requests, perform actions, and prepare data to be rendered in the views.
Models –
The "Models" folder or project section holds the classes that represent the data structures,
entities, or business objects used within the application.
View-
The "Views" folder or project section contains the Razor views responsible for rendering the
HTML and generating the user interface.
appsettings.json –
This file contains configuration settings of the application. It helps to store config
information.
Here we can store info like database connection string, application variable values etc.
program.cs –
It is your application’s entry point which starts when you run your application. Here you
create your application host, choose the web server, add services, authorization and
authentications.
Dependencies-
This section shows the dependencies of the selected project, including NuGet packages,
project references, and other external libraries or frameworks used in the application.
Properties:
The "Properties" folder or section contains project-specific settings and metadata files. It may
include files like "launchSettings.json", which defines the launch profiles for the application.
Multiple view support: Multiple views of the same data can be displayed at the same time.
Parallel Development: The development progresses in parallel
Controls: The ASP.NET MVC framework provides more control over HTML, JavaScript,
and CSS than the traditional Web Forms.
Lightweight : ASP.NET MVC framework doesn’t use View State and thus reduces the
bandwidth of the requests to an extent.
SEO-friendly development: Improving its visibility and ranking in search engine results.
Code Reusability: With MVC, the separation of concerns allows for greater code reusability.
For example, you can reuse the same model or business logic across multiple views or
interfaces.
Enhanced Testability: Due to the separation of concerns, each component in MVC can be
tested independently.
Flexibility and Scalability: MVC provides a flexible and scalable architecture for
applications.
As the codebase grows, it becomes easier to add new features, modify existing functionality,
or extend the application's capabilities without affecting other components. The modularity of
MVC allows for easier maintenance and updates.
Support for Multiple Views: In MVC, the same model can be associated with multiple
views, each representing a different presentation of the data. This allows for greater
flexibility in supporting different user interfaces or platforms, such as desktop, web, or
mobile applications, without duplicating the underlying logic.
Q9> MVC Application Life Cycle. /Can you explain the Request Life cycle of an
MVC application?
=> The life cycle of an MVC application involves the following steps:
Depending on the URL sent “UrlRoutingModule” searches the route table to create
“RouteData” object which has the details of which controller and action to invoke.
Step 3 - Request context created
The “RouteData” object is used to create the “RequestContext” object.
Route Table:
Q11> How to manage the life cycle of objects or components within the application?
1.Scoped: A scoped object/component is created and maintained within the scope of a
specific request or user session. In other words, a new instance of the scoped object is created
for each request or session and is available throughout the lifetime of that request or session.
2.Transient: A transient object/component is created each time it is requested and is not
shared across different parts of the application. In other words, a new instance is created
every time you need it.
3.Singleton: A singleton object/component is created only once and is shared across the
entire application. It means that the same instance of the singleton object is reused whenever
it is requested.
Q12> What are strongly typed models in MVC?
=> Strongly typed models are classes that represent the data passed between the controller
and the view.
Q13> Define Scaffolding in MVC?
=> AJAX functionality can be implemented in MVC by using the jQuery.ajax() method or
the AjaxHelper class to send asynchronous requests and update parts of the page
dynamically.
It is a view engine that combines HTML markup with server-side code to generate the final
HTML output. Razor provides a concise and expressive syntax for embedding server-side
code within HTML, making it easier to create dynamic and data-driven web applications.
Example of implementation:
=> You can implement authentication and authorization in MVC by using authentication
filters, authorization attributes.
=> The ModelState represents the state of a model and its validation errors. It is an instance
of the ModelStateDictionary class.
=> Form validation can be performed in MVC by using data annotations, implementing
custom validation attributes, or by manually validating the form data.
Also, while creating template for MVC, we have option to select languages like VB.Net, J#,
C# etc, same for the view .cshtml etc.
ASP.NET MVC uses default binders to complete this behind the scenes.
then use the following HTML Helper method
Syntax: @Html.Hidden(“id”)
=> Separation of Concerns can be defined as one of the core features as well as benefits of
using MVC and is supported by ASP.NET. Here, the MVC framework offers a distinct
detachment of the different concerns such as User Interface (UI), data and the business logic.
Q28>What is used to handle an error in MVC?
=> Error handling is usually done using Exception handling, whether it’s a Windows Forms
application or a web application. The HandleError attribute is used, which helps in providing
built-in exception filters. The HandleError attribute of ASP.NET can be functional over the
action method as well as Controller at its global level.
Example of implementation:
Model Binder
Q31> Different return types used by the controller action method in MVC
Q: Action Result in MVC:
=> Action Result is a return type of Action method. Base of for all return types of all Action
Methods
Ex: View, Partial View, Redirect, Json, Content, File, Redirect To Action, etc. are derived
from the abstract Action Result class .
=> It’s a Kind of User Control that can shared among different views.
When we have to return a Partial View instead of View from an Action Method in the ASP.NET
MVC Application. In that case we use Partial View Result.
The Partial View Result in MVC is returning the result to a Partial View Page.
A partial view is one of the views that we can call inside a normal view page.
Note: Normally, we keep Partial View inside the Shared Folder under View. So that it is
accessible to Controllers also the Controllers that are defined in Area. (Not mandatory)
Start with “_” under score.
Q33> How We Can Add Partial View/ Steps to Add Partial View?
=> Right-Click on the Shared Folder which is inside the Views folder
and then selects Add => View option from menu
which will open the following Add view window, select “Create as Partial View”.
How We can Convert Objects to Json, string etc/ Ex of Json Action Result?
=>With attribute routing, you can define routes right above the action methods in your
controllers using attributes, such as [Route] and [HttpGet]. This allows you to have more
control over the routing behavior and makes it easier to define custom routes for specific
actions.
Q36> Difference between attribute and conventional routing in mvc.
=> Conventional routing: The route is determined based on conventions that are defined in
route templates that, at runtime, will map requests to controllers and actions (methods).
Attribute-based routing: The route is determined based on attributes that you set on your
controllers and methods. These will define the mapping to the controller’s actions.
Q37> Mention what is the difference between adding routes to a webform application
and an MVC application?
Ans:
To add routes to a webform application, we can use MapPageRoute() method of the
RouteCollection class, where adding routes to an MVC application, you can use MapRoute()
method.
In ASP.NET MVC, you can use the async and await keywords along with asynchronous
methods to perform asynchronous programming. Additionally, ASP.NET MVC provides
asynchronous versions of various I/O-bound operations, such as reading and writing to
databases or making HTTP requests, allowing you to take advantage of asynchronous
programming in different parts of your application.
=> Errors can be handled in MVC by using try-catch blocks, implementing custom error
filters, or by using the HandleError attribute.
Q41> assembly in which the MVC framework
• temp data
• view bag :The ViewBag is a dynamic property that allows you to pass data from the
controller to the view. It is a dynamic wrapper around the ViewData dictionary.
=> ViewData is a dictionary object used to pass data between the controller and the view,
whereas ViewBag is a dynamic property that provides a similar functionality.
=> Session management is a scenario for storage of user data while the user browses a web
Application.
Some reasons why session management is needed.
User Authentication- When a user logs in to a web application, their login credentials are
verified, and a session is created.
User State Management:Sessions enable the storage and management of user-specific data
and state across multiple requests
Security and Authorization-
Customization and Personalization:
E-commerce and Shopping Carts
Stateful Web Applications
Tracking and Analytic
Q46>What is a cookie ?
.Non-Persistent Cookie: Non Persistent Cookie destroys when we close the browser.It is
Basically stateless in nature.
=> DOM stands for Document Object Model. In simple terms, it's a way for web browsers
to understand and manipulate web pages.
DOM is a tool that enables web browsers to understand and manipulate web pages. It
provides a structured representation of the elements
Q48> What is HTTP verbs and How many types of HTTP verbs?
[HttpGet]:. It is used when you want a specific action to handle GET requests for a
particular route.
[HttpPost]: It is used for form submissions or any action that requires modifying data on the
server.
[HttpPut]:. It is typically used for updating existing resources on the server.
[HttpDelete]:. It is used for deleting resources on the server.
25. What does a context mean in http
=> It represents the environment and data that is necessary to process and handle the request
or response correctly.
• 1.Request context: The request context contains information related to the HTTP
request being made. It includes details such as the request method (e.g., GET, POST),
the requested URL, request headers, query parameters, cookies, and form data.
•
• 2.Response context: The response context contains information related to the HTTP
response being sent back to the client. It includes details such as the response status
code (e.g., 200 OK, 404 Not Found).
•
• 3.Session context: The session context represents the state and data associated with a
user's session. In HTTP, which is a stateless protocol, sessions are typically managed
using cookies or URL rewriting.
Q49> Why are Minification and Bundling introduced in MVC?
=> Two new techniques have been included in MVC, known as Bundling and minification,
whose primary function is to progress the request load time. It advances the load time by
dipping the number of requests sent to the server as well as reducing the requested asset’s
(JavaScript and CSS) size.
=> There are situations where I want to implement some logic either prior to the execution of
the action method or right after it. In that scenario, the Action Filters are used. Filters are used
to determine the logic needed for executing before or after the action method gets executed.
Action methods make use of the action filters as an attribute.
It contains the layout page It does not contain the layout page
Before any view is rendered, viewstart page Partial view does not verify for a
is rendered viewstart.cshtml. We cannot put common
code for a partial view within the
viewStart.cshtml.page
View might have markup tags like body, Partial view is designed specially to render
html, head, title, meta etc. within the view, and just because of that it
does not consist any markup
• 3.Testability:, you can provide mock or stub implementations during testing, allowing
you to isolate and test individual components in isolation.
•
• 4.Response Processing: Once the request has passed through all the middleware
components and reached the controller, the controller performs its actions and
generates a response.
•
when we want to improve the performance of the application we use output caching, it
prevents the duplicate content to be loaded by caching the content returned by the controller,
When the controller methods are invoked, it is the best method to reduce the server round
trips, reduce database server round trips, reduce network traffic etc.
[HttpPost]
[OutputCache(Duration = 10, VaryByParam = "name")]
public ActionResult SearchCustomer(string name = "")
{
NorthwindEntities db = new NorthwindEntities();
var model = from r in db.Customers
where r.ContactName.Contains(name)
select r;
if (model.Count() > 0)
{
return View(model);
}
else
{
return View();
}
}
Q60>Explain RenderSection In MVC
RenderSection is used to designate a place to render content that is different from the one in
RenderBody.
Example:
@RenderSection("footer", required: false)
By default, a section is required. We pass required: false to designate that section is optional.
@Section is used to render section in View as:
@section Footer
{
<p>Section/Index page</p>
}
Group_React_AspNetCore
Q.1. What is the difference between Virtual DOM and Real DOM?
Ans. Virtual DOM Real DOM
Changes can be made easily Changes can be expensive
Minimal memory wastage High demand for memory and more wastage
JSX element is updated Creates a new DOM every time an element if the
element exists gets updated
Cannot update HTML directly Able to directly manipulate HTML
Faster updates Slow updates
2. What is React?
• React is a front-end JavaScript library developed by Facebook in 2011.
• It follows the component based approach which helps in building reusable
UI components.
• It is used for developing complex and interactive web and mobile UI.
• Even though it was open-sourced only in 2015, it has one of the largest
communities supporting it.
6. What is JSX?
JSX is a shorthand for JavaScript XML. This is a type of file used by React which
utilizes the expressiveness of JavaScript along with HTML like template syntax.
This makes the HTML file really easy to understand. This file makes applications
robust and boosts its performance. Below is an example of JSX:
render(){
return(
<div>
</div>
);
}
7. What do you understand by Virtual DOM? Explain its works.
A virtual DOM is a lightweight JavaScript object which originally is just a copy of
the real DOM. It is a node tree that lists the elements, their attributes and content
as Objects and their properties. React’s render function creates a node tree out of
the React components. It then updates this tree in response to the mutations in
the data model which is caused by various actions done by the user or by the
system.
1 // ES5
2 var React = require('react');
3
4 // ES6
5 import React from 'react';
1 // ES5
2 module.exports = Component;
3
4 // ES6
5 export default Component;
1 // ES5
2 var MyComponent =
React.createClass({
3
render: function() {
4
return
5
6
7 <h3>Hello Edureka!</h3>
8 ;
9 }
10 });
11
12 // ES6
13 class MyComponent extends
React.Component {
14
render() {
15
return
16
17
<h3>Hello Edureka!</h3>
18
;
19
}
}
xvi. props
1 // ES5
2 var App = React.createClass({
3 propTypes: { name:
React.PropTypes.string },
4
render: function() {
5
return
6
7
<h3>Hello,
8
{this.props.name}!</h3>
9
;
10
}
11
});
12
13 // ES6
14 class App extends
React.Component {
15
render() {
16
return
17
18
<h3>Hello,
19
{this.props.name}!</h3>
20
;
}
}
1 // ES5
2 var App = React.createClass({
3 getInitialState: function()
{
4
return { name: 'world'
5
};
6
},
7
render: function() {
8
return
9
10
<h3>Hello,
11 {this.state.name}!</h3>
12 ;
13 }
14 });
15
16 // ES6
17 class App extends
React.Component {
18
19 constructor() {
20 super();
21 this.state = { name:
'world' };
22
}
23
render() {
24
return
25
26
<h3>Hello,
{this.state.name}!</h3>
;
}
}
13. How can you embed two or more components into one?
We can embed components into one in the following way:
1 class MyComponent extends
React.Component{
2
render(){
3
return(
4
5
<div>
6
7
<h1>Hello</h1>
8
9
<Header/>
10
</div>
11
12
);
13
}
14
}
15
class Header extends
16
React.Component{
17
render(){
18
return
19
20
<h1>Header Component</h1>
21
22
};
23
}
24
ReactDOM.render(
25 <MyComponent/>,
document.getElementById('content
')
);
5 this.state = {
6 name: 'Maxx',
7 id: '101'
8 }
9 }
10 render()
11 {
12
setTimeout(()=>{this.setState({name
13
:'Jaeha', id:'222'})},2000)
14
return (
15
16
<div>
17
18
<h1>Hello {this.state.name}</h1>
19
20
<h2>Your Id is {this.state.id}</h2>
21
22
</div>
23
24
);
25
}
26
}
27
ReactDOM.render(
<MyComponent/>,
document.getElementById('content')
);
2 render() {
3 return(
4 <MyInput
onChange={this.handleChange.bind(th
5
is) } />
6
);
7
}
8
//With Arrow Function
9
render() {
10
return(
11
<MyInput onChange={ (e) =>
12 this.handleOnChange(e) } />
);
}
1. Stores info about component’s state change in 1. Calculates the internal state of the
memory components
2. Have authority to change state 2. Do not have the authority to change state
3. Contains the knowledge of past, current and 3. Contains no knowledge of past, current and
possible future changes in state possible future state changes
4. Stateless components notify them about the 4. They receive the props from the Stateful
requirement of the state change, then they send components and treat them as callback
down the props to them. functions.
xxvii. Events are named using camel case instead of just using the
lowercase.
xxviii. Events are passed as functions instead of strings.
The event argument contains a set of properties, which are specific to an event.
Each event type contains its own properties and behavior which can be accessed
via its event handler only.
23. How do you create an event in React?
1 class Display extends
React.Component({
2
show(evt) {
3
// code
4
},
5
render() {
6
// Render the div with
7
an onClick prop (value is a
8 function)
9 return (
10
11 <div onClick={this.show}>Click
Me!</div>
12
13
);
}
});
9 render() {
10 return(
11
12 <div>
13 Name: <input
type="text" ref={input =>
14
this.inputDemo = input} />
15
<button name="Click"
16 onClick={this.display}>Click</bu
tton>
17
18
<h2>Hello <span
id="disp"></span> !!!</h2>
</div>
);
}
}
26. List some of the cases when you should use Refs.
Following are the cases when refs should be used:
1 //ChildComponent.jsx
2 export default class
ChildComponent extends
3
React.Component {
4
render() {
5
return(
6
7
<div>
8
9
<h1>This is a child
10 component</h1>
11
12 </div>
13
14 );
15 }
16 }
17
18 //ParentComponent.jsx
19 import ChildComponent from
'./childcomponent.js';
20
class ParentComponent extends
21
React.Component {
22
render() {
23
return(
24
25
<div>
26
<App />
27
</div>
28
);
}
}
1 handleSubmit(event) {
2 alert('A name was submitted:
' + this.state.value);
3
event.preventDefault();
4
}
5
6
render() {
7
return (
8
9
<form
10
onSubmit={this.handleSubmit}>
11
<label>
12
Name:
13
<input
14 type="text"
value={this.state.value}
15
onChange={this.handleSubmit} />
16
</label>
17
<input type="submit"
18 value="Submit" />
</form>
);
}
their arguments.
In case you are facing any challenges with these React interview questions,
please comment on your problems in the section below.
3 type: ADD_TODO,
4 text
5 }
6 }
Flux Redux
1. The Store contains state and change logic 1. Store and change logic are separate
3. All the stores are disconnected and flat 3. Single store with hierarchical reducers
xxxvi. Just like how React is based on components, in React Router v4, the
API is ‘All About Components’. A Router can be visualized as a single root
component (<BrowserRouter>) in which we enclose the specific child
routes (<route>).
xxxvii. No need to manually set History value: In React Router v4, all we
need to do is wrap our routes within the <BrowserRouter> component.
xxxviii. The packages are split: Three packages one each for Web, Native and
Core. This supports the compact size of our application. It is easy to switch
over based on a similar coding style.
An uncontrolled component, on the other hand, maintains its own internal state
and updates it using DOM events. The component directly updates the DOM and
does not rely on the parent component to pass and update the state.
Handling forms in React can be done in a few different ways, but the most
common approach is to create a controlled component for the form and its
inputs. A controlled component is a component that has its state controlled by
the parent component. The parent component passes the state as props to the
controlled component and also handles any changes to the state via callback
functions.
Here is an example of how to handle a simple form with two input fields
(username and password) in a controlled component:
22. First, define the initial state of the form in the parent component’s
constructor. For example:
1 </pre>
2 constructor(props) {
3 super(props);
4 this.state = {
5 username: '' ,
6 password: '',
7 };
8 }
9 <pre>
23. Next, create callback functions for each input field that updates the
corresponding state property when the input value changes. For example:
1 </span>
2 handleUsernameChange = (event) =
3 this.setState({username:
event.target.value});
4
}
5
handlePasswordChange = (event) => {
6
this.setState({password:
7
event.target.value});
}
2 username={this.state.username}
3 password={this.state.password}
4 handleUsernameChange={this.handleUs
ernameChange}
5
handlePasswordChange={this.handlePa
6
sswordChange}
/>
24. In the controlled form component, use the passed-in props to set the
value and onChange attributes of each input field. For example:
1 <input
2 type="text"
3 value={props.username}
4 onChange={props.handleUsernameChang
e}
5
6 />
7 <input
8 type="password"
9 value={props.password}
10 onChange={props.handlePasswordChang
e}
/>
25. Finally, in the parent component’s form submit callback function, you can
access the form data from the component’s state and handle the form
submission as necessary.
Alternatively, you can use third-party libraries such as Formik, or the new hooks
in react, useState and useEffect, to handle forms in a more efficient way.
It’s important to note that when you are creating forms in React, you should also
validate the input values, and display appropriate error messages to users.
For example, you could have a route for the homepage that maps to a “Home”
component and a route for a user’s profile that maps to a “Profile” component.
When the user navigates to the “/” route, the Home component would be
displayed, and when they navigate to the “/profile” route, the Profile component
would be displayed.
To use React Router in a React application, you’ll need to install it, import it into
your application, and define your routes and the components they map to.
Here’s an example of how you might set up React Router in a simple React
application:
1 import { BrowserRouter as Router,
Route } from "react-router-dom";
2
import Home from
3
“./components/Home";
4
import profile from
5 “./components/Profile”;
6 function App() {
7 return (
8 <Router>
</Router>
);
}
In this example, the Router component is used to wrap the entire application
and the Route component is used to define the specific routes and the
components they map to. The exact prop is used to ensure that only the exact
path is matched and not any subpaths.
56. Explain the difference between server-side rendering and client-side
rendering in React.
In a React application, there are two main ways to render the components:
server-side rendering (SSR) and client-side rendering (CSR).
Faster time-to-first-byte
In general, CSR is the simpler option to implement and more popular, but SSR is
a good choice for certain use cases, such as when SEO is a primary concern, or
when the app is targeting users on slow internet connections.
It is also worth noting that, it is possible to have a hybrid approach between SSR
and CSR which is called isomorphic or universal rendering. This approach allows
to leverage the benefits of both SSR and CSR.
Which one to use depends on your specific use case and requirements.
There are several techniques that can be used to optimize a large React
application:
Use the React Developer Tools to identify and fix performance bottlenecks. The
React Developer Tools allow you to track the performance of individual
components and identify which components are causing the most re-renders.
Use the useEffect hook to handle side effects. This hook allows you to run side
effects, such as network requests, after a component has rendered.
Use the useMemo hook to memoize expensive calculations. This hook allows
you to cache the results of expensive calculations and only recalculate them
when the inputs have changed.
Lazy loading: Lazy loading is a technique where you only load the components
that are needed for the current view. This can greatly improve the performance
of your application.
Code splitting: Code splitting is a technique where you split your application into
smaller chunks of code that are loaded on demand. This can greatly improve the
performance of your application.
Optimize the loading time of your application by using techniques like code
minification, compression, and caching.
The combineReducers function is also useful for structuring and organizing your
code in a more modular way, as it allows you to separate the logic for different
parts of the state into different files and functions.
React Testing Library is a great tool for testing React components. It’s a set of
helpers that let you test React components without relying on their
implementation details. This approach makes refactoring a breeze and also
nudges you towards best practices for accessibility. With components, the
distinction between a “unit” and “integration” test can be blurry. If you’re testing
a form, should its test also test the buttons inside of it? Or should a button
component have its own test suite? Should refactoring a button ever break the
form test? Jest is a JavaScript test runner that lets you access the DOM via jsdom,
which is an approximation of how the browser works. Jest provides a great
iteration speed combined with powerful features like mocking modules and
timers so you can have more control over how the code executes. It’s a great
tool for running tests on React apps. You can also use a tool like BrowserStack’s
Real Device Cloud to run end-to-end tests on real devices. Cross browser
compatibility testing can also be done with a tool like BrowserStack Live.
66. What are the different ways to pass data between components in
React?
The components that require the data are served by the Provider, and the
components that need to access the data are served by the Consumer. Data that
is local to a component can be stored in a state, which allows for the tracking of
data across time. Through the useState Hook, state in a component can be
obtained. The current state value and a function to update the state value are
the two items of an array that the useState Hook returns after receiving an initial
value.
A React component can be rendered outside of the DOM hierarchy of its parent
component using React Portals. As an example, you could render components in
a modal dialogue box, hover card, loader, or popup message, which would be in
a “different place” than their parent component. The ReactDOM.createPortal()
method, which accepts a React element (child) and a DOM element as inputs, is
used to create React portals (container). The container is the DOM element that
the child component should be rendered into, and the child component is any
renderable React child, such as an element, string, or fragment. For items that
must appear above all other elements, such as profile hovercards, modal
dialogue boxes, and tooltips, portals are frequently utilised.
One key difference between the two is that a class component can have local
state and lifecycle methods, while a functional component cannot. However,
starting with React 16.8, functional components can also have a state using
hooks.
A component that needs to access the context data can consume it by using the
useContext hook or the Consumer component. To make the context available to
a component, a parent component needs to provide it using the Provider
component.
It should be noted that context should be used sparingly, as it can make your
components more difficult to reason about and test. If possible, it’s better to
pass props down the component tree manually.
One popular way to handle async data loading is to use the useEffect hook in
combination with fetch or a library like axios to load data in a component after it
has been rendered. The useEffect hook allows you to synchronize a component
with an external system, such as a server, by running a side effect (the data
loading) after the component has rendered. The hook takes a callback function
that contains the effect, and an array of dependencies.
In either case, it’s important to keep an eye on the component’s state and
update it properly with the loaded data.
14 setData(json);
15 setLoading(false);
16 } catch (error) {
17 setError(error) {
18 setLoading(fase);
19 }
20 }
21 fetchData();
22 }, []);
if (loading) {
return <p>Loading...</p>;
1 if (error) {
2 return <p>Error:
{error.message}</p>;
3
}
4
return <p>Data:
5
{JSON.stringify(data)}</p>;
}
“Hooks are a new feature in React that allows us to add state and other React
features to functional components. They were introduced in React 16.8 and have
since become a popular way to manage state and side effects in functional
components. Hooks are named functions that start with the word use and allow
us to reuse stateful logic across components without having to write a class
component. For example, the useState Hook allows us to add state to a
functional component and the useEffect Hook lets us perform side effects like
data fetching or updating the document title. Hooks make our code more
reusable, easier to understand, and easier to test.”
To use react-i18next in your React application, you would install it using npm
and then configure it in your index.js file. After that, you can use the
useTranslation Hook to access the translations in your components.
2 return <h1>Hello,
{props.name}</h1>;
3
}
32. Setting up your server to handle incoming requests and render the
appropriate components.
33. Rendering the components on the server using
ReactDOMServer.renderToString or
ReactDOMServer.renderToStaticMarkup.
34. Sending the resulting HTML to the client as part of the response.
35. Hydrating the components on the client so that they can be interactively
controlled by the user.
It’s worth noting that SSR comes with some trade-offs and additional complexity,
so it’s important to carefully consider whether it’s the right choice for your
application.
The separation of concerns between the two types of components allows for
better code organization, maintenance, and testing.
A Custom Hook in React is a JavaScript function that lets you extract state logic
and behavior out of a component, and reuse it across multiple components.
Custom Hooks allow you to abstract away state and behavior that is common
across your application into a reusable piece of code.
Custom Hooks are named with the prefix use (e.g. useForm, useFetch), and can
call other Hooks as well as your own custom Hooks. They have the same rules as
Hooks and can only be called at the top level of your component or your own
custom Hooks.
Custom Hooks can receive arguments and return values, just like a regular
function, but they also have the ability to manage state and perform side-effects.
By abstracting state and behavior into a Custom Hook, you can improve the
readability and maintainability of your code.
• Data fetching
• Managing state updates
• Handling form submissions
• Implementing animations and transitions
• And many more.
Using Custom Hooks can make your components cleaner, more reusable, and
easier to test, which makes them a powerful tool in your React toolkit.
36. Semantic HTML: Use semantic HTML elements, such as <button>, <nav>,
and <header>, to clearly define the structure and purpose of your
content.
37. Accessible Props: Use accessible props, such as aria-label, role, and
tabIndex, to provide additional information to assistive technologies, such
as screen readers.
38. Keyboard Navigation: Ensure that all functionality can be accessed using a
keyboard, and that keyboard focus is managed correctly.
39. Color Contrast: Make sure that the contrast between the text and the
background is high enough to be readable by people with color blindness
or low vision.
40. Alternative Text: Provide alternative text for images, videos, and other
non-text elements to ensure that information is accessible to screen
reader users.
41. Screen Reader Testing: Test your application with screen readers and
other assistive technologies to identify and fix any accessibility issues.
In Redux, a reducer and an action are two different but related concepts.
An action is a plain JavaScript object that describes the change that should be
made to the state of the application. It has a type property that defines the type
of action being performed, and a payload property that provides any additional
data needed to perform the action. Actions are dispatched from the application
to the Redux store, which then passes the action to the reducers.
A reducer is a pure function that takes the current state of the application and
an action, and returns the next state of the application. The reducer is
responsible for handling the actions and updating the state accordingly. It
should not perform any side-effects, such as making API calls, but should instead
only return the next state.
In summary, actions describe what should change, while reducers define how
the state should change in response to the actions.
82. Explain the concept of a Higher Order Component (HOC) in React and
when to use it.
Examples of HOCs include the withRouter HOC from react-router and the
connect HOC from react-redux.
42. PropTypes: React provides a built-in library called PropTypes that allows
you to specify the expected data types for your component’s props.
PropTypes will validate the props passed to your component at runtime,
and will log warnings in the browser console if any props are of the wrong
type.
43. Custom validation functions: You can write custom validation functions to
check the validity of your data. These functions can be called inside your
component, and can be used to set error messages or update the state to
indicate invalid data.
44. Third-party libraries: There are several third-party libraries available for
data validation in React, such as yup, joi, or zod. These libraries provide a
more powerful and flexible way to validate data, and often provide a more
user-friendly way to report errors.
Regardless of the method you choose, it’s important to handle data validation in
your React application to ensure that the data being processed is in the correct
format and meets the required constraints. Validation helps to catch potential
errors early in the development process and prevent bugs from affecting the
end-user experience.
In Redux, an action is a plain JavaScript object that describes the change in the
state of the application. Actions can be either synchronous or asynchronous.
When a React component’s state changes, React updates the Virtual DOM,
instead of directly updating the actual DOM. This is more efficient because
updating the Virtual DOM is faster than updating the actual DOM, as it can
calculate the difference between the previous and current render output, and
only update the parts that have changed.
React then takes the updated Virtual DOM and uses it to update the actual DOM,
minimizing the amount of work that needs to be done in the actual DOM and
improving the overall performance of the application.
45. Polyfills: To support older browsers, you can use polyfills, which are
JavaScript libraries that emulate missing features in older browsers.
46. Browser detection: You can use libraries like browser-detect to detect the
user’s browser and its version, and adjust your code accordingly.
47. Feature detection: Instead of relying on browser detection, you can use
feature detection to check if a specific feature is supported by the user’s
browser before using it.
48. CSS Reset: You can use CSS resets like normalize.css to make sure that all
browsers display the styles in a consistent way.
49. Testing: Regular testing in different browsers and devices is essential to
catch any compatibility issues early in the development process.
By using these techniques, you can ensure that your React application runs
smoothly across different browsers and devices.
The key difference between the two is the way they manage and manipulate
data. Stateful components have their own internal state and are responsible for
managing and updating it, whereas stateless components simply receive data
via props and render it without any data manipulation.
Input validation: Validate all user inputs on the client and server side to prevent
any malicious data from being processed.
Regular security audits: Conduct regular security audits to identify and address
potential security issues in a timely manner.
In React, there are two main types of components: function components and
class components.
Class Components, on the other hand, are JavaScript classes that extend the
React.Component base class. They are used for creating components that have a
state, or need to access lifecycle methods such as componentDidMount or
shouldComponentUpdate. Class components are more complex than function
components, but provide more advanced features.
By using the Provider, you ensure that all of your components can subscribe to
the store and dispatch actions to modify its state. In other words, the Provider
acts as a bridge between your React components and your Redux store, making
the store accessible to all components in your application.
11 </div>
);
}
14 <Route path="/about"
component={About} />
</Suspense>
</div>
);
}
By using these approaches, you can effectively handle code splitting in a React
application and improve its performance by reducing the initial loading time and
only loading the required code on demand.
50. Code splitting: This allows you to split your code into smaller chunks that
can be loaded on demand, reducing the initial load time of your
application.
51. Lazy loading: Lazy loading allows you to load components only when they
are required, reducing the amount of code that needs to be loaded and
parsed at startup.
52. Use of a bundler such as Webpack: A bundler can help you optimize your
code by reducing the size of your JavaScript files, combining multiple files
into one, and more.
53. Use of caching: You can cache the data and components that are
frequently used in your application to avoid fetching the same data over
and over.
54. Use of efficient algorithms and data structures: In order to keep your
application fast, it’s important to use algorithms and data structures that
are optimized for performance.
55. Regular performance monitoring and profiling: Regular performance
monitoring and profiling can help you identify performance bottlenecks
and areas for improvement in your code.
56. Use of optimization techniques such as memoization: By using techniques
such as memoization, you can reduce the number of unnecessary re-
renders and computations in your application, improving its overall
performance.
A React element, on the other hand, is a plain JavaScript object that represents a
DOM node. It is an immutable representation of a DOM node, which can be
created using React.createElement or JSX.
There are several libraries and techniques that can be used to implement
internationalization in a React application, including:
2
3 import { FormattedMessage, useIntl
} from ‘react-intl';
4
function MyComponent() {
5
const intl = useintl();
6
return (
7
<div>
8
<p>
9
<FormattedMessage id="greeting"
10
defaultMessage="Hello, World!" />
11
</p>
12
<p>
13
{int1.formatDate(new Date(), {
14
weekday: 'long’,
15
year: ‘numeric’,
16
month: 'long’,
17
day: ‘numeric’,
18
})}
19
</p>
20
</div>
);
In this example, the useIntl hook is used to access the intl object, which provides
internationalization functions like formatDate. The FormattedMessage
component is used to display a localized message with the ID greeting.
99. What is the difference between a React component and a React class?
When asked about class components, you can highlight that they are defined as
JavaScript classes that extend the React.Component class, have a render
method, and can have additional lifecycle methods and state. You can also
provide a simple example to show your understanding of class components.
When asked about functional components, you can emphasize that they are
defined as plain JavaScript functions that return the component’s JSX markup,
and that they can use state and other React features with hooks. You can also
give an example to show how to write a functional component that achieves the
same functionality as a class component.
Finally, you can explain the trade-offs between class components and functional
components, such as that functional components are generally simpler and
easier to read, while class components offer more features and flexibility.
Showing your ability to weigh the pros and cons of each approach can
demonstrate your critical thinking skills and ability to write maintainable code.
For example, to handle a click event on a button, you would define a function in
your React component that updates the component’s state, and then attach that
function to the button as an onClick event handler.
1 class MyComponent extends
React.Component {
2
constructor(props) {
3
super(props);
4
this.state = {count: 0};
5
}
6
handleclick() {
7
8 this.setstate({count:
this.state.count + 1});
9
}
10
render() {
11
return (
12
<div>
13
<p>You clicked {this.state.count}
14
times</p>
15
<button onClick={() =>
16 this.handleClick()}>
17 Click me
18 </button>
</div>
);
}
In this example, when the button is clicked, the handleClick function is called and
the component’s state is updated. This causes a re-render of the component,
and the displayed count is updated accordingly.
Event handlers are a key part of React’s event handling system and are used to
add interactivity to your application.
Group_WPF _MVVVM
Group_VCPlusPlus_MFC
1. What are the different data types present in C++?
The 4 data types in C++ are given below:
i. Primitive Datatype (basic datatype). Example- char, short, int, float, long, double,
bool, etc.
ii. Derived datatype. Example- array, pointer, etc.
iii. Enumeration. Example- enum
iv. User-defined data types. Example- structure, class, etc.
2. What is the difference between C and C++?
The main difference between C and C++ are provided in the table below:
C C++
C is a procedure-oriented programming C++ is an object-oriented programming
language. language.
Data is hidden by encapsulation to ensure that
C does not support data hiding. data structures and operators are used as
intended.
C is a subset of C++ C++ is a superset of C.
Function and operator overloading are not Function and operator overloading is
supported in C supported in C++
Namespace is used by C++, which avoids
Namespace features are not present in C
name collisions.
Functions can not be defined inside structures. Functions can be defined inside structures.
calloc() and malloc() functions are used for new operator is used for memory allocation
memory allocation and free() function is used and deletes operator is used for memory
for memory deallocation. deallocation.
3. What are class and object in C++?
A class is a user-defined data type that has data members and member functions. Data members
are the data variables and member functions are the functions that are used to perform
operations on these variables.
An object is an instance of a class. Since a class is a user-defined data type so an object can
also be called a variable of that data type.
A class is defined as-
class A{
private:
int data;
public:
void fun(){
}
};
4. What is operator overloading?
Operator Overloading is a very essential element to perform the operations on user-defined
data types. By operator overloading we can modify the default meaning to the operators like +,
-, *, /, <=, etc.
For example -
The following code is for adding two complex number using operator overloading-
class complex{
private:
float r, i;
public:
complex(float r, float i){
this->r=r;
this->i=i;
}
complex(){}
void displaydata(){
cout<<”real part = “<<r<<endl;
cout<<”imaginary part = “<<i<<endl;
}
complex operator+(complex c){
return complex(r+c.r, i+c.i);
}
};
int main(){
complex a(2,3);
complex b(3,4);
complex c=a+b;
c.displaydata();
return 0;
}
5. What is polymorphism in C++?
Polymorphism in simple means having many forms. Its behavior is different in different
situations. And this occurs when we have multiple classes that are related to each other by
inheritance.
For example, think of a base class called a car that has a method called car brand(). Derived
classes of cars could be Mercedes, BMW, Audi - And they also have their own implementation
of a cars
The two types of polymorphism are:
i. Compile Time Polymorphism
ii. Runtime Polymorphism
6. Explain constructor?
The constructor is a member function that is executed automatically whenever an object is
created. Constructors have the same name as the class of which they are members so that
compiler knows that the member function is a constructor. And no return type is used for
constructors.
Example:
class A{
private:
int val;
public:
A(int x){ //one argument constructor
val=x;
}
A(){ //zero argument constructor
}
}
int main(){
A a(3);
return 0;
}
7. What is a virtual function?
Virtual function is a member function in the base class that you redefine in a derived class. A
virtual function is declared using the virtual keyword. When the function is made virtual, C++
determines which function is to be invoked at the runtime based on the type of the object
pointed by the base class pointer.
8. Compare compile time polymorphism and Runtime polymorphism.
The main difference between compile-time and runtime polymorphism is provided below:
=================================================================
===
20. What is a copy constructor?
A copy constructor is a member function that initializes an object using another object of the
same class.
Example-
class A{
int x,y;
A(int x, int y){
this->x=x;
this->y=y;
}
};
int main(){
A a1(2,3);
A a2 = a1; //default copy constructor is called
return 0;
}
We can define our copy constructor. If we don’t define a copy constructor then the default
copy constructor is called.
21. What is the difference between shallow copy and deep copy?
The difference between shallow copy and a deep copy is given below:
Shallow Copy Deep Copy
Deep copy makes a new and separate copy of
Shallow copy stores the references of objects
an entire object with its unique memory
to the original memory address.
address.
Shallow copy is faster. Deep copy is comparatively slower.
Shallow copy reflects changes made to the Deep copy doesn’t reflect changes made to
new/copied object in the original object. the new/copied object in the original object
22. What is the difference between virtual functions and pure virtual functions?
A virtual function is a member function in the base class that you redefine in a derived class. It
is declared using the virtual keyword.
Example-
class base{
public:
virtual void fun(){
}
};
A pure virtual function is a function that has no implementation and is declared by assigning
0. It has no body.
Example-
class base{
public:
virtual void fun()=0;
};
Here, = sign has got nothing to do with the assignment, and value 0 is not assigned to anything.
It is used to simply tell the compiler that a function will be pure and it will not have anybody.
23. If class D is derived from a base class B. When creating an object of type D in
what order would the constructors of these classes get called?
The derived class has two parts, a base part, and a derived part. When C++ constructs derived
objects, it does so in phases. First, the most-base class (at the top of the inheritance tree) is
constructed. Then each child class is constructed in order until the most-child class is
constructed last.
So the first Constructor of class B will be called and then the constructor of class D will be
called.
During the destruction exactly reverse order is followed. That is destructor starts at the most-
derived class and works its way down to base class.
So the first destructor of class D will be called and then the destructor of class B will be called.
24. Can we call a virtual function from a constructor?
Yes, we can call a virtual function from a constructor. But the behavior is a little different in
this case. When a virtual function is called, the virtual call is resolved at runtime. It is always
the member function of the current class that gets called. That is the virtual machine doesn’t
work within the constructor.
For example-
class base{
private:
int value;
public:
base(int x){
value=x;
}
virtual void fun(){
}
}
class derived{
private:
int a;
public:
derived(int x, int y):base(x){
base *b;
b=this;
b->fun(); //calls derived::fun()
}
void fun(){
cout<<”fun inside derived class”<<endl;
}
}
25. What are void pointers?
A void pointer is a pointer which is having no datatype associated with it. It can hold addresses
of any type.
For example-
void *ptr;
char *str;
p=str; // no error
str=p; // error because of type mismatch
We can assign a pointer of any type to a void pointer but the reverse is not true unless you
typecast it as
str=(char*) ptr;
26. What is this pointer in C++?
The member functions of every object have a pointer named this, which points to the object
itself. The value of this is set to the address of the object for which it is called. It can be used
to access the data in the object it points to.
Example
class A{
private:
int value;
public:
void setvalue(int x){
this->value=x;
}
};
int main(){
A a;
a.setvalue(5);
return 0;
}
27. How do you allocate and deallocate memory in C++?
The new operator is used for memory allocation and deletes operator is used for memory
deallocation in C++.
For example-
int value=new int; //allocates memory for storing 1 integer
delete value; // deallocates memory taken by
value
=================================================================
=
30. How are virtual functions different from pure virtual functions?
A virtual function is a base class member function that a derived class can modify. A member
function of a base class that is a pure virtual function must be defined in the derived type;
otherwise, the derived class will become abstract as well.
31. How would you deallocate and allocate memory in C++?
The heap is used in C to allocate dynamic memory, and these functions are part of the standard
library. malloc() and free are the two important dynamic memory operations (). The size of the
desired memory area in bytes is the only parameter accepted by the malloc() function.
#include <iostream>
#include <cstdlib>
#include <cstring>
int main() {
char *user;
cout << "User Name = " << user << " " << &user << endl;
free(user);
• ?: – conditional operator
• .* – dereferencing operator
• sizeof – sizeof operator
• :: – scope resolution operator
• . – Dot operator
• -> – member dereferencing operator
36. What do you understand about smart pointers in C++?
Smart pointers are employed in garbage collection to ensure no memory leaks. If you use smart
pointers, you need not call delete for any memory allocated dynamically as it is automatically
deallocated. You can implement smart pointers in C++11 and higher versions. C++11 has the
following four kinds of smart pointers:
• auto_ptr
• unique_ptr
• shared_ptr
• weak_ptr.
37. What is the role of this pointer and void pointer?
This pointer: The 'this pointer' is present in the member functions of every object. It points to
the object itself and can be used to access the object's data.
Void pointer: A pointer that has no data type associated with it is called a void pointer. You
can assign any type of pointer to a void pointer, but the reverse isn't true unless you use it as
follows
Void *ptr;
// reference variable
int& ref = GFG;
Calling a function by sending the values by Calling a function by sending the address
copying variables. of the passed variable.
The changes made in the function are never The changes made in the functions can be
reflected outside the function on the seen outside the function on the passed
variable. In short, the original value is function. In short, the original value is
never altered in Call by Value. altered in Call by reference.
Passed actual and formal parameters are Passed actual and formal parameters are
stored in different memory locations. stored in the same memory location.
Therefore, making Call by Value a little Therefore, making Call by Reference a
memory insufficient little more memory efficient.
Struct Class
Members of the struct are always by Members of the class can be in private,
default public mode protected, and public modes.
Structures are of the value type. They only Classes are of reference type. It holds a
hold value in memory. reference of an object in memory.
Reference Pointer
It can never hold a null value as it needs an It can hold or point at a null value and be
existing value to become an alias of termed as a nullptr or null pointer
45. What is the difference between function overloading and operator overloading?
Arrays Lists
While loop is also termed an entry- The do-while loop is termed an exit control
controlled loop loop
prefix postfix
It simply means putting the operator before It simply means putting the operator after
the operand the operand
new malloc()
50. What is the difference between virtual functions and pure virtual functions?
It is also termed static binding and early It is also termed Dynamic binding and Late
binding. binding.
delete[] delete
It is used for deleting a whole array It is used to delete only one single pointer
It is used for deleting the objects of new[]; It is used for deleting the objects of new;
By this, we can say that delete[] is used to By this, we can say that delete is used to
delete an array of objects delete a single object
Multiple Inheritances
delete [] GFG;
59. What do you know about friend class and friend function?
A friend class is a class that can access both the protected and private variables of the classes
where it is declared as a friend.
Example of friend class:
class Class_1st {
statements;
}
class Class_2nd {
statements;
A friend function is a function used to access the private, protected, and public data members
or member functions of other classes. It is declared with a friend keyword. The advantage of a
friend function is that it is not bound to the scope of the class and once it is declared in a class,
furthermore to that, it cannot be called by an object of the class; therefore it can be called by
other functions. Considering all the mentioned points we can say that a friend function is a
global function.
Example of friend function:
class GFG {
statements;
friend dataype
function_Name(arguments);
statements;
OR
class GFG{
statements'
friend int divide(10,5);
statements;
#include <iostream>
int fun(void)
return 0;
64. Define inline function. Can we have a recursive inline function in C++?
An inline function is a form of request not an order to a compiler which results in the inlining
of our function to the main function body. An inline function can become overhead if the
execution time of the function is less than the switching time from the caller function to called
function. To make a function inline use the keyword inline before and define the function
before any calls are made to the function.
Syntax:
inline data_type function_name()
{
Body;
}
The answer is No; It cannot be recursive.
An inline function cannot be recursive because in the case of an inline function the code is
merely placed into the position from where it is called and does not maintain a piece of
information on the stack which is necessary for recursion.
Plus, if you write an inline keyword in front of a recursive function, the compiler will
automatically ignore it because the inline is only taken as a suggestion by the compiler.
65. What is an abstract class and when do you use it?
An abstract class is a class that is specifically designed to be used as a base class. An abstract
class contains at least one pure virtual function. You declare a pure virtual function by using a
pure specifier(= 0) in the declaration of a virtual member function in the class declaration
You cannot use an abstract class as a parameter type, a function return type, or the type of an
explicit conversion, nor can you declare an object of an abstract class. However, it can be used
to declare pointers and references to an abstract class.
An abstract class is used if you want to provide a common, implemented functionality among
all the implementations of the component. Abstract classes will allow you to partially
implement your class, whereas interfaces would have no implementation for any members
whatsoever. In simple words, Abstract Classes are a good fit if you want to provide
implementation details to your children but don’t want to allow an instance of your class to be
directly instantiated.
66. What are the static data members and static member functions?
The static data member of a class is a normal data member but preceded with a static keyword.
It executes before main() in a program and is initialized to 0 when the first object of the class
is created. It is only visible to a defined class but its scope is of a lifetime.
Syntax:
static Data_Type Data_Member;
The static member function is the member function that is used to access other static data
members or other static member functions. It is also defined with a static keyword. We can
access the static member function using the class name or class objects.
Syntax:
classname::function name(parameter);
67. What is the main use of the keyword “Volatile”?
Just like its name, things can change suddenly and unexpectantly; So it is used to inform the
compiler that the value may change anytime. Also, the volatile keyword prevents the compiler
from performing optimization on the code. It was intended to be used when interfacing with
memory-mapped hardware, signal handlers, and machine code instruction.
68. Define storage class in C++.
Storage class is used to define the features(lifetime and visibility) of a variable or function.
These features usually help in tracing the existence of a variable during the runtime of a
program.
Syntax:
storage_class var_data_type var_name;
Some types of storage classes:
69. What is a mutable storage class specifier? How can they be used?
Just like its name, the mutable storage class specifier is used only on a class data member to
make it modifiable even though the member is part of an object declared as const. Static or
const, or reference members cannot use the mutable specifier. When we declare a function as
const, this pointer passed to the function becomes const.
70. Define the Block scope variable.
So the scope of a variable is a region where a variable is accessible. There are two scope
regions, A global and block or local.
A block scope variable is also known as a local scope variable. A variable that is defined inside
a function (like main) or inside a block (like loops and if blocks) is a local variable. It can be
used ONLY inside that particular function/block in which it is declared. a block-scoped
variable will not be available outside the block even if the block is inside a function.
71. What is the function of the keyword “auto”?
The auto keyword may be used to declare a variable with a complex type in a straightforward
fashion. You can use auto to declare a variable if the initialization phrase contains templates,
pointers to functions, references to members, etc. With type inference capabilities, we can
spend less time having to write out things the compiler already knows. As all the types are
deduced in the compiler phase only, the time for compilation increases slightly but it does not
affect the runtime of the program.
72. Define namespace in C++.
Namespaces enable us to organize named items that would otherwise have global scope into
smaller scopes, allowing us to give them namespace scope. This permits program parts to be
organized into distinct logical scopes with names. The namespace provides a place to define or
declare identifiers such as variables, methods, and classes.
Or we could say that A namespace is a declarative zone that gives the identifiers (names of
types, functions, variables, and so on) within it a scope. Namespaces are used to arrange code
into logical categories and to avoid name clashes, which might happen when you have many
libraries in your code base.
73. When is void return type used?
The void keyword, when used as a function return type, indicates that the function does not
return a value. When used as a parameter list for a function, void indicates that the function
takes no parameters. Non-Value Returning functions are also known as void functions. They’re
called “void” since they’re not designed to return anything. True, but only partially. We can’t
return values from void functions, but we can certainly return something. Although void
functions have no return type, they can return values.
74. What is ‘this‘ pointer in C++?
this pointer enables every object to have access to its own address through an essential pointer.
All member functions take this pointer as an implicit argument. this pointer may be used to
refer to the calling object within a member function.
• this pointer is used to pass an object as a parameter to another method.
• Each object gets its own copy of the data member.
• this pointer is used to declare indexers.
75. What is Data binding and Abstraction?
Data Binding: Data binding is the method of constructing a link between both the
application's user interface and the information it shows. If the binding has the correct
parameters and the information provides the appropriate notification, whenever the data has
changed its value, the components that are connected to it instantly adapt to the change.
Data Abstraction: Data abstraction is a process of reducing an enormous amount of
information to a simple representation of the whole. Abstraction is the process of diminishing
something to a set of basic characteristics by eliminating or subtracting characteristics.
}
};
A pure virtual function is one that has no implementation and is declared by setting the value
to 0. It doesn't have a body.
Example:
class base{
public:
virtual void fun()=0;
};
The value 0 is not allocated to anything, and the = sign has no bearing on the assignment. Its
sole purpose is to inform the compiler that a function will be pure and will not contain anyone.
82. What are void pointers?
A void pointer is a pointer that doesn't have a datatype attached to it. It may store any form of
address.
Example:
void *ptr;
char *str;
p=str; // no error
str=p; // error because of type mismatch
We can assign any type of pointer to a void pointer, but we can't do the opposite unless we
typecast it as void.
str=(char*) ptr;
83. How do you allocate and deallocate memory in C++?
In C++, the new operator is used to allocate memory, whereas the deletes operator is used to
deallocate memory.
Example:
int value=new int; //allocates memory for storing 1 integer
delete value; // deallocates memory taken by
value
int main(){
A *a=new B();
return 0;
}
SQL
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.
Primary key:
PRIMARY KEY constraint uniquely identifies each row in a table. It must
contain UNIQUE values and has an implicit NOT NULL constraint.
Foreign key: Foreign keys are the column of the table used to point to the
primary key of another table.
Composite key: Whenever a primary key consists of more than one attribute, it
is known as a composite key. This key is also known as Concatenated Key.
SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.
-- Unique Key
CREATE TABLE <table name>
(
column1 datatype Primary key Identity(<SeeValue>,<NextValue>),
column2 datatype Unique key (<column name>),
column3 datatype,
....
);
-- Foreign key
CREATE TABLE <table name>
(
column1 datatype Primary key Identity(<SeeValue>,<NextValue>),
column2 datatype Foreign key ,
column3 datatype,
....
);
-- Check
CREATE TABLE <table name>
(
column1 datatype Primary key Identity(< Seed Value>,<NextValue>),
column3 datatype CHECK (Column >=value),
....
);
-- Default
CREATE TABLE <table name>
(
column1 datatype Primary key Identity(<Seed Value>,<Next Value>),
column3 datatype DEFAULT value
....
);
-- To ALTER TABLE
ALTER TABLE table_name ALTER COLUMN column_name column_type;
Joins are used to combine rows from two or more tables, based on a related
column between them.
Types of Joins:
• INNER JOIN − Returns rows when there is a match in both tables.
• LEFT JOIN − Returns all rows from the left table, even if there are no
matches in the right table.
• RIGHT JOIN − Returns all rows from the right table, even if there are no
matches in the left table.
• FULL OUTER JOIN − Returns rows when there is a match in one of the
tables.
• SELF JOIN − Used to join a table to itself as if the table were two tables,
temporarily renaming at least one table in the SQL statement.
• CARTESIAN JOIN (CROSS JOIN) − Returns the Cartesian product of the
sets of records from the two or more joined tables.
Inner Join – it returns the rows if there is at least one match in two tables.
Left Join – returns all the rows from the left table even if there is no match in the
right table.
Syntax:
1 SELECT ColumnList from LeftTable
2 L
3 LEFT join RightTable R
4 ON L.Column=R.Column
Where R.Column is NULL
Right Join – returns all the rows from the right table even if no matches exist in
the left table.
Self Join : A SQL Self join is a mechanism of joining a table to itself. You would
use a self join when you wanted to create a result set joining records in the table
with some other records from the same table.
Difference between keys and Constraints?
Constraints:
SQL constraints are used to specify rules for the data in a table. If there is
any violation between the constraint and the data action, the action is aborted.
Constraints can be specified when the table is created (inside the CREATE
TABLE statement) or after the table is created (inside the ALTER TABLE
statement).
Let’s look at the different types of constraints which are present in SQL:
Constraint Description
Ensures that a column cannot have a
NOT NULL
NULL value.
Provides a default value for a column
DEFAULT
when none is specified.
Ensures that all the values in a
UNIQUE
column are different
Uniquely identifies each row/record
PRIMARY
in a database table
Uniquely identifies a row/record in
FOREIGN
any another database table
The CHECK constraint ensures that
CHECK all values in a column satisfy certain
conditions.
Used to create and retrieve data from
INDEX
the database very quickly.
What is the primary key?
Ans. A foreign key (often called the referencing key) is used to link two tables
together. It is a column or a combination of columns whose values match a
Primary Key in a different table. It acts as a cross-reference between tables
because it references the primary key of another table and established a link
between them.
Ans. A unique key is a set of one or more than one field/column of a table that
uniquely identifies a record in a database table. A primary key is a special kind
of unique key.
One-to-one :
One-to-many :
Any single rows of the first table can be related to one or more rows of the
second tables,
Many-to-many:
-- 1 to 1 relation
CREATE TABLE Employee (
ID int PRIMARY KEY,
Name VARCHAR(50)
);
Query Syntax:
--SELECT <select_criteria>
--[;]
--<select_criteria> ::=
-- [ TOP ( top_expression ) ]
-- [ ALL | DISTINCT ]
-- { * | column_name | expression } [ ,...n ]
-- [ FROM { table_source } [ ,...n ] ]
-- [ WHERE <search_condition> ]
-- [ GROUP BY <group_by_clause> ]
-- [ HAVING <search_condition> ]
-- [ ORDER BY <order_by_expression> ]
-- [ OPTION ( <query_option> [ ,...n ] ) ]
Delete : It removes the pointer to that table about particular Tuple then it is
rollback the data. If there are Identity column in a table, then it will start from
the next records it set the next identity value is a table.
Syntax:
DELETE FROM table_name WHERE condition;
Truncate: It is used to delete all the rows from the table and free the space
containing the table.
Order By in SQL
SQL Order By is used to sort the data in ascending or descending order. It sorts
the data in ascending order by default. To sort the data in descending order we
use the DESC keyword.
GROUP BY:
Syntax:
SELECT column1, column2, ..., aggregate_function(column)
FROM table
WHERE conditions
GROUP BY column1, column2, …
When the GROUP BY clause is used, the result set is divided into groups based
on the columns specified.
How to find:
l. duplicate records with one field.
li. duplicate records with more than one field.
SELECT COUNT(field)
FROM table_name
GROUP BY field
FROM table_name
GROUP BY field1,field2,field3
HAVING COUNT(*) > 1
Ans. This is one of the most commonly asked SQL interview questions. The
difference between TRUNCATE and DELETE are:
DELETE TRUNCATE
Delete command is used to delete a Truncate is used to delete all the rows
specified row in a table. from a table.
You can roll back data after using the
You cannot roll back data.
delete statement.
It is a DML command. It is a DDL command.
It is faster.
It is slower than a truncate statement.
Ans. The first syntax will not work because NULL means ‘no value’, and you
cannot use scalar value operators. This is why there is a separate IS – a NULL
predicate in SQL.
Select * From TableName Where Exists in (Select <column name> From table
name <alias> Where Tablename.FiledName = TableName.FieldName )
Ans: d
2) Which of the following provides the ability to query information from the database and
insert tuples into, delete tuples from, and modify tuples in the database?
4) Which of the following is generally used for performing tasks like creating the structure of
the relations, deleting relation?
5) Which of the following provides the ability to query information from the database
and insert tuples into, delete tuples from, and modify tuples in the database?
Answer : A
7) Which one of the following given statements possibly contains the error?
a. select * from emp where empid = 10003;
b. select empid from emp where empid = 10006;
c. select empid from emp;
d. select empid where empid = 1009 and Lastname = 'GELLER';
Answer : D
In the above-given Query, which of the following can be placed in the Query's blank portion
to select the "dept_name" that also contains Computer Science as its ending strings?
a. &
b. _
c. %
d. $
Answer : C
Answer : D
11) In case of any shut down during transaction before commit which of the following
statement is done automatically ?
A. View
B. Commit
C. Rollback
Answer C
Answer : D
13) Which one of the following commands is used for removing (or deleting) a relation forms
the SQL database?
a. Delete
b. Drop
c. Remove
d. All of the above
Answer D
14) Which of the following makes the transaction permanent in the database ?
A. View
B. Commit
C. Rollback
Answer B
15) In order to undo the work of transaction after last commit which one
should be used ?
A. View
B. Commit
C. Rollback
Answer C
16) Which of the following deletes all tuples in the instructor relation for those instructors
associated with a department located in the Watson building which is in department relation.
Answer : A
18) The given Query can be replaced with ____________:
SELECT name
FROM instructor1
WHERE salary <= 100000 AND salary >= 90000;
a) SELECT name
FROM instructor1
WHERE salary BETWEEN 100000 AND 90000
b) SELECT name
FROM instructor|
WHERE salary BETWEEN 90000 AND 100000;
c) SELECT name
FROM instructor!
WHERE salary <= 90000 AND salary>=100000;
Answer C
19) Wrie a query to find out the Total Count and Max Salary and Min Salary.
Emp
EmpID EmpName Salary
100 Paul 2000
200 Greg 4000
300 Ram 600
400 Shyam 6500
500 Ravi 8000
a) 10,10,2000
b) 5, 5, 4000
c) 8, 600, 2000
d) 5, 8000, 600
Answer: D
Answer : D
21) Create table LTable table (EmpID int)
Insert into LTable
Select 1
Union All
Select 1
Union All
Select 1
a) 3
b) 6
c) 12
d) 9
Answer : D
23)
Create table TblL (EmpID int)
Insert into TblL
Select 100
UNION ALL
Select 200
UNION ALL
Select 300
a) Equal No of records
b) Not Equal no of records
c) None of the above
Ans b
24) Char is a ______ length data type and varchar is a ____ data type
a) Fixed Length
b) Variable, Fixed
c) Variable, Variable
d) Fixed , Fixed
Answer : B
Set 2
1. From the following tables, write a SQL query to find the information on each salesperson
of ABC Company. Return name, city, country and state of each salesperson.
Input:
table: salespersons
salesperson_id|first_name|last_name|
--------------|----------|---------|
1|Green |Wright |
2|Jones |Collins |
3|Bryant |Davis |
table: address
address_id|salesperson_id|city |state |country|
----------|--------------|-----------|----------|-------|
1| 2|Los Angeles|California|USA |
2| 3|Denver |Colorado |USA |
3| 4|Atlanta |Georgia |USA |
Output:
first_name|last_name|city |state |
----------|---------|-----------|----------|
Jones |Collins |Los Angeles|California|
Bryant |Davis |Denver |Colorado |
Green |Wright | | |
2. From the following table, write a SQL query to find the third highest sale. Return sale
amount.
Input:
table: salemast
sale_id|employee_id|sale_date |sale_amt|
-------|-----------|----------|--------|
1| 1000|2012-03-08| 4500|
2| 1001|2012-03-09| 5500|
3| 1003|2012-04-10| 3500|
3| 1003|2012-04-10| 2500|
Output:
SecondHighestSale|
-----------------|
4500|
3. From the following table, write a SQL query to find the Nth highest sale. Return sale
amount.
Input:
table: salemast
sale_id|employee_id|sale_date |sale_amt|
-------|-----------|----------|--------|
1| 1000|2012-03-08| 4500|
2| 1001|2012-03-09| 5500|
3| 1003|2012-04-10| 3500|
Output:
getNthHighestSaleAmt(3)|
-----------------------|
3500|
4. From the following table, write a SQL query to find the marks, which appear at least thrice
one after another without interruption. Return the number.
Input:
table: logs
student_id|marks|
----------|-----|
101| 83|
102| 79|
103| 83|
104| 83|
105| 83|
106| 79|
107| 79|
108| 83|
Output:
ConsecutiveNums|
---------------|
83|
5. From the following table, write a SQL query to find all the duplicate emails (no upper case
letters) of the employees. Return email id.
Input:
table: employees
employee_id|employee_name|email_id |
-----------|-------------|-------------|
101|Liam Alton |li.al@abc.com|
102|Josh Day |jo.da@abc.com|
103|Sean Mann |se.ma@abc.com|
104|Evan Blake |ev.bl@abc.com|
105|Toby Scott |jo.da@abc.com|
Output:
email_id |
-------------|
jo.da@abc.com|
6. From the following tables, write a SQL query to find those customers who never ordered
anything. Return customer name.
Input:
table: customers
customer_id|customer_name|
-----------|-------------|
101|Liam |
102|Josh |
103|Sean |
104|Evan |
105|Toby |
table: orders
order_id|customer_id|order_date|order_amount|
--------|-----------|----------|------------|
401| 103|2012-03-08| 4500|
402| 101|2012-09-15| 3650|
403| 102|2012-06-27| 4800|
Output:
Customers|
---------|
Evan |
Toby |
7. From the following table, write a SQL query to remove all the duplicate emails of
employees keeping the unique email with the lowest employee id. Return employee id and
unique emails.
Input:
table: employees
employee_id|employee_name|email_id |
-----------|-------------|-------------|
101|Liam Alton |li.al@abc.com|
102|Josh Day |jo.da@abc.com|
103|Sean Mann |se.ma@abc.com|
104|Evan Blake |ev.bl@abc.com|
105|Toby Scott |jo.da@abc.com|
Output:
employee_id|employee_name|email_id |
-----------|-------------|-------------|
101|Liam Alton |li.al@abc.com|
102|Josh Day |jo.da@abc.com|
103|Sean Mann |se.ma@abc.com|
104|Evan Blake |ev.bl@abc.com|
8. From the following table, write a SQL query to find all dates' city ID with higher pollution
compared to its previous dates (yesterday). Return city ID, date and pollution.
Input:
table: so2_pollution
city_id|date |so2_amt|
-------|----------|-------|
701|2015-10-15| 5|
702|2015-10-16| 7|
703|2015-10-17| 9|
704|2018-10-18| 15|
705|2015-10-19| 14|
Output:
City ID|
-------|
702|
703|
9. A salesperson is a person whose job is to sell products or services.
From the following tables, write a SQL query to find the top 10 salesperson that have made
highest sale. Return their names and total sale amount.
Input:
Table: sales
TRANSACTION_ID|SALESMAN_ID|SALE_AMOUNT|
--------------|-----------|-----------|
501| 18| 5200.00|
502| 50| 5566.00|
503| 38| 8400.00|
...
599| 24| 16745.00|
600| 12| 14900.00|
Table: salesman
SALESMAN_ID|SALESMAN_NAME |
-----------|---------------------|
11|Jonathan Goodwin |
12|Adam Hughes |
13|Mark Davenport |
....
59|Cleveland Hart |
60|Marion Gregory |
Output:
salesman_name |total_sale|
---------------------|----------|
Dan McKee | 70530.00|
Cleveland Klein | 61020.00|
Elliot Clapham | 60519.00|
Evan Blake | 53108.00|
Ollie Wheatley | 52640.00|
Frederick Kelsey | 52270.00|
Sean Mann | 52053.00|
Callum Bing | 48645.00|
Kian Wordsworth | 45250.00|
Bradley Wright | 41961.00|
10. An active customer is simply someone who has bought company's product once before
and has returned to make another purchase within 10 days.
From the following table, write a SQL query to identify the active customers. Show the list of
customer IDs of active customers.
Input:
Table: orders
ORDER_ID|CUSTOMER_ID|ITEM_DESC|ORDER_DATE|
--------|-----------|---------|----------|
101| 2109|juice |2020-03-03|
102| 2139|chocolate|2019-03-18|
103| 2120|juice |2019-03-18|
...
199| 2130|juice |2019-03-16|
200| 2117|cake |2021-03-10|
Output:
customer_id|
-----------|
2103|
2110|
2111|
2112|
2129|
2130|
11. From the following table, write a SQL query to convert negative numbers to positive and
vice verse. Return the number.
Input:
Table name: tablefortest
srno|pos_neg_val|
----|-----------|
1| 56|
2| -74|
3| 15|
4| -51|
5| -9|
6| 32|
Output:
srno|pos_neg_val|converted_signed_value|
----|-----------|----------------------|
1| 56| -56|
2| -74| 74|
3| 15| -15|
4| -51| 51|
5| -9| 9|
6| 32| -32|
12. From the following table, write a SQL query to find the century of a given date. Return
the century.
Input:
Table name: tablefortest
ID|date_of_birth|
--|-------------|
1| 1907-08-15|
2| 1883-06-27|
3| 1900-01-01|
4| 1901-01-01|
5| 2005-09-01|
6| 1775-11-23|
7| 1800-01-01|
Output:
id|date_of_birth|Century|
--|-------------|-------|
1| 1907-08-15| 20 |
2| 1883-06-27| 19 |
3| 1900-01-01| 19 |
4| 1901-01-01| 20 |
5| 2005-09-01| 21 |
6| 1775-11-23| 18 |
7| 1800-01-01| 18 |
13. From the following table, write a SQL query to find the even or odd values. Return
"Even" for even number and "Odd" for odd number.
Input:
Table name: tablefortest
srno|col_val|
----|-------|
1| 56|
2| 74|
3| 15|
4| 51|
5| 9|
6| 32|
Output:
srno|col_val|Even_Odd|
----|-------|--------|
1| 56|Even |
2| 74|Even |
3| 15|Odd |
4| 51|Odd |
5| 9|Odd |
6| 32|Even |
14. From the following table, write a SQL query to find the unique marks. Return the unique
marks.
Input:
Table name: student_test
student_id|marks_achieved|
----------|--------------|
1| 56|
2| 74|
3| 15|
4| 74|
5| 89|
6| 56|
7| 93|
Output:
Unique Marks|
------------|
56|
74|
15|
89|
93|
15. From the following table, write a SQL query to find those students who have referred by
the teacher whose id not equal to 602. Return the student names.
Input:
Table Name: students
student_id|student_name|teacher_id|
----------|------------|----------|
1001|Alex | 601|
1002|Jhon | |
1003|Peter | |
1004|Minto | 604|
1005|Crage | |
1006|Chang | 601|
1007|Philip | 602|
Output:
student_name|
------------|
Alex |
Jhon |
Peter |
Minto |
Crage |
Chang |
16. From the following table, write a SQL query to find the order_id(s) that was executed by
the maximum number of salespersons.
If there are, more than one order_id(s) executed by the maximum number of salespersons
find all the order_id(s). Return order_id.
Input:
Table Name: salemast
salesperson_id|order_id|
--------------|--------|
5001| 1001|
5002| 1002|
5003| 1002|
5004| 1002|
5005| 1003|
5006| 1004|
5007| 1004|
5008| 1004|
Output:
order_id|
--------|
1002|
1004|
17. A city is big if it has an area bigger than 50K square km or a population of more than 15
million.
From the following table, write a SQL query to find big cities name, population and area.
Input:
Table : cities_test
city_name |country |city_population|city_area|
-------------|-------------|---------------|---------|
Tokyo |Japan | 13515271| 2191|
Delhi |India | 16753235| 1484|
Shanghai |China | 24870895| 6341|
Sao Paulo |Brazil | 12252023| 1521|
Mexico City |Mexico | 9209944| 1485|
Cairo |Egypt | 9500000| 3085|
Mumbai |India | 12478447| 603|
Beijing |China | 21893095| 16411|
Osaka |Japan | 2725006| 225|
New York |United States| 8398748| 786|
Buenos Aires |Argentina | 3054300| 203|
Chongqing |China | 32054159| 82403|
Istanbul |Turkey | 15519267| 5196|
Kolkata |India | 4496694| 205|
Manila |Philippines | 1780148| 43|
Output:
city_name |country |city_population|city_area|
------------|--------|---------------|---------|
Delhi |India | 16753235| 1484|
Shanghai |China | 24870895| 6341|
Beijing |China | 21893095| 16411|
Chongqing |China | 32054159| 82403|
Istanbul |Turkey | 15519267| 5196|
18. From the following table, write a SQL query to find those items, which have ordered 5 or
more times. Return item name and number of orders.
Input:
Table: orders
ORDER_ID|CUSTOMER_ID|ITEM_DESC|
--------|-----------|---------|
101| 2109|juice |
102| 2139|chocolate|
103| 2120|juice |
104| 2108|cookies |
105| 2130|juice |
106| 2103|cake |
107| 2122|cookies |
108| 2125|cake |
109| 2139|cake |
110| 2141|cookies |
111| 2116|cake |
112| 2128|cake |
113| 2146|chocolate|
114| 2119|cookies |
115| 2142|cake |
Output:
item_desc|Number of orders|
---------|----------------|
cake | 6|
19. From the following tables, write a SQL query to find the overall rate of execution of
orders, which is the number of orders execution divided by the number of orders quote.
Return rate_of_execution rounded to 2 decimals places.
Input:
Table: orders_issued
distributor_id|company_id|quotation_date|
--------------|----------|--------------|
101| 202| 2019-11-15|
101| 203| 2019-11-15|
101| 204| 2019-11-15|
102| 202| 2019-11-16|
102| 201| 2019-11-15|
103| 203| 2019-11-17|
103| 202| 2019-11-17|
104| 203| 2019-11-18|
104| 204| 2019-11-18|
Table: orders_executed
orders_from|executed_from|executed_date|
-----------|-------------|-------------|
101| 202| 2019-11-17|
101| 203| 2019-11-17|
102| 202| 2019-11-17|
103| 203| 2019-11-18|
103| 202| 2019-11-19|
104| 203| 2019-11-20|
Output:
rate_of_execution|
-----------------|
0.67|
20. From the following table write an SQL query to display the records with four or more
rows with consecutive match_no's, and the crowd attended more than or equal to 50000 for
each match. Return match_no, match_date and audience. Order the result by visit_date,
descending.
Input:
table : match_crowd
match_no|match_date|audience|
--------|----------|--------|
1|2016-06-11| 75113|
2|2016-06-12| 62343|
3|2016-06-13| 43035|
4|2016-06-14| 55408|
5|2016-06-15| 38742|
6|2016-06-16| 63670|
7|2016-06-17| 73648|
8|2016-06-18| 52409|
9|2016-06-19| 67291|
10|2016-06-20| 49752|
11|2016-06-21| 28840|
12|2016-06-22| 32836|
13|2016-06-23| 44268|
Output:
match_no|match_date|audience|
--------|----------|--------|
6|2016-06-16| 63670|
7|2016-06-17| 73648|
8|2016-06-18| 52409|
9|2016-06-19| 67291|
21. From the following table write a SQL query to know the availability of the doctor for
consecutive 2 or more days. Return visiting days.
Input:
Table: dr_clinic
visiting_date|availability|
-------------|------------|
2016-06-11| 1|
2016-06-12| 1|
2016-06-13| 0|
2016-06-14| 1|
2016-06-15| 0|
2016-06-16| 0|
2016-06-17| 1|
2016-06-18| 1|
2016-06-19| 1|
2016-06-20| 1|
2016-06-21| 1|
Output:
visiting_date|
-------------|
2016-06-11|
2016-06-12|
2016-06-17|
2016-06-18|
2016-06-19|
2016-06-20|
2016-06-21|
22. From the following tables find those customers who did not make any order to the
supplier 'DCX LTD'. Return customers name.
Input:
Table: customers
customer_id|customer_name|customer_city|avg_profit|
-----------|-------------|-------------|----------|
101|Liam |New York | 25000|
102|Josh |Atlanta | 22000|
103|Sean |New York | 27000|
104|Evan |Toronto | 15000|
105|Toby |Dallas | 20000|
Table : supplier
supplier_id|supplier_name|supplier_city|
-----------|-------------|-------------|
501|ABC INC |Dallas |
502|DCX LTD |Atlanta |
503|PUC ENT |New York |
504|JCR INC |Toronto |
Table: orders
order_id|customer_id|supplier_id|order_date|order_amount|
--------|-----------|-----------|----------|------------|
401| 103| 501|2012-03-08| 4500|
402| 101| 503|2012-09-15| 3650|
403| 102| 503|2012-06-27| 4800|
404| 104| 502|2012-06-17| 5600|
405| 104| 504|2012-06-22| 6000|
406| 105| 502|2012-06-25| 5600|
Output:
customer_name|
-------------|
Liam |
Josh |
Sean |
----------------------
23. Table students contain marks of mathematics for several students in a class. It may same
marks for more than one student.
From the following table write a SQL table to find the highest unique marks a student
achieved. Return the marks.
Table: students
student_id|student_name|marks_achieved|
----------|------------|--------------|
1|Alex | 87|
2|Jhon | 92|
3|Pain | 83|
4|Danny | 87|
5|Paul | 92|
6|Rex | 89|
7|Philip | 87|
8|Josh | 83|
9|Evan | 92|
10|Larry | 87|
Output:
marks|
-----|
89|
24. In a hostel, each room contains two beds. After every 6 months a student have to change
their bed with his or her room-mate.
From the following tables write a SQL query to find the new beds of the students in the
hostel. Return original_bed_id, student_name, bed_id and student_new.
Table : bed_info
bed_id|student_name|
------|------------|
101|Alex |
102|Jhon |
103|Pain |
104|Danny |
105|Paul |
106|Rex |
107|Philip |
108|Josh |
109|Evan |
110|Green |
Output:
original_bed_id|student_name|bed_id|student_new|
---------------|------------|------|-----------|
102|Jhon | 101|Jhon |
101|Alex | 102|Alex |
104|Danny | 103|Danny |
103|Pain | 104|Pain |
106|Rex | 105|Rex |
105|Paul | 106|Paul |
108|Josh | 107|Josh |
107|Philip | 108|Philip |
110|Green | 109|Green |
109|Evan | 110|Evan |
25. From the following table, write a SQL query to find the first login date for each customer.
Return customer id, login date.
Input:
Table: bank_trans
trans_id|customer_id|login_date|
--------|-----------|----------|
101| 3002|2019-09-01|
101| 3002|2019-08-01|
102| 3003|2018-09-13|
102| 3002|2018-07-24|
103| 3001|2019-09-25|
102| 3004|2017-09-05|
Output:
customer_id|first_login|
-----------|-----------|
3001| 2019-09-25|
3002| 2018-07-24|
3003| 2018-09-13|
3004| 2017-09-05|
26. From the following table, write a SQL query to find those salespersons whose
commission is less than ten thousand. Return salesperson name, commission.
Input:
Table: salemast
salesman_id|salesman_name|yearly_sale|
-----------|-------------|-----------|
101|Adam | 250000|
103|Mark | 100000|
104|Liam | 200000|
102|Evan | 150000|
105|Blake | 275000|
106|Noah | 50000|
Table : commision
salesman_id|commision_amt|
-----------|-------------|
101| 10000|
103| 4000|
104| 8000|
102| 6000|
105| 11000|
Output:
salesman_name|commision_amt|
-------------|-------------|
Mark | 4000|
Liam | 8000|
Evan | 6000|
27. From the following table write a SQL query to find those distributors who purchased all
types of item from the company. Return distributors ids.
Input:
Table: items
item_code|item_name|
---------|---------|
10091|juice |
10092|chocolate|
10093|cookies |
10094|cake |
Table : orders
order_id|distributor_id|item_ordered|item_quantity|
--------|--------------|------------|-------------|
1| 501| 10091| 250|
2| 502| 10093| 100|
3| 503| 10091| 200|
4| 502| 10091| 150|
5| 502| 10092| 300|
6| 504| 10094| 200|
7| 503| 10093| 250|
8| 503| 10092| 250|
9| 501| 10094| 180|
10| 503| 10094| 350|
Output:
distributor_id|
--------------|
503|
28. From the following tables write a SQL query to find those directors and actors who
worked together at least three or more movies. Return the director and actor name.
Input:
Table: actor_test
act_id|act_name |
------|-----------------|
101|James Stewart |
102|Deborah Kerr |
103|Peter OToole |
104|Robert De Niro |
105|F. Murray Abraham|
106|Harrison Ford |
107|Bill Paxton |
108|Stephen Baldwin |
109|Jack Nicholson |
110|Mark Wahlberg |
Table : director_test
dir_id|dir_name |
------|-----------------|
201|Alfred Hitchcock |
202|Jack Clayton |
203|James Cameron |
204|Michael Cimino |
205|Milos Forman |
206|Ridley Scott |
207|Stanley Kubrick |
208|Bryan Singer |
209|Roman Polanski |
Table: movie_test
mov_id|movie_name |
------|-------------------|
901|Vertigo |
902|Aliens |
903|Lawrence of Arabia |
904|The Deer Hunter |
905|True Lies |
906|Blade Runner |
907|Eyes Wide Shut |
908|Titanic |
909|Chinatown |
910|Ghosts of the Abyss|
Table : mov_direction_test
dir_id|mov_id|act_id|
------|------|------|
201| 901| 101|
203| 902| 107|
204| 904| 104|
203| 905| 107|
206| 906| 106|
203| 908| 107|
209| 909| 109|
203| 910| 107|
Output:
dir_name |act_name |
-------------|-----------|
James Cameron|Bill Paxton|
29. From the following tables write a SQL query to find those students who achieved 100
percent in various subjects in every year. Return examination ID, subject name, examination
year, number of students.
Input:
Table: exam_test
exam_id|subject_id|exam_year|no_of_student|
-------|----------|---------|-------------|
71| 201| 2017| 5146|
71| 201| 2018| 3545|
71| 202| 2018| 5945|
71| 202| 2019| 2500|
71| 203| 2017| 2500|
72| 201| 2018| 3500|
72| 202| 2017| 3651|
73| 201| 2018| 2647|
73| 201| 2019| 2647|
73| 202| 2018| 4501|
Table : subject_test
subject_id|subject_name|
----------|------------|
201|Mathematics |
202|Physics |
203|Chemistry |
Output:
exam_id|subject_name|exam_year|no_of_student|
-------|------------|---------|-------------|
71|Chemistry | 2017| 2500|
71|Mathematics | 2017| 5146|
71|Mathematics | 2018| 3545|
71|Physics | 2018| 5945|
71|Physics | 2019| 2500|
72|Mathematics | 2018| 3500|
72|Physics | 2017| 3651|
73|Mathematics | 2018| 2647|
73|Mathematics | 2019| 2647|
73|Physics | 2018| 4501|
30. From the following tables write a SQL query to find those students who achieved 100
percent marks in every subject for all the year. Return subject ID, subject name, students for
all year.
Input:
Table: exam_test
exam_id|subject_id|exam_year|no_of_student|
-------|----------|---------|-------------|
71| 201| 2017| 5146|
71| 201| 2018| 3545|
71| 202| 2018| 5945|
71| 202| 2019| 2500|
71| 203| 2017| 2500|
72| 201| 2018| 3500|
72| 202| 2017| 3651|
73| 201| 2018| 2647|
73| 201| 2019| 2647|
73| 202| 2018| 4501|
Table : subject_test
subject_id|subject_name|
----------|------------|
201|Mathematics |
202|Physics |
203|Chemistry |
Output:
subject_id|subject_name|Students for all year|
----------|------------|---------------------|
201|Mathematics | 17485|
202|Physics | 16597|
203|Chemistry | 2500|
31. From the following tables write a SQL query that will generate a report which shows the
total number of students achieved 100 percent for the first year of each examination of every
subject.
Input:
Table: exam_test
exam_id|subject_id|exam_year|no_of_student|
-------|----------|---------|-------------|
71| 201| 2017| 5146|
71| 201| 2018| 3545|
71| 202| 2017| 2701|
71| 202| 2018| 5945|
71| 202| 2019| 2500|
71| 203| 2017| 2500|
72| 201| 2018| 3500|
72| 202| 2017| 3651|
73| 201| 2017| 1000|
73| 201| 2018| 2647|
73| 201| 2019| 2647|
73| 202| 2018| 4501|
Table : subject_test
subject_id|subject_name|
----------|------------|
201|Mathematics |
202|Physics |
203|Chemistry |
Output:
exam_id|subject_name|first_year|no_of_student|
-------|------------|----------|-------------|
71|Mathematics | 2017| 5146|
71|Physics | 2017| 2701|
71|Chemistry | 2017| 2500|
72|Physics | 2017| 3651|
73|Mathematics | 2017| 1000|
32. From the following tables write a SQL query to display those managers who have average
experience for each scheme.
Input:
Table: managing_body
manager_id|manager_name|running_years|
----------|------------|-------------|
51|James | 5|
52|Cork | 3|
53|Paul | 4|
54|Adam | 3|
55|Hense | 4|
56|Peter | 2|
Table : scheme
scheme_code|scheme_manager_id|
-----------|-----------------|
1001| 51|
1001| 53|
1001| 54|
1001| 56|
1002| 51|
1002| 55|
1003| 51|
1004| 52|
Output:
scheme_code|Average year of experience|
-----------|--------------------------|
1001| 3.50|
1002| 4.50|
1003| 5.00|
1004| 3.00|
33. From the following tables write a SQL query to find those schemes which executed by
minimum number of employees. Return scheme code.
Input:
Table: managing_body
manager_id|manager_name|running_years|
----------|------------|-------------|
51|James | 5|
52|Cork | 3|
53|Paul | 4|
54|Adam | 3|
55|Hense | 4|
56|Peter | 2|
Table : scheme
scheme_code|scheme_manager_id|
-----------|-----------------|
1001| 51|
1001| 53|
1001| 54|
1001| 56|
1002| 51|
1002| 55|
1003| 51|
1004| 52|
Output:
scheme_code|
-----------|
1003|
1004|
34. From the following tables write a SQL query to find those experienced manager who
execute the schemes. Return scheme code and scheme manager ID.
Input:
Table: managing_body
manager_id|manager_name|running_years|
----------|------------|-------------|
51|James | 5|
52|Cork | 3|
53|Paul | 4|
54|Adam | 3|
55|Hense | 4|
56|Peter | 2|
Table : scheme
scheme_code|scheme_manager_id|
-----------|-----------------|
1001| 51|
1001| 53|
1001| 54|
1001| 56|
1002| 51|
1002| 55|
1003| 51|
1004| 52|
Output:
scheme_code|scheme_manager_id|
-----------|-----------------|
1001| 51|
1002| 51|
1003| 51|
1004| 52|
35. From the following tables write an SQL query to find the best seller by total sales price.
Return distributor ID , If there is a tie, report them all.
Input:
Table: item
item_code|item_desc |cost|
---------|------------|----|
101|mother board|2700|
102|RAM | 800|
103|key board | 300|
104|mouse | 300|
Table : sales_info
distributor_id|item_code|retailer_id|date_of_sell|quantity|total_cost|
--------------|---------|-----------|------------|--------|----------|
5001| 101| 1001| 2020-02-12| 3| 8100|
5001| 103| 1002| 2020-03-15| 15| 4500|
5002| 101| 1001| 2019-06-24| 2| 5400|
5001| 104| 1003| 2019-09-11| 8| 2400|
5003| 101| 1003| 2020-10-21| 5| 13500|
5003| 104| 1002| 2020-12-27| 10| 3000|
5002| 102| 1001| 2019-05-18| 12| 9600|
5002| 103| 1004| 2020-06-17| 8| 2400|
5003| 103| 1001| 2020-04-12| 3| 900|
Output:
distributor_id|
--------------|
5002|
5003|
36. From the following table write a SQL query to find those retailers who have bought 'key
board' but not 'mouse'. Return retailer ID.
Input:
Table: item
item_code|item_desc |cost|
---------|------------|----|
101|mother board|2700|
102|RAM | 800|
103|key board | 300|
104|mouse | 300|
Table : sales_info
distributor_id|item_code|retailer_id|date_of_sell|quantity|total_cost|
--------------|---------|-----------|------------|--------|----------|
5001| 101| 1001| 2020-02-12| 3| 8100|
5001| 103| 1002| 2020-03-15| 15| 4500|
5002| 101| 1001| 2019-06-24| 2| 5400|
5001| 104| 1003| 2019-09-11| 8| 2400|
5003| 101| 1003| 2020-10-21| 5| 13500|
5003| 104| 1002| 2020-12-27| 10| 3000|
5002| 102| 1001| 2019-05-18| 12| 9600|
5002| 103| 1004| 2020-06-17| 8| 2400|
5003| 103| 1001| 2020-04-12| 3| 900|
Output:
retailer_id|
-----------|
1001|
1004|
37. From the following table write a SQL query to display those items that were only sold in
the 2nd quarter of a year, i.e. April 1st to June end for the year 2020. Return item code and
item description.
Input:
Table: item
item_code|item_desc |cost|
---------|------------|----|
101|mother board|2700|
102|RAM | 800|
103|key board | 300|
104|mouse | 300|
Table : sales_info
distributor_id|item_code|retailer_id|date_of_sell|quantity|total_cost|
--------------|---------|-----------|------------|--------|----------|
5001| 101| 1001| 2020-02-12| 3| 8100|
5001| 103| 1002| 2020-03-15| 15| 4500|
5002| 101| 1001| 2019-06-24| 2| 5400|
5001| 104| 1003| 2019-09-11| 8| 2400|
5003| 101| 1003| 2020-10-21| 5| 13500|
5003| 104| 1002| 2020-12-27| 10| 3000|
5002| 102| 1001| 2019-05-18| 12| 9600|
5002| 103| 1004| 2020-06-17| 8| 2400|
5003| 103| 1001| 2020-04-12| 3| 900|
Output:
item_code|item_desc |
---------|------------|
101|mother board|
102|RAM |
103|key board |
38. From the following table write a SQL query to find the highest purchase with its
corresponding item for each customer. In case of a same quantity purchase find the item code
which is smallest.
The output must be sorted by increasing of customer_id. Return customer ID,lowest item
code and purchase quantity.
Input:
Table: purchase
Field |Type |Null|Key|Default|Extra|
-----------|-------|----|---|-------|-----|
customer_id|int(11)|NO | | | |
item_code |int(11)|NO | | | |
purch_qty |int(11)|NO | | | |
Data:
customer_id|item_code|purch_qty|
-----------|---------|---------|
101| 504| 25|
101| 503| 50|
102| 502| 40|
102| 503| 25|
102| 501| 45|
103| 505| 30|
103| 503| 25|
104| 505| 40|
101| 502| 25|
102| 504| 40|
102| 505| 50|
103| 502| 25|
104| 504| 40|
103| 501| 35|
Output:
customer_id|lowest item code|purch_qty|
-----------|----------------|---------|
101| 503| 50|
102| 505| 50|
103| 501| 35|
104| 504| 40|
39. From the following table write a SQL query to find all the writers who rated at least one
of their own topic. Sorted the result in ascending order by writer id. Return writer ID.
Input:
Table: topics
Field |Type |Null|Key|Default|Extra|
--------------|-------|----|---|-------|-----|
topic_id |int(11)|YES | | | |
writer_id |int(11)|YES | | | |
rated_by |int(11)|YES | | | |
date_of_rating|date |YES | | | |
Data:
topic_id|writer_id|rated_by|date_of_rating|
-------|---------|--------|--------------|
10001| 504| 507| 2020-07-17|
10003| 502| 503| 2020-09-22|
10001| 503| 507| 2020-02-07|
10002| 501| 507| 2020-05-13|
10002| 502| 502| 2020-04-10|
10002| 504| 502| 2020-11-16|
10003| 501| 502| 2020-10-05|
10001| 507| 507| 2020-12-23|
10004| 503| 501| 2020-08-28|
10003| 505| 504| 2020-12-21|
Output:
Author rated on own topic|
-------------------------|
502|
507|
40. From the following table write a SQL query to find all the writers who rated more than
one topics on the same date, sorted in ascending order by their id. Return writr ID.
Input:
Table: topics
Field |Type |Null|Key|Default|Extra|
--------------|-------|----|---|-------|-----|
topic_id |int(11)|YES | | | |
writer_id |int(11)|YES | | | |
rated_by |int(11)|YES | | | |
date_of_rating|date |YES | | | |
Data:
topic_id|writer_id|rated_by|date_of_rating|
-------|---------|--------|--------------|
10001| 504| 507| 2020-07-17|
10003| 502| 503| 2020-09-22|
10001| 503| 507| 2020-02-07|
10002| 501| 507| 2020-05-13|
10002| 502| 502| 2020-04-10|
10002| 504| 502| 2020-11-16|
10003| 501| 502| 2020-10-05|
10001| 507| 507| 2020-12-23|
10004| 503| 501| 2020-08-28|
10003| 505| 504| 2020-12-21|
Output:
Topic rated by the writer|
-------------------------|
502|
507|
41. From the following table write a SQL query to make a report such that there is a product
id column and a sale quantity column for each quarter. Return product ID and sale quantity of
each quarter.
Input:
Table: sale
Field |Type |Null|Key|Default|Extra|
----------|-----------|----|---|-------|-----|
product_id|int(11) |NO |PRI| | |
sale_qty |int(11) |YES | | | |
qtr_no |varchar(25)|NO |PRI| | |
Data:
product_id|sale_qty|qtr_no|
----------|--------|------|
1| 15000|qtr1 |
1| 10000|qtr2 |
2| 20000|qtr1 |
2| 12000|qtr2 |
3| 20000|qtr1 |
3| 15000|qtr2 |
3| 23000|qtr3 |
3| 22000|qtr4 |
4| 25000|qtr2 |
4| 18000|qtr4 |
Output:
product_id qtr1_sale qtr2_sale qtr3_sale qtr4_sale
1 15000 10000 NULL NULL
2 20000 12000 NULL NULL
3 20000 15000 23000 22000
4 NULL 25000 NULL 18000
42. From the following table write a SQL query to find for each month and company, the
number of orders issued and their total quantity, the number of orders booked and their total
order quantity. Return month, name of the company, number of orders issued, number of
booked orders, total order quantity and total booked orders quantity.
Input:
Table: order_stat
Field |Type |Null|Key|Default|Extra|
---------|-----------|----|---|-------|-----|
order_id |int(11) |NO |PRI| | |
com_name |varchar(25)|YES | | | |
ord_qty |int(11) |YES | | | |
ord_stat |varchar(25)|YES | | | |
stat_date|date |YES | | | |
Data:
order_id|com_name |ord_qty|ord_stat |stat_date |
--------|-----------|-------|---------|----------|
151|MMS INC | 500|Booked |2020-08-15|
152|BCT LTD | 300|Cancelled|2020-08-15|
153|MMS INC | 400|Cancelled|2020-08-26|
154|XYZ COR | 500|Booked |2020-08-15|
155|MMS INC | 500|Cancelled|2020-10-11|
156|BWD PRO LTD| 250|Cancelled|2020-11-15|
157|BCT LTD | 600|Booked |2020-10-07|
158|MMS INC | 300|Booked |2020-12-11|
159|XYZ COR | 300|Booked |2020-08-26|
160|BCT LTD | 400|Booked |2020-11-15|
Output:
month year com_name no_of_orders booked_orders total_order_qty
no_of_booked_qty
2020-08 MMS INC 2 1 900
500
2020-08 BCT LTD 1 0 300
0
2020-08 XYZ COR 2 2 800
800
2020-10 MMS INC 1 0 500
0
2020-11 BWD PRO LTD 1 0 250
0
2020-10 BCT LTD 1 1 600
600
2020-12 MMS INC 1 1 300
300
2020-11 BCT LTD 1 1 400
400
43. From the following table write a SQL query to find for each month and company, the
number of orders issued and their total quantity, the number of orders cancelled and their
total quantity. Return month, name of the company, number of orders booked, number of
booked quantity, number of cancelled order, and number of cancelled quantity.
Input:
Table: order_stat
Field |Type |Null|Key|Default|Extra|
---------|-----------|----|---|-------|-----|
order_id |int(11) |NO |PRI| | |
com_name |varchar(25)|YES | | | |
ord_qty |int(11) |YES | | | |
ord_stat |varchar(25)|YES | | | |
stat_date|date |YES | | | |
Data:
order_id|com_name |ord_qty|ord_stat |stat_date |
--------|-----------|-------|---------|----------|
151|MMS INC | 500|Booked |2020-08-15|
152|BCT LTD | 300|Cancelled|2020-08-15|
153|MMS INC | 400|Cancelled|2020-08-26|
154|XYZ COR | 500|Booked |2020-08-15|
155|MMS INC | 500|Cancelled|2020-10-11|
156|BWD PRO LTD| 250|Cancelled|2020-11-15|
157|BCT LTD | 600|Booked |2020-10-07|
158|MMS INC | 300|Booked |2020-12-11|
159|XYZ COR | 300|Booked |2020-08-26|
160|BCT LTD | 400|Booked |2020-11-15|
Table: order_return
Structure:
Field Type Null Key Default Extra
order_id int(11) NO MUL
return_date date YES
Data:
order_id return_date
153 2020-10-12
154 2020-11-07
156 2020-12-05
159 2020-09-17
Output:
month |com_name |booked_count|booked_qty|cancelled_count|cancelled_qty|
-------|-----------|------------|----------|---------------|-------------|
2020-08|BCT LTD | 0| 0.0| 1| 300.0|
2020-08|MMS INC | 1| 500.0| 1| 400.0|
2020-08|XYZ COR | 2| 800.0| 0| 0.0|
2020-10|BCT LTD | 1| 600.0| 0| 0.0|
2020-10|MMS INC | 0| 0.0| 1| 500.0|
2020-11|BCT LTD | 1| 400.0| 0| 0.0|
2020-11|BWD PRO LTD| 0| 0.0| 1| 250.0|
2020-12|MMS INC | 1| 300.0| 0| 0.0|
44. From the following tables write a SQL query to find the average selling price for each
item. Return item code and average_selling_price. average_selling_price should be rounded
to 2 decimal places.
Input:
Table: item_price
Field |Type |Null|Key|Default|Extra|
---------|-------|----|---|-------|-----|
item_code|int(11)|YES | | | |
date_from|date |YES | | | |
date_to |date |YES | | | |
item_cost|int(11)|YES | | | |
Data:
item_code|date_from |date_to |item_cost|
---------|----------|----------|---------|
101|2018-04-07|2018-06-28| 8|
102|2018-02-15|2018-04-17| 13|
103|2018-03-12|2018-04-30| 10|
101|2018-06-29|2018-10-31| 15|
103|2018-05-01|2019-08-24| 14|
102|2018-04-18|2018-07-10| 25|
104|2018-06-11|2018-10-10| 25|
101|2018-11-01|2019-01-15| 20|
Table: sale
Structure:
Field Type Null Key Default Extra
sale_date date YES
item_code int(11) YES
sale_qty int(11) YES
Data:
sale_date item_code sale_qty
2018-05-15 101 120
2018-04-27 103 80
2018-04-10 102 200
2018-07-12 101 100
2018-07-07 103 50
2018-09-17 104 100
2018-06-25 102 100
Output:
item_code|average_selling_price|
---------|---------------------|
101| 11.18|
102| 17.00|
103| 11.54|
104| 25.00|
45. From the following table write a SQL query to find all employees that directly or
indirectly report to the head of the company. Return employee_id, name, and manager_id.
Input:
Table: emp_test_table
Field |Type |Null|Key|Default|Extra|
-----------|-----------|----|---|-------|-----|
employee_id|int(11) |NO |PRI| | |
first_name |varchar(25)|YES | | | |
manager_id |int(11) |YES | | | |
Data:
employee_id|first_name |manager_id|
-----------|-----------|----------|
100|Steven | 100|
101|Neena | 100|
102|Lex | 100|
103|Alexander | 102|
104|Bruce | 103|
105|David | 103|
106|Valli | 103|
107|Diana | 103|
108|Nancy | 101|
109|Daniel | 108|
110|John | 108|
Output:
employee_id|Name |manager_id|
-----------|-----------|----------|
101|Neena | 100|
102|Lex | 100|
103|Alexander | 102|
104|Bruce | 103|
105|David | 103|
106|Valli | 103|
107|Diana | 103|
108|Nancy | 101|
109|Daniel | 108|
110|John | 108|
46. From the following tables write a SQL query to find the number of times each patient call
the specialist doctor since their treating period. Order the result table by patient_id and
specialist_call.
Input:
Table: patient
Field |Type |Null|Key|Default|Extra|
------------|-----------|----|---|-------|-----|
patient_id |int(11) |NO |PRI| | |
patient_name|varchar(25)|YES | | | |
Data:
patient_id|patient_name |
----------|---------------|
1001|Gilbart Kane |
1002|Thomas Richi |
1003|Ricardo Grance |
1004|Vanio Tishuma |
1005|Charls Brown |
Table: speciality
Field |Type |Null|Key|Default|Extra|
----------|-----------|----|---|-------|-----|
specialist|varchar(25)|YES | | | |
Data:
specialist |
-----------|
medicine |
cardiology |
neurology |
hematology |
Table: treatment
Field |Type |Null|Key|Default|Extra|
---------------|-----------|----|---|-------|-----|
patient_id |int(11) |YES |MUL| | |
specialist_call|varchar(25)|YES | | | |
Data:
patient_id|specialist_call|
----------|---------------|
1001|medicine |
1003|medicine |
1002|cardiology |
1001|hematology |
1004|medicine |
1003|cardiology |
1005|neurology |
1002|neurology |
1001|cardiology |
1005|cardiology |
1003|cardiology |
1005|hematology |
1004|hematology |
1005|neurology |
1002|neurology |
1001|hematology |
Output:
patient_id|patient_name |specialist |Specialist Attended|
----------|---------------|-----------|-------------------|
1001|Gilbart Kane |cardiology | 1|
1001|Gilbart Kane |hematology | 2|
1001|Gilbart Kane |medicine | 1|
1001|Gilbart Kane |neurology | 0|
1002|Thomas Richi |cardiology | 1|
1002|Thomas Richi |hematology | 0|
1002|Thomas Richi |medicine | 0|
1002|Thomas Richi |neurology | 2|
1003|Ricardo Grance |cardiology | 2|
1003|Ricardo Grance |hematology | 0|
1003|Ricardo Grance |medicine | 1|
1003|Ricardo Grance |neurology | 0|
1004|Vanio Tishuma |cardiology | 0|
1004|Vanio Tishuma |hematology | 1|
1004|Vanio Tishuma |medicine | 1|
1004|Vanio Tishuma |neurology | 0|
1005|Charls Brown |cardiology | 1|
1005|Charls Brown |hematology | 1|
1005|Charls Brown |medicine | 0|
1005|Charls Brown |neurology | 2|
47. From the following table write a SQL query to find the number of employees are working
in the department of each employees. Return employee Id and number of employees are
working in their department.
Input:
Table: emp_test_table
Field |Type |Null|Key|Default|Extra|
-----------|-----------|----|---|-------|-----|
employee_id|int(11) |NO |PRI| | |
first_name |varchar(25)|YES | | | |
manager_id |int(11) |YES | | | |
Data:
employee_id|first_name |department_id|
-----------|-----------|-------------|
100|Steven | 90|
101|Neena | 90|
102|Lex | 90|
103|Alexander | 60|
104|Bruce | 60|
105|David | 60|
106|Valli | 60|
107|Diana | 60|
108|Nancy | 100|
109|Daniel | 100|
110|John | 100|
Output:
employee_id|employees_in_department|
-----------|-----------------------|
100| 3|
101| 3|
102| 3|
103| 5|
104| 5|
105| 5|
106| 5|
107| 5|
108| 3|
109| 3|
110| 3|
48. From the following table write a SQL query to find the total sale quantity of items of each
unit type at each day. Return unit type, date and total sale quantity at each day. Order the
result table by gender and day.
Input:
Table: sale
Field |Type |Null|Key|Default|Extra|
------------|-----------|----|---|-------|-----|
product_name|varchar(25)|YES | | | |
unit_type |varchar(5) |YES | | | |
sale_date |date |YES | | | |
sale_qty |int(11) |YES | | | |
Data:
product_name |unit_type|sale_date |sale_qty|
---------------|---------|----------|--------|
Munchos |P |2018-05-15| 20|
Boyer Chocolate|P |2018-04-27| 30|
CocaCola |L |2018-04-10| 25|
Fruit Cakes |P |2018-07-12| 30|
CocaCola |L |2018-07-07| 50|
Fanta |L |2018-01-27| 70|
Chex Mix |P |2018-09-17| 40|
Jaffa Cakes |P |2018-06-25| 40|
Pom-Bear |P |2018-02-11| 30|
Twix Chocolate |P |2018-12-24| 50|
Limca |L |2018-03-15| 50|
Mirinda |L |2018-02-05| 40|
Output:
unit_type|sale_date |running unit|
---------|----------|------------|
L |2018-01-27| 70|
L |2018-02-05| 110|
L |2018-03-15| 160|
L |2018-04-10| 185|
L |2018-07-07| 235|
P |2018-02-11| 30|
P |2018-04-27| 60|
P |2018-05-15| 80|
P |2018-06-25| 120|
P |2018-07-12| 150|
P |2018-09-17| 190|
P |2018-12-24| 240|
49. From the following tables write a SQL query to get the description of items with 50 or
more quantities sold out within January and February of 2020. Return item description and
sale quantity.
Input:
Table: item
Field |Type |Null|Key|Default|Extra|
---------|------------|----|---|-------|-----|
item_code|int(11) |NO |PRI| | |
item_desc|varchar(255)|YES | | | |
cost |int(11) |YES | | | |
Data:
item_code|item_desc |cost|
---------|------------|----|
101|mother board|2700|
102|RAM | 800|
103|key board | 300|
104|mouse | 300|
Table: sales_info
Field |Type |Null|Key|Default|Extra|
--------------|-------|----|---|-------|-----|
distributor_id|int(11)|YES | | | |
item_code |int(11)|YES | | | |
retailer_id |int(11)|YES | | | |
date_of_sell |date |YES | | | |
quantity |int(11)|YES | | | |
total_cost |int(11)|YES | | | |
Data:
distributor_id|item_code|retailer_id|date_of_sell|quantity|total_cost|
--------------|---------|-----------|------------|--------|----------|
5001| 101| 1001| 2020-01-12| 30| 8100|
5001| 103| 1002| 2020-01-15| 25| 4500|
5002| 101| 1001| 2019-01-30| 25| 5400|
5001| 104| 1003| 2019-02-17| 75| 2400|
5003| 101| 1003| 2020-03-07| 55| 13500|
5003| 104| 1002| 2020-05-27| 100| 3000|
5002| 102| 1001| 2020-05-18| 65| 9600|
5002| 103| 1004| 2020-01-30| 45| 2400|
5003| 103| 1001| 2020-03-12| 30| 900|
Output:
item_desc |sale_quantity|
------------|-------------|
key board | 70|
mother board| 55|
mouse | 75|
50. From the following table write a SQL query to find the order id and the item name for all
companies who are not registered with the distributor. Return the result table in any order.
Input:
Table: company_info
Field |Type |Null|Key|Default|Extra|
------------|-----------|----|---|-------|-----|
company_id |int(11) |NO |PRI| | |
company_name|varchar(25)|YES | | | |
Data:
company_id|company_name|
----------|------------|
5001|Intel |
5002|Kingston |
5003|Dell |
5004|Sony |
5005|Iball |
5006|Canon |
Table: orders
Field |Type |Null|Key|Default|Extra|
----------|-----------|----|---|-------|-----|
order_id |int(11) |YES | | | |
item_name |varchar(25)|YES | | | |
company_id|int(11) |YES | | | |
Data:
order_id|item_name |company_id|
--------|-------------|----------|
101|mother board | 5001|
102|RAM | 5002|
103|printer | 5006|
104|keyboard | 5005|
105|mouse | 6051|
106|speaker | 6009|
107|web cam | 5005|
108|hard disk | 5002|
109|monitor | 5003|
110|scanner | 7023|
Output:
order_id|item_name|
--------|---------|
105|mouse |
106|speaker |
110|scanner |