Interview Question Full 2
Interview Question Full 2
SQL CLAUSES
SQL clause helps us to retrieve a set or bundles of records from the table.
SQL clause helps us to specify a condition on the columns or the records of a table.
WHERE CLAUSE
GROUP BY CLAUSE
HAVING CLAUSE
ORDER BY CLAUSE
WHERE Clause: The SQL WHERE clause is used to specify a condition while fetching the data from
a single table or by joining with multiple tables.
If the given condition is satisfied, then only it returns a specific value from the table.
You should use the WHERE clause to filter the records and fetching only the necessary records.
The WHERE clause is not only used in the SELECT statement, but it is also used for
SELECT
UPDATE
DELETE
Syntax
SELECT "column_name"
FROM "table_name"
WHERE "condition";
The usage of SQL GROUP BY clause is, to divide the rows in a table into smaller groups.
The grouping can happen after retrieves the rows from a table.
When some rows are retrieved from a grouped result against some condition, that is possible with
HAVING clause.
The GROUP BY clause is used with the SELECT statement to make a group of rows based on the
values of a specific column or expression. The SQL AGGREGATE function can be used to get
summary information for every group and these are applied to an individual group.
The WHERE clause is used to retrieve rows based on a certain condition, but it cannot be applied to
grouped result.
In an SQL statement, suppose you are using GROUP BY, if required you can use HAVING instead of
WHERE, after GROUP BY.
Syntax:
SELECT <column_list>
[HAVING] <condition>;
FROM Store_Information
GROUP BY Store_Name;
Having clause: The HAVING clause is used to filter the result set based on the result of an aggregate
function.
HAVING is often coupled with the presence of the GROUP BY clause, although it is possible to have
a HAVING clause without the GROUP BY clause.
Syntax:
FROM "table_name"
[GROUP BY "column_name1"]
The brackets around "column_name1" and GROUP BY "column_name1" means that they are
optional.
Note: We may select zero, one, or more columns in addition to the aggregate function. If we do select
any column outside of the aggregate function, there is no need for the GROUP BY clause.
Table Store_Information
To see only the stores with sales over $1,500, we would type,
FROM Store_Information
GROUP BY Store_Name
order by: The ORDER BY command in SQL will sort the result set in either ascending or descending
order.
ORDER BY usually appears last in a SQL statement because it is performed after the result set has
been retrieved.
The ORDER BY keyword will sort the records in ascending order by default.
sql tutorial , pl sql tutorial , mysql tutorial , oracle tutorial , learn sql , sql server tutorial
Syntax:
SELECT "column_name"
FROM "table_name"
[WHERE "condition"]
The [ ] means that the WHERE statement is optional. However, if a WHERE clause exists, it comes
before the ORDER BY clause.
ASC means that the results will be shown in ascending order, and DESC means that the results will be
shown in descending order.
Assuming that we choose ascending order for both columns, the output will be ordered in ascending
order according to column 1.
If there is a tie for the value of column 1, we then sort in ascending order by column 2.
Table Store_Information
To list the contents of Table Store_Information by Sales in descending order, we key in,
FROM Store_Information
Result:
67. Collection classes are specialized classes for data storage and retrieval. These classes provide
support for stacks, queues, lists, and hash tables. Most collection classes implement the same
interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements and
accessing a list of items on the basis of an index etc. These classes create collections of objects of the
Object class, which is the base class for all data types in C#.
It is basically an alternative to an array. However, unlike array you can add and remove items from a
list at a specified position using an index and the array resizes itself automatically. It also allows
dynamic memory allocation, adding, searching and sorting items in the list.
2Hashtable
A hash table is used when you need to access elements by using key, and you can identify a useful
key value. Each item in the hash table has a key/value pair. The key is used to access the items in the
collection.
3SortedList
A sorted list is a combination of an array and a hash table. It contains a list of items that can be
accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you
access items using a key , it is a Hashtable. The collection of items is always sorted by the key value.
4Stack
It is used when you need a last-in, first-out access of items. When you add an item in the list, it is
called pushing the item and when you remove it, it is called popping the item.
5Queue
It is used when you need a first-in, first-out access of items. When you add an item in the list, it is
called enqueue and when you remove an item, it is called deque.
6 BitArray
70. DataReader
DataReader is used to read the data from the database and it is a read and forward only connection
oriented architecture during fetch the data from database. DataReader will fetch the data very fast
when compared with dataset. Generally, we will use ExecuteReader object to bind data to datareader.
To bind DataReader data to GridView we need to write the code like as shown below:
con.Open();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
C#
Holds the connection open until you are finished (don't forget to close it!).
DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during
work with datasets and it is a collection of DataTables and relations between tables. It is used to hold
multiple tables with data. You can select data form tables, create views based on table and ask child
rows over relations. Also DataSet provides you with rich features like saving data as XML and
loading XML data.
conn.Open();
sda.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
C#
DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to
read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented
architecture. Check below sample code to see how to use DataAdapter in code:
conn.Open();
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
C#
Lets you close the connection as soon it's done loading data, and may even close it for you
automatically
You can iterate over it as many times as you need, or even look up a specific record by index
DataTable
DataTable represents a single table in the database. It has rows and columns. There is no much
difference between dataset and datatable, dataset is simply the collection of datatables.
conn.Open();
sda.Fill(dt);
gridview1.DataSource = dt;
gvidview1.DataBind();
}
71.Array
An Array is a collection of data items of the same type. An Array is reference type so memory for the
array is allocated on the heap. We can initialize an Array using the "new" operator and by specifying
the type and number of elements inside the Array.
EXAMPLE
As a memory for an Array is allocated on the heap, 5 empty array elements are allocated on the heap
when we initialize the Array1.
After array is declared and initialized, you can access the array elements using indexer. Array support
only indexers having integer parameters.
array1[0]=”Hello”;
array1[1]=”Bye”;
Here, the first important point to note is that array has a fixed size.
An array is strongly-typed. It means if we declare an Array of string type, then we cannot store the
integer value in that array.
The array provides better performance than the ArrayList because an array stores the same type of
data which doesn't need unnecessary boxing or unboxing.
"Array class" is the base class for all arrays in C#. It is defined in system namespace.
ArrayList
ArrayList implements the IList interface. ArrayList is one of the most flexible data structures from C#
collection. Collection classes are special classes for data storage and retrieval.
EXAMPLE
using System.Collection;
a1.add(null);
a1.insert(1, ”hi”);
a1.add(3);
a1.add(8.23);
ArrayLists do not have a specific size. When we initialize an arraylist, it will initially allocate the
memory for 4 elements. When we add the 5th element, ArrayList will automatically redimension to
double of its current size. So, the size will increase as 4, 8, 16, 32, 64 and so on (i.e 2^n).
ArrayList is a non-generic type of collection in C#. It means you can store any type of data in
ArrayList.
ArrayList provides the facility of dynamic size but it comes at a cost of performance. The ArrayList's
internal Array is of "object type". So, if we are using value type then each element is boxed and stored
on a heap and whenever we access them it is unboxed to value type.
ArrayList implements the IList interface so, it provides a various method that we can use for easy
implementation.
73.VARCHAR
VARCHAR (short for variable character) is a data type used to store non-Unicode variable-length
character strings. This means that it can store characters from a single-byte character set, such as
ASCII. The maximum length of a VARCHAR column can be specified during table creation or
modification, up to a maximum of 8,000 characters.
NVARCHAR
NVARCHAR (short for national variable character) is a data type used to store Unicode variable-
length character strings. Unicode is a character encoding standard that allows for the representation of
a wide range of characters, including those from different languages and scripts. Like VARCHAR, the
maximum length of an NVARCHAR column can be specified during table creation or modification,
up to a maximum of 4,000 characters.
LastName NVARCHAR(50)
);
DataReader
The ADO.NET DataReader is used to retrieve read-only (cannot update data back to a datasource)
and forward-only (cannot read backward/random) data from a database.
Using of a DataReader increases application performance and reduces system overheads. This is due
to one row at a time is stored in memory.
This is a connected architecture: The data is available as long as the connection with database exists.
The following code statement is used to retrieve rows from a data source.
conn.open();
//The Read method of the DataReader object is used to obtain a row from the results of the executed
query.
while(myReader.Read())
//Once you're done with the data reader, call the Close method to close a data reader:
myReader.Close();
conn.close();
DataReader in ADO.NET
DataReader in C#
DataSet
The DataSet represents a complete set of data including related tables, constraints, and relationships
among the tables.
The DataSet can also persist and reload its contents as XML and its schema as XML Schema
definition language (XSD) schema.
The DataAdapter acts as a bridge between a DataSet and a data source for retrieving and saving data.
The DataAdapter helps mapping the data in the DataSet to match the data in the data source.
Also, Upon an update of dataset, it allows changing the data in the data source to match the data in the
DataSet.
Hence, point (8) says that it is a disconnected architecture. Fill the data in DataSet and that's it. No
connection existence required
The following code statement is used to retrieve rows from a data source.
//Create SqlDataAdapter which acts as bridge to put the data in DataSet,(data is table available by
executing your SQL query)
//fill the dataset with the data by some name say "CustomersTable"
myAdapter.Fill(ds,"CustomersTable");
75.C# static
In C#, static is a keyword or modifier that belongs to the type not instance. So instance is not required
to access the static members. In C#, static can be field, method, constructor, class, properties, operator
and event.
Memory efficient: Now we don't need to create instance for accessing the static members, so it saves
memory. Moreover, it belongs to the type, so it will not get memory each time when instance is
created.
C# Static Field
A field which is declared as static, is called static field. Unlike instance field which gets memory each
time whenever you create object, there is only one copy of static field created in the memory. It is
shared to all the objects.
It is used to refer the common property of all objects such as rateOfInterest in case of Account,
companyName in case of Employee etc.
using System;
this.accno = accno;
this.name = name;
class TestAccount{
a2.display();
Output:
In C#, serialization is the process of converting object into byte stream so that it can be saved to
memory, file or database. The reverse process of serialization is called deserialization.
78.C# serialization
C# SerializableAttribute
To serialize the object, you need to apply SerializableAttribute attribute to the type. If you don't apply
SerializableAttribute attribute to the type, SerializationException exception is thrown at runtime.
C# Serialization example
Let's see the simple example of serialization in C# where we are serializing the object of Student
class. Here, we are going to use BinaryFormatter.Serialize(stream, reference) method to serialize the
object.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Student
int rollno;
string name;
this.rollno = rollno;
this.name = name;
formatter.Serialize(stream, s);
stream.Close();
sss.txt:
As you can see, the serialized data is stored in the file. To get the data, you need to perform
deserialization.
79.Hash set and tree set both belong to the collection framework. HashSet is the implementation of
the Set interface whereas Tree set implements sorted set. Tree set is backed by TreeMap while
HashSet is backed by a hashmap.
Sr. No. Key Hash Set Tree Set
Implementation
Null Object
The tree set does not allow the null object. It throws the null pointer exception.
Methods
Heterogeneous object
Ordering
Example of TreeSet
class TreeSetExmaple {
treeset.add("Good");
treeset.add("For");
treeset.add("Health");
//Add Duplicate Element
treeset.add("Good");
System.out.println("TreeSet : ");
System.out.println(temp);
Output
TreeSet:
For
Good
Health
Example of HashSet
class HashSetExample {
hashSet.add("Good");
hashSet.add("For");
hashSet.add("Health");
hashSet.add("Good");
System.out.println("HashSet: ");
System.out.println(temp);
}
Output
HashSet:
Health
For
Good
Both exceptions and errors are used to handle and manage exceptional situations or unexpected events
that occur during the execution of a program. While they are similar in some ways, there are notable
differences between exceptions and errors in terms of their nature, handling, and impact on the
program.
Nature
Error: An error, also known as a system error or runtime error, refers to an unrecoverable or severe
issue that occurs in the system or environment where the program is running. Errors are usually
caused by issues like hardware failures, memory corruption, or stack overflow, and they indicate a
critical failure that cannot be resolved within the program itself.
Handling
Exception: Exceptions are designed to be caught and handled by the program. They provide a
mechanism for gracefully recovering from exceptional situations, allowing the program to continue
executing without terminating abruptly. Exceptions can be caught and handled using try-catch blocks,
allowing developers to handle specific types of exceptions and take appropriate actions.
Error: Errors, on the other hand, are generally not meant to be caught and handled by the program.
They indicate severe issues that typically require system-level intervention or debugging. Errors are
often fatal and can cause the program to terminate abruptly. In most cases, errors are handled at a
higher level, such as the operating system or runtime environment.
Impact on Program
Exception: Exceptions have a localized impact on the program. When an exception occurs, the
program's flow is interrupted, and the runtime searches for an appropriate exception handler to handle
the exception. If an exception is not caught and handled, it propagates up the call stack until it reaches
an appropriate catch block or, if unhandled, causes the program to terminate.
Error: Errors have a broader impact on the program and the system. They often indicate critical
failures that affect the entire system or environment. When an error occurs, it may result in the
termination of the program, abnormal system behavior, or the need to restart the application or the
system itself.
Example | Exception
try
Console.WriteLine(result);
if (divisor == 0)
Example | Error
Conclusion
Exceptions are used to handle and recover from exceptional conditions within the program, while
errors indicate severe system-level issues that may require external intervention. Exceptions are
caught and handled by the program, while errors are typically handled at a higher level. Proper
exception handling is an essential practice in C# to ensure robust and reliable software.
81.How can we call one constructor from another in the same class in C#?
Make use of this keyword in c# to call one constructor from another constructor
To call a constructor which is present in parent class make use of base keyword
Example
class Demo{
public Demo(){
System.Console.WriteLine($"{firstNumber} {secondNumber}");
class Program{
Console.ReadLine();
Output
12
123
To call a constructor which is present in another class make use of base keyword
83.SDLC Models
Software Development life cycle (SDLC) is a spiritual model used in project management that defines
the stages include in an information system development project, from an initial feasibility study to
the maintenance of the completed application.
There are different software development life cycle models specify and design, which are followed
during the software development phase. These models are also called "Software Development Process
Models." Each process model follows a series of phase unique to its type to ensure success in the step
of software development.
Waterfall Model
The waterfall is a universally accepted SDLC model. In this method, the whole process of software
development is divided into various phases.
The waterfall model is a continuous software development model in which development is seen as
flowing steadily downwards (like a waterfall) through the steps of requirements analysis, design,
implementation, testing (validation), integration, and maintenance.
Linear ordering of activities has some significant consequences. First, to identify the end of a phase
and the beginning of the next, some certification techniques have to be employed at the end of each
step. Some verification and validation usually do this mean that will ensure that the output of the stage
is consistent with its input (which is the output of the previous step), and that the output of the stage is
consistent with the overall requirements of the system.
RAD Model
RAD or Rapid Application Development process is an adoption of the waterfall model; it targets
developing software in a short period. The RAD model is based on the concept that a better system
can be developed in lesser time by using focus groups to gather system requirements.
Business Modeling
Data Modeling
Process Modeling
Application Generation
Spiral Model
The spiral model is a risk-driven process model. This SDLC model helps the group to adopt elements
of one or more process models like a waterfall, incremental, waterfall, etc. The spiral technique is a
combination of rapid prototyping and concurrency in design and development activities.
Each cycle in the spiral begins with the identification of objectives for that cycle, the different
alternatives that are possible for achieving the goals, and the constraints that exist. This is the first
quadrant of the cycle (upper-left quadrant).
The next step in the cycle is to evaluate these different alternatives based on the objectives and
constraints. The focus of evaluation in this step is based on the risk perception for the project.
The next step is to develop strategies that solve uncertainties and risks. This step may involve
activities such as benchmarking, simulation, and prototyping.
V-Model
In this type of SDLC model testing and the development, the step is planned in parallel. So, there are
verification phases on the side and the validation phase on the other side. V-Model joins by Coding
phase.
Incremental Model
The incremental model is not a separate model. It is necessarily a series of waterfall cycles. The
requirements are divided into groups at the start of the project. For each group, the SDLC model is
followed to develop software. The SDLC process is repeated, with each release adding more
functionality until all requirements are met. In this method, each cycle act as the maintenance phase
for the previous software release. Modification to the incremental model allows development cycles
to overlap. After that subsequent cycle may begin before the previous cycle is complete.
Agile Model
Agile methodology is a practice which promotes continues interaction of development and testing
during the SDLC process of any project. In the Agile method, the entire project is divided into small
incremental builds. All of these builds are provided in iterations, and each iteration lasts from one to
three weeks.
Any agile software phase is characterized in a manner that addresses several key assumptions about
the bulk of software projects:
It is difficult to think in advance which software requirements will persist and which will change. It is
equally difficult to predict how user priorities will change as the project proceeds.
For many types of software, design and development are interleaved. That is, both activities should be
performed in tandem so that design models are proven as they are created. It is difficult to think about
how much design is necessary before construction is used to test the configuration.
Analysis, design, development, and testing are not as predictable (from a planning point of view) as
we might like.
Iterative Model
This model works best for small projects with smaller size development team which are working
together. It is also useful for academic software development projects. It is an ideal model where
requirements are either unknown or final release date is not given.
Prototype Model
The prototyping model starts with the requirements gathering. The developer and the user meet and
define the purpose of the software, identify the needs, etc.
A 'quick design' is then created. This design focuses on those aspects of the software that will be
visible to the user. It then leads to the development of a prototype. The customer then checks the
prototype, and any modifications or changes that are needed are made to the prototype.
Looping takes place in this step, and better versions of the prototype are created. These are
continuously shown to the user so that any new changes can be updated in the prototype. This process
continue until the customer is satisfied with the system. Once a user is satisfied, the prototype is
converted to the actual system with all considerations for quality and security.
In real life, we store our data in multiple logical tables that are linked together by a common key value
in relational databases like SQL Server, Oracle, MySQL, and others. As a result, we constantly need
to get data from two or more tables into the desired output based on some conditions. We can quickly
achieve this type of data in SQL Server using the SQL JOIN clause. This article gives a complete
overview of JOIN and its different types with an example.
The join clause allows us to retrieve data from two or more related tables into a meaningful result set.
We can join the table using a SELECT statement and a join condition. It indicates how SQL Server
can use data from one table to select rows from another table. In general, tables are related to each
other using foreign key constraints.
Specify the logical operator to compare values from the columns like =, <, or >.
SQL Server mainly supports four types of JOINS, and each join type defines how two tables are
related in a query. The following are types of join supports in SQL Server:
INNER JOIN
SELF JOIN
CROSS JOIN
OUTER JOIN
INNER JOIN
This JOIN returns all records from multiple tables that satisfy the specified join condition. It is the
simple and most popular form of join and assumes as a default join. If we omit the INNER keyword
with the JOIN query, we will get the same output.
The following visual representation explains how INNER JOIN returns the matching records from
table1 and table2:
The following syntax illustrates the use of INNER JOIN in SQL Server:
SELECT columns
FROM table1
age int,
);
amount_paid int,
);
Next, we will insert some records into these tables using the below statements:
(8345,'SQL', 15000),
Table: Student
Table: Fee
FROM Student
ON Student.admission_no = Fee.admission_no;
In this example, we have used the admission_no column as a join condition to get the data from both
tables. Depending on this table, we can see the information of the students who have paid their fee.
SELF JOIN
A table is joined to itself using the SELF JOIN. It means that each table row is combined with itself
and with every other table row. The SELF JOIN can be thought of as a JOIN of two copies of the
same tables. We can do this with the help of table name aliases to assign a specific name to each
table's instance. The table aliases enable us to use the table's temporary name that we are going to use
in the query. It's a useful way to extract hierarchical data and comparing rows inside a single table.
The following expression illustrates the syntax of SELF JOIN in SQL Server. It works the same as the
syntax of joining two different tables. Here, we use aliases names for tables because both the table
name are the same.
WHERE join_condition;
Example
ORDER BY S2.city;
In this example, we have used the id and city column as a join condition to get the data from both
tables.
CROSS JOIN
CROSS JOIN in SQL Server combines all of the possibilities of two or more tables and returns a
result that includes every row from all contributing tables. It's also known as CARTESIAN JOIN
because it produces the Cartesian product of all linked tables. The Cartesian product represents all
rows present in the first table multiplied by all rows present in the second table.
The below visual representation illustrates the CROSS JOIN. It will give all the records from table1
and table2 where each row is the combination of rows of both tables:
The following syntax illustrates the use of CROSS JOIN in SQL Server:
SELECT column_lists
FROM table1
Example
FROM Student
OUTER JOIN
OUTER JOIN in SQL Server returns all records from both tables that satisfy the join condition. In
other words, this join will not return only the matching record but also return all unmatched rows
from one or both tables.
The following syntax illustrates the use of LEFT OUTER JOIN in SQL Server
SELECT column_lists
FROM table1
ON table1.column = table2.column;
Example
We can demonstrate the LEFT OUTER JOIN using the following command:
FROM Student
ON Student.admission_no = Fee.admission_no;
This output shows that the unmatched row's values are replaced with NULLs in the respective
columns.
The RIGHT OUTER JOIN retrieves all the records from the right-hand table and matched rows from
the left-hand table. It will return NULL when no matching record is found in the left-hand table. Since
OUTER is an optional keyword, it is also known as RIGHT JOIN.
freestar
The following syntax illustrates the use of RIGHT OUTER JOIN in SQL Server:
SELECT column_lists
FROM table1
ON table1.column = table2.column;
Example
The following example explains how to use the RIGHT OUTER JOIN to get records from both
tables:
FROM Student
ON Student.admission_no = Fee.admission_no;
In this output, we can see that no column has NULL values because all rows in the Fee table are
available in the Student table based on the specified condition.
The FULL OUTER JOIN in SQL Server returns a result that includes all rows from both tables. The
columns of the right-hand table return NULL when no matching records are found in the left-hand
table. And if no matching records are found in the right-hand table, the left-hand table column returns
NULL.
The following syntax illustrates the use of FULL OUTER JOIN in SQL Server:
SELECT column_lists
FROM table1
ON table1.column = table2.column;
Example
The following example explains how to use the FULL OUTER JOIN to get records from both tables:
FROM Student
ON Student.admission_no = Fee.admission_no;
In this output, we can see that the column has NULL values when no matching records are found in
the left-hand and right-hand table based on the specified condition.
87.Connection string
The act of swapping two variables refers to mutually exchanging the values of the variables. Generall,
this is done with the data in memory.
The simplest method to swap two variables is to use a third temporary variable :
define swap(x, y)
temp := x
x := y
y := temp
Sample Solution:
C# Sharp Code:
using System;
number1 = int.Parse(Console.ReadLine());
number2 = int.Parse(Console.ReadLine());
temp = number1;
number1 = number2;
number2 = temp;
Console.Read();
Sample Output:
After Swapping :
First Number : 5
Second Number : 2
System Testing (ST) is a black box testing technique performed to evaluate the complete system the
system's compliance against specified requirements. In System testing, the functionalities of the
system are tested from an end-to-end perspective.
System Testing is usually carried out by a team that is independent of the development team in order
to measure the quality of the system unbiased. It includes both functional and Non-Functional testing.
90.What is router.
In MVC, routing is a process of mapping the browser request to the controller action and return
response back. Each MVC application has default routing for the default HomeController. We can set
custom routing for newly created controller.
The RouteConfig.cs file is used to set routing for the application. Initially it contains the following
code.
// RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplicationDemo
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
);
91.What is Scaffolding
ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Visual Studio
2013 includes pre-installed code generators for MVC and Web API projects. You add scaffolding to
your project when you want to quickly add code that interacts with data models. Using scaffolding
can reduce the amount of time to develop standard data operations in your project.
As you have seen that we have created the views for Index, Create, Edit actions and also need to
update the actions methods as well. But ASP.Net MVC provides an easier way to create all these
Views and action methods using scaffolding.
What is trigger.
The trigger is a database object similar to a stored procedure that is executed automatically when an
event occurs in a database. There are different kinds of events that can activate a trigger like inserting
or deleting rows in a table, a user logging into a database server instance, an update to a table column,
a table is created, altered, or dropped, etc.
ON table_name
AS
{SQL_Statements}
Triggers will be helpful when we need to execute some events automatically on certain desirable
scenarios.
93.Palindrome program in C#
A palindrome number is a number that is same after reverse. For example 121, 34543, 343, 131,
48984 are the palindrome numbers.
Let's see the palindrome program in C#. In this program, we will get an input from the user and check
whether number is palindrome or not.
using System;
int n,r,sum=0,temp;
n = int.Parse(Console.ReadLine());
temp=n;
while(n>0)
r=n%10;
sum=(sum*10)+r;
n=n/10;
if(temp==sum)
Console.Write("Number is Palindrome.");
else
Output:
Number is Palindrome.
In case of fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3,
5, 8, 13, 21 etc. The first two numbers of fibonacci series are 0 and 1.
int n1=0,n2=1,n3,i,number;
number = int.Parse(Console.ReadLine());
n3=n1+n2;
Console.Write(n3+" ");
n1=n2;
n2=n3;
Output:
Prime number is a number that is greater than 1 and divided by 1 or itself. In other words, prime
numbers can't be divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17, 19,
23.... are the prime numbers.
Let's see the prime number program in C#. In this C# program, we will take an input from the user
and check whether the number is prime or not.
using System;
n = int.Parse(Console.ReadLine());
m=n/2;
if(n % i == 0)
flag=1;
break;
if (flag==0)
Console.Write("Number is Prime.");
Output:
Number is Prime.
Enter the Number to check Prime: 57
We can reverse a number in C# using loop and arithmetic operators. In this program, we are getting
number as input from the user and reversing that number.
using System;
n= int.Parse(Console.ReadLine());
while(n!=0)
rem=n%10;
reverse=reverse*10+rem;
n/=10;
Output:
We can swap two numbers without using third variable. There are two common ways to swap two
numbers without using third variable:
By + and -
By * and /
Let's see a simple C# example to swap two numbers without using third variable.
using System;
Output:
Before swap a= 5 b= 10
After swap a= 10 b= 5
using System;
{
public static void Main(string[] args)
Output:
Before swap a= 5 b= 10
After swap a= 10 b= 5
Having two or more methods with same name but different in parameters, is known as method
overloading in C#.
The advantage of method overloading is that it increases the readability of the program because you
don't need to use different names for same action.
Let's see the simple example of method overloading where we are changing number of arguments of
add() method.
using System;
return a + b + c;
Console.WriteLine(Cal.add(12, 23));
Output:
35
60
C# Method Overriding
If derived class defines same method as defined in its base class, it is known as method overriding in
C#. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of
the method which is already provided by its base class.
To perform method overriding in C#, you need to use virtual keyword with base class method and
override keyword with derived class method.
Let's see a simple example of method overriding in C#. In this example, we are overriding the eat()
method by the help of override keyword.
using System;
Console.WriteLine("Eating...");
Console.WriteLine("Eating bread...");
d.eat();
Output:
Eating bread...
100.Dependency Injection (DI) is a software design pattern that helps developers build better
software. It allows us to develop loosely-coupled code that is easy to maintain. Dependency Injection
reduces the hard-coded dependencies among your classes by injecting those dependencies at run time
instead of design time technically.
Constructor Injection in C#
Construction injection is the most commonly used dependency pattern in Object Oriented
Programming. The constructor injection typically has only one parameterized constructor, so in this
constructor dependency, there is no default constructor, and we need to pass the specified value at the
time of object creation. We can use the injection component anywhere within the class. It addresses
the most common scenario where a class requires one or more dependencies.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace propertyinjuction
void print();
// constructor injection
this._text = t1;
_text.print();
class constructor
cs.print();
Console.ReadKey();
C#
Dependency Injection in C#
The builder assembled the dependencies bypassing the services that implemented the text interface.
Property Injection in C#
We use constructor injection, but there are some cases where I need a parameter-less constructor, so
we need to use property injection.
class atul {
this.task = at;
task.ActOnNotification(messages);
class Program
//oth.run();
//Console.WriteLine();
EventLogWriter elw = new EventLogWriter();
Console.ReadKey();
C#
You cannot control when the dependency is set at all. It can be changed at any point in the object's
lifetime.
Method Injection in C#
In method injection, we only need to pass the dependency in the method. The entire class does not
require dependency, just one method. I have a class with a method that has a dependency. I do not
want to use constructor injection because then I would create the dependent object every time this
class is instantiated, and most of the methods do not need this dependent object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace propertyinjuction
void print();
Console.WriteLine("print........");
this._set = serv;
Console.WriteLine("start");
this._set.print();
class method
cn.run(new servic());
Console.ReadKey();
C#
Dependency Injection in C#
A variable is a name given to a memory location and all the operations done on the variable effects
that memory location. In C#, all the variables must be declared before they can be used. It is the basic
unit of storage in a program. The value stored in a variable can be changed during program execution.
Types of Variables
Local variables
Constant Variables
Readonly Variables
Local Variables
These variables are created when the block is entered or the function is called and destroyed after
exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is declared. i.e. we can
access these variables only within that block.
Example 1:
// C# program to demonstrate
using System;
class StudentDetails {
// Method
int age = 0;
age = age + 10;
// Main Method
// Creating object
obj.StudentAge();
Output:
Student age is : 10
Instance variables are non-static variables and are declared in a class but outside any method,
constructor or block. As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed. Unlike local variables, we
may use access specifiers for instance variables.
Example:
// Instance variables
using System;
class Marks {
int engMarks;
int mathsMarks;
int phyMarks;
// Main Method
// first object
obj1.engMarks = 90;
obj1.mathsMarks = 80;
obj1.phyMarks = 93;
// second object
obj2.engMarks = 95;
obj2.mathsMarks = 70;
obj2.phyMarks = 90;
Console.WriteLine(obj1.engMarks);
Console.WriteLine(obj1.mathsMarks);
Console.WriteLine(obj1.phyMarks);
Console.WriteLine(obj2.engMarks);
Console.WriteLine(obj2.mathsMarks);
Console.WriteLine(obj2.phyMarks);
Output :
90
80
93
95
70
90
Explanation: In the above program the variables, engMarks, mathsMarks, phyMarksare instance
variables. If there are multiple objects as in the above program, each object will have its own copies
of instance variables. It is clear from the above output that each object will have its own copy of the
instance variable.
In c# programming, this is a keyword that refers to the current instance of the class. There can be 3
main usage of this keyword in C#.
It can be used to refer current class instance variable. It is used if field names (instance variables) and
parameter names are same, that is why both can be distinguish easily.
C# this example
Let's see the example of this keyword in C# that refers to the fields of current class.
using System;
this.id = id;
this.name = name;
this.salary = salary;
class TestEmployee{
e2.display();
Output:
104.C# Interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have method body and cannot be
instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully
abstraction because it cannot have method body.
Its implementation must be provided by class or struct. The class or struct which implements the
interface, must provide the implementation of all the methods declared inside the interface.
C# interface example
Let's see the example of interface in C# which has draw() method. Its implementation is provided by
two classes: Rectangle and Circle.
using System;
void draw();
Console.WriteLine("drawing rectangle...");
}
Console.WriteLine("drawing circle...");
Drawable d;
d = new Rectangle();
d.draw();
d = new Circle();
d.draw();
Output:
drawing ractangle...
drawing circle...
final
Java has final keyword, but C# does not have its implementation. For the same implementation, use
the sealed keyword.
With sealed, you can prevent overriding of a method. When you use sealed modifiers in C# on a
method, then the method loses its capabilities of overriding. The sealed method should be part of a
derived class and the method must be an overridden method.
Finally
The finally block is used to execute a given set of statements, whether an exception is thrown or not
thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
Finalize
The Finalize in C# is used to free unmanaged resources like database connections etc. The method
finalize() is for unmanaged resources.
C# if-else
In C# programming, the if statement is used to test the condition. There are various types of if
statements in C#.
if statement
if-else statement
nested if statement
if-else-if ladder
C# IF Statement
Syntax:
if(condition){
//code to be executed
}
C# If Example
using System;
if (num % 2 == 0)
Output:
It is even number
C# IF-else Statement
The C# if-else statement also tests the condition. It executes the if block if condition is true otherwise
else block is executed.
Syntax:
if(condition)
}else{
C# If-else Example
using System;
if (num % 2 == 0)
else
Output:
It is odd number
C# switch
The C# switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement in C#.
Syntax:
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
break;
C# Switch Example
using System;
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());
switch (num)
Output:
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
C# For Loop
The C# for loop is used to iterate a part of the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or do-while loops.
The C# for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization; condition; incr/decr)
//code to be executed
Flowchart:
using System;
for(int i=1;i<=10;i++){
Console.WriteLine(i);
Output:
10
3. Breaks in Loop
Code
>using System;
if( i == 4 )
break;
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
C# Do-While Loop
The C# do-while loop is used to iterate a part of the program several times. If the number of iteration
is not fixed and you must have to execute the loop at least once, it is recommended to use do-while
loop.
The C# do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do
}while(condition);
//code to be executed
}while(condition);
using System;
int i = 1;
do{
Console.WriteLine(i);
i++;
} while (i <= 10) ;
Output:
10
C# While Loop
In C#, while loop is used to iterate a part of the program several times. If the number of iteration is not
fixed, it is recommended to use while loop than for loop.
Syntax:
while(condition)
//code to be executed
Flowchart:
C# While Loop Example
using System;
int i=1;
while(i<=10)
Console.WriteLine(i);
i++;
}
}
Output:
10
C# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope of
variables and functions in the C# application.
Public
Protected
Internal
Protected internal
Private
We can choose any of these to protect our data. Public is not restricted and Private is most restricted.
The following table describes about the accessibility of each.
Access Specifier Description
Protected It specifies that access is limited to the containing class or in derived class.
protected
internal It specifies that access is limited to the current assembly or types derived from the
containing class.
It makes data accessible publicly. It does not restrict data to the declared block.
Example
using System;
namespace AccessSpecifiers
class PublicTest
class Program
{
PublicTest publicTest = new PublicTest();
publicTest.Msg("Peter Decosta");
Output:
It is accessible within the class and has limited scope. It is also accessible within sub class or child
class, in case of inheritance.
Example
using System;
namespace AccessSpecifiers
class ProtectedTest
class Program
{
protectedTest.Msg("Swami Ayyer");
Output:
Example2
using System;
namespace AccessSpecifiers
class ProtectedTest
program.Msg("Swami Ayyer");
Output:
Hello Shashikant
The internal keyword is used to specify the internal access specifier for the variables and functions.
This specifier is accessible only within files in the same assembly.
Example
using System;
namespace AccessSpecifiers
class InternalTest
class Program
internalTest.Msg("Peter Decosta");
Output:
freestar
Variable or function declared protected internal can be accessed in the assembly in which it is
declared. It can also be accessed within a derived class in another assembly.
Example
using System;
namespace AccessSpecifiers
class InternalTest
class Program
internalTest.Msg("Peter Decosta");
Output:
Private Access Specifier is used to specify private accessibility to the variable or function. It is most
restrictive and accessible only within the body of class in which it is declared.
Example
using System;
namespace AccessSpecifiers
class PrivateTest
class Program
privateTest.Msg("Peter Decosta");
Output:
using System;
namespace AccessSpecifiers
class Program
program.Msg("Peter Decosta");
Output:
A Composite Key also can be created by combining more than one Candidate Key.
When the database table doesn’t have any column which is alone capable of identifying a unique row
(or a record) from the table, then we might need two or more two fields/columns to get a unique
record/row from the table.
Syntax
Note − Here the COMPOSITE_KEY_NAME is the name of the Composite Key in a table. It is
optional to specify this. It comes handy when you want to drop the composite key constraint from the
column of the table.
Example
In the following example, we are trying to create a table named CUSTOMERS with multiple
columns, and while creating the table will pass two columns named ADHARCARD_ID and
MOBILE_NO to the PRIMARY KEY (ADHARCARD_ID, MOBILE_NO) to create a composite key
on these columns.
ADHARCARD_ID BIGINT,
MOBILE_NO BIGINT,
);
Output
(0 rows affected)
The Hashtable class represents a collection of key-and-value pairs that are organized based on the
hash code of the key. It uses the key to access the elements in the collection.
A hash table is used when you need to access elements by using key, and you can identify a useful
key value. Each item in the hash table has a key/value pair. The key is used to access the items in the
collection.
The following table lists some of the commonly used properties of the Hashtable class −
Count
Gets the number of key-and-value pairs contained in the Hashtable.
IsFixedSize
IsReadOnly
Item
Keys
Values
Example
Live Demo
using System;
using System.Collections;
namespace CollectionsApplication {
class Program {
if (ht.ContainsValue("Nuha Ali")) {
} else {
Console.ReadKey();
When the above code is compiled and executed, it produces the following result −
005: M. Amlan
006: M. Arif
DML commands are used to modify the database. It is responsible for all form of changes in the
database.
The command of DML is not auto-committed that means it can't permanently save all the changes in
the database. They can be rollback.
INSERT
UPDATE
DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.
Syntax:
freestar
Or
For example:
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
For example:
UPDATE students
Syntax:
For example:
WHERE Author="Sonoo";
DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
All the command of DDL are auto-committed that means it permanently save all the changes in the
database.
CREATE
ALTER
DROP
TRUNCATE
a. CREATE It is used to create a new table in the database.
Syntax:
Example:
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
Example
c. ALTER: It is used to alter the structure of the database. This change could be either to modify the
characteristics of an existing attribute or probably to add a new attribute.
Syntax:
EXAMPLE
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
Syntax:
The SELECT statement is the most commonly used command in Structured Query Language. It is
used to access the records from one or more database tables and views. It also retrieves the selected
data that follow the conditions we want.
TRUNCATE vs DELETE
Even though the TRUNCATE and DELETE commands work similar logically, there are some major
differences that exist between them. They are detailed in the table below.
The DELETE command in SQL removes one or more rows from a table based on the conditions
specified in a WHERE Clause.
There is a need to make a manual COMMIT after making changes to the DELETE command, for the
modifications to be committed.
It deletes rows one at a time and applies same criteria to each deletion.
If there is an identity column, the table identity is not reset to the value it had when the table was
created.
TRUNCATE:
SQL's TRUNCATE command is used to remove all of the rows from a table, regardless of whether or
not any conditions are met.
TRUNCATE utilizes a table lock, which locks the pages so they cannot be deleted.
The only activity recorded is the deallocation of the pages on which the data is stored.
It is much faster.
The SQL TRUNCATE TABLE command is used to empties a table completely. This command is a
sequence of DROP TABLE and CREATE TABLE statements and requires the DROP privilege.
You can also use DROP TABLE command to delete a table but it will remove the complete table
structure from the database and you would need to re-create this table once again if you wish you
store some data again.
Syntax
The SQL DELETE is a command of Data Manipulation Language (DML), so it does not delete or
modify the table structure but it delete only the data contained within the table. Therefore, any
constraints, indexes, or triggers defined in the table will still exist after you delete data from it.
The SQL DELETE TABLE statement is used to delete the existing records from a table in a database.
If you wish to delete only the specific number of rows from the table, you can use the WHERE clause
with the DELETE statement. If you omit the WHERE clause, all rows in the table will be deleted. The
SQL DELETE statement operates on a single table at a time.
Syntax
Following is the basic syntax for using the SQL DELETE command in SQL −
We can use the SQL DELETE statement to delete specific rows from a table based on a single
condition using the WHERE clause.
Syntax
Following is the syntax for deleting specific rows based on single condition −
WHERE condition;
A data type specifies the type of data that a variable can store such as integer, floating, character etc.
The value data types are integer-based and floating-point based. C# language supports both signed
and unsigned literals.
The memory size of data types may change according to 32 or 64 bit operating system.
Let's see the value data types. It size is given according to 32 bit OS.
decimal 16 byte at least -7.9 * 10?28 - 7.9 * 1028, with at least 28-digit precision
The reference data types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
If the data is changed by one of the variables, the other variable automatically reflects this change in
value.
The pointer in C# language is a variable, it is also known as locator or indicator that points to an
address of a value.
CSHRAP Data types 2
Declaring a pointer
A CTE is a one-time result set, meaning a temporary table that only exists for the duration of the
query. It enables us to refer to the data within the execution scope of a single SELECT, UPDATE,
INSERT, DELETE, CREATE, VIEW, OR MERGE statement. CTE is temporary because it cannot be
stored anywhere; once the query is executed, it can be lost as soon as possible.
It first came with SQL server 2005. A dba always preferred CTE to use an alternative to a
subquery/view. They follow ANSI SQL 99 and are SQL-compliant.
CTEs can make it easier to manage and write complex queries by making them more readable and
simple, like database views and derived tables. We can reuse or rewrite the query by breaking down
the complex queries into simple blocks.
Syntax
The CTE syntax consists of a CTE name, a statement query that defines a column table expression,
and an optional column list. We can use it as a view in SELECT, INSERT, UPDATE, DELETE, and
merge queries after defining it.
Following diagram is the representation of the query definition −
CTE
Note − While writing the CTE query definition; we can use the following commands.
INTO
Option clause
FOR BROWSE
Example
In the following example, let’s see how CTE will work in SQL Server. In this case, we'll use the
customer table and perform CTE on it.
+------+----------+------+-----------+--------+
+------+----------+------+-----------+--------+
+------+----------+------+-----------+--------+
WITH customer_AGE
Since we've created a common table expression called customer AGE, when the above query is
executed, we receive an ID, name, and age from CTE, and that age is equal to 23.
+------+---------+------+
| ID | NAME | AGE |
+------+---------+------+
| 2 | Aman | 23 |
| 3 | kaushik | 23 |
128.A Subquery or Inner query or a Nested query is a query within another SQL query and embedded
within clauses, most commonly in the WHERE clause. It is used to return data from a table, and this
data will be used in the main query as a condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
A subquery can have only one column in the SELECT clause, unless multiple columns are in the main
query for the subquery to compare its selected columns.
An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER
BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a
subquery.
Subqueries that return more than one row can only be used with multiple value operators such as the
IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB,
or NCLOB.
The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be
used within the subquery.
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −
[WHERE])
Class v/s Id
The selectors in CSS are part of the CSS ruleset and used to select the content we want to style. Id and
class both are the CSS element selectors and are used to identify an element based on its assigned
name. CSS id and class selectors are the most used selectors in CSS.
During the use of selectors, sometimes there is confusion occurs between id and class. Both of them
do not have any default styling information; they require CSS to select them and apply it to style.
Although both are used for selecting the element, they are different from each other in many ways.
129.Class
We can apply a class to various elements so that it could be numerous times on a single page.
The class is assigned to an element and its name starts with "." followed by the name of the class
Syntax:
.class{
// declarations of CSS
Id
The Id is unique in a page, and we can only apply it to one specific element.
.The name of the Id starts with the "#" symbol followed by a unique id name.
Syntax:
#id{
// declarations of CSS
Bootstrap Container
In Bootstrap, container is used to set the content's margins dealing with the responsive behaviors of
your layout. It contains the row elements and the row elements are the container of columns (known
as grid system).
container
container-fluid
<html>
<body>
<div class="container">
<div class="row">
<div class="col-md-xx"></div>
...
</div>
<div class="row">
<div class="col-md-xx"></div>
...
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Job</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
</head>
<body>
<div class="container">
<h1>Container</h1>
<p>container content</p>
</div>
<div class="container-fluid">
<h1>Container-fluid</h1>
<p>container-fluid content</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</body>
</html>
2. Range validation: Ensures that a field's value falls within a specific range.
3. Regular expression validation: Ensures that a field's value matches a specific pattern.
4. Compare validation: Compares the value of one field with another field's value.
Full stack development is the process of designing, creating, testing, and deploying a complete web
application from start to finish. It involves working with various technologies and tools, including
front-end web development, back-end web development, and database development.
Html:
definition :A hypertext markup language (HTML) is the primary language for developing web pages.
Multimedia support: Language in HTML does not have support for video and audio.
Browser compatibility: HTML is compatible with almost all browsers because it has been present for
a long time, and the browser made modifications to support all the features.
Graphics support: In HTML, vector graphics are possible with tools LikeSilver light, Adobe
Flash, VML, etc
Threading: In HTML, the browser interface and JavaScript running in the same thread.
Vector and Graphics: Vector graphics are possible with the help of technologies like VML,
Silverlight, Flash,etc.
<! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.01 // EN"
"http://www.w3.org/TR/html4/strict.dtd">
<! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.0 Transitional // EN">
Html5: HTML5 is a new version of HTML with new functionalities with markup language with
Internet technologies.
HTML5 has the storage options like:application cache, SQL database, and web storage.
In HTML5, we have many new tags, elements, and some tags that have been removed/modified, so
only some browsers are fully compatible with HTML5.
The HTML5 has the JavaScript Web Worker API, which allows the browser interface to run in
multiple threads.
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and
servers.
Example: A client (browser) sends an HTTP request to the server; then the server returns a response
to the client. The response contains status information about the request and may also contain the
requested content.
HTTP Methods
GET,POST,PUT,HEAD,DELETE,PATCH,OPTIONS,CONNECT,TRACE
The two most common HTTP methods are: GET and POST.
Note that the query string (name/value pairs) is sent in the URL of a GET request:
/test/demo_form.php?name1=value1&name2=value2
GET requests should never be used when dealing with sensitive data
Host: w3schools.com
name1=value1&name2=value2
Definition:
Stored procedure is a pre compiled statement, it will have a faster execution when compared to a
normal query. A normal query will get compiled and get executed where as stored procedure is pre-
compiled statement, it will only execute. The operation will be very fast.
as Begin
End
Statements
Exec procedure_name
• A Stored Procedure can be stored for later use and can used many times.
• Stored procedures can reduce network traffic between clients and servers, because the
commands are executed as a single batch of code.
Question 2: Write a query to create a view(bill pdt) and to display the created view for the table
tbl_product-Columns product Name,quantity.
Definition: A view is a virtual table (Used to enhance security) and it can be QUERIED, UPDATED,
INSERTED INTO, DELETED FROM and JOINED with other tables and views. A view is a data
object which does not contain any data. Its contents are the resultant of a base table.
SYNTAX
select column1,column2,....
from table_name
Indexing
An index is used to retrieve the data faster because it will rearrange the data in the database in an
orderly manner. The create index statement is used to create indexes in tables.
SYNTAX:
ON table_Name(column_Name).
No null value
It will create clustered index automatically Why only one primary key?
If more than one primary key, the table will Get confused in which order it needs to put the data.
137.C# Polymorphism
The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a
greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation and
polymorphism.
There are two types of polymorphism in C#: compile time polymorphism and runtime polymorphism.
Compile time polymorphism is achieved by method overloading and operator overloading in C#. It is
also known as static binding or early binding. Runtime polymorphism in achieved by method
overriding which is also known as dynamic binding or late binding.
A configuration file (web.config) is used to manage various settings that define a website. The
settings are stored in XML files that are separate from your application code. In this way you can
configure settings independently from your code. Generally a website contains a single Web.config
file stored inside the application root directory. However there can be many configuration files that
manage settings at various levels within an application.
ASP.NET Configuration system is used to describe the properties and behaviors of various aspects of
ASP.NET applications. Configuration files help you to manage the many settings related to your
website. Each file is an XML file (with the extension .config) that contains a set of configuration
elements. Configuration information is stored in XML-based text files.
<configuration>
<connectionStrings>
<add name="myCon"
connectionString="server=MyServer;database=puran;uid=puranmehra;pwd=mydata1223" />
</connectionStrings>
</configuration/>
139.Method Overloading
With method overloading, multiple methods can have the same name with different parameters:
int MyMethod(int x)
float MyMethod(float x)
Example
return x + y;
return x + y;
Int: 13
Double: 10.559999999999999
If derived class defines same method as defined in its base class, it is known as method overriding in
C#. It is used to achieve runtime polymorphism. It enables you to provide specific implementation of
the method which is already provided by its base class.
To perform method overriding in C#, you need to use virtual keyword with base class method and
override keyword with derived class method.
C# Method Overriding Example
Let's see a simple example of method overriding in C#. In this example, we are overriding the eat()
method by the help of override keyword.
using System;
Console.WriteLine("Eating...");
Console.WriteLine("Eating bread...");
d.eat();
Output:
Eating bread...
C# Strings
In C#, string is an object of System.String class that represent sequence of characters. We can perform
many operations on strings such as concatenation, comparision, getting substring, search, trim,
replacement etc.
string vs String
In C#, string is keyword which is an alias for System.String class. That is why string and String are
equivalent. We are free to use any naming convention.
C# String Example
using System;
string s1 = "hello";
Console.WriteLine(s1);
Console.WriteLine(s2);
Output:
hello
csharp
143.C# Exception Handling
In C#, exception is an event or object which is thrown at runtime. All exceptions the derived from
System.Exception class. It is a runtime error which can be handled. If we don't handle the exception,
it prints exception message and terminates the program.
Advantage
It maintains the normal flow of the application. In such case, rest of the code is executed event after
exception.
C# Exception Classes
All the exception classes in C# are derived from System.Exception class. Let's see the list of C#
common exception classes.
Exception Description
try
catch
finally, and
throw.
144.The finally keyword is used as a block to execute a given set of statements, whether an exception
is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is
raised or not.
Syntax
try {
} catch( ExceptionName e1 ) {
} catch( ExceptionName e2 ) {
} catch( ExceptionName eN ) {
} finally {
// statements to be executed
Example
Live Demo
using System;
int result;
Demo() {
result = 0;
}
try {
} catch (DivideByZeroException e) {
} finally {
d.division(100, 0);
Output
0kebv45.0.cs:line 11
Result = 0
145.C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type
variable that holds the reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates are
implicitly derived from the System.Delegate class.
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A delegate can
refer to a method, which has the same signature as that of the delegate.
For example, consider a delegate −
The preceding delegate can be used to reference any method that has a single string parameter and
returns an int type variable.
Instantiating Delegates
Once a delegate type is declared, a delegate object must be created with the new keyword and be
associated with a particular method. When creating a delegate, the argument passed to the new
expression is written similar to a method call, but without the arguments to the method. For example
−
...
Following example demonstrates declaration, instantiation, and use of a delegate that can be used to
reference methods that take an integer parameter and returns an integer value.
Live Demo
using System;
namespace DelegateAppl {
class TestDelegate {
num += p;
return num;
num *= q;
return num;
return num;
nc1(25);
nc2(5);
Console.ReadKey();
When the above code is compiled and executed, it produces the following result −
Value of Num: 35
Value of Num: 175
145.C# Strings
Elements can be added or removed from the Array List collection at any point in time.
The capacity of an ArrayList is the number of elements the ArrayList can hold.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-
based.
Constructors
Constructor Description
ArrayList() Initializes a new instance of the ArrayList class that is empty and has the default
initial capacity.
ArrayList(ICollection) Initializes a new instance of the ArrayList class that contains elements copied
from the specified collection and that has the same initial capacity as the number of elements copied.
ArrayList(Int32) Initializes a new instance of the ArrayList class that is empty and has the
specified initial capacity.
Example:
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
// Driver code
// Creating an ArrayList
myList.Add("Hello");
myList.Add("World");
Output:
Count : 2
Capacity : 4
The Array class gives methods for creating, manipulating, searching, and sorting arrays. The Array
class is not part of the System.Collections namespace, but it is still considered as a collection because
it is based on the IList interface. The Array class is the base class for language implementations that
support arrays.
In Array, the elements are the value of the array and the length of the array is the total number of item
present in the array.
The lower bound of an Array is the index of its first element and the default value of the lower bound
is 0.
Array objects with the same array type share the same Type object.
Example:
using System;
namespace geeksforgeeks {
class GFG {
// Main Method
{
// declares an 1D Array of string
string[] store;
Console.WriteLine();
Output:
Americano,
Cafe au lait,
Espresso,
Cappuccino,
Long Black,
Macchiato
C# Interface
Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are
declared inside the interface are abstract methods. It cannot have method body and cannot be
instantiated.
It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully
abstraction because it cannot have method body.
Its implementation must be provided by class or struct. The class or struct which implements the
interface, must provide the implementation of all the methods declared inside the interface.
C# interface example
Let's see the example of interface in C# which has draw() method. Its implementation is provided by
two classes: Rectangle and Circle.
using System;
void draw();
Console.WriteLine("drawing rectangle...");
Console.WriteLine("drawing circle...");
Drawable d;
d = new Rectangle();
d.draw();
d = new Circle();
d.draw();
Output:
drawing ractangle...
drawing circle...
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be
inherited from another class).
No, we can't create an object of an abstract class. But we can create a reference variable of an abstract
class. The reference variable is used to refer to the objects of derived classes (subclasses of abstract
class).
An abstract class means hiding the implementation and showing the function definition to the user is
known as Abstract class. A Java abstract class can have instance methods that implement a default
behavior if we know the requirement and partially implementation we can go for an abstract class.
Example
Live Demo
double dim1;
double dim2;
Diagram(double a, double b) {
dim1 = a;
dim2 = b;
Rectangle(double a, double b) {
super(a, b);
double area() {
Triangle(double a, double b) {
super(a, b);
double area() {
System.out.println("Inside Area for Triangle.");
diagRef = r;
diagRef = t;
In the above example, we cannot create the object of type Diagram but we can create a reference
variable of type Diagram. Here we created a reference variable of type Diagram and the Diagram
class reference variable is used to refer to the objects of the class Rectangle and Triangle.
Output
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be
used for creating web services. REST API is a way of accessing web services in a simple and flexible
way without having any processing.
REST API
REST technology is generally preferred to the more robust Simple Object Access Protocol (SOAP)
technology because REST uses less bandwidth, simple and flexible making it more suitable for
internet usage. It’s used to fetch or give some information from a web service. All communication
done via REST API uses only HTTP request.
Working: A request is sent from client to server in the form of a web URL as HTTP GET or POST or
PUT or DELETE request. After that, a response comes back from the server in the form of a resource
which can be anything like HTML, XML, Image, or JSON. But now JSON is the most popular format
being used in Web Services.
Build REST API Mastery Learn to integrate popular and practical Python REST APIs in Django web
applications with Educative’s interactive skill path Become a Python-based API Integrator. Sign up at
Educative.io with the code GEEKS10 to save 10% on your subscription.
In HTTP there are five methods that are commonly used in a REST-based Architecture i.e., POST,
GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD)
operations respectively. There are other methods which are less frequently used like OPTIONS and
HEAD.
GET: The HTTP GET method is used to read (or retrieve) a representation of a resource. In the safe
path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an
error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).
POST: The POST verb is most often utilized to create new resources. In particular, it’s used to create
subordinate resources. That is, subordinate to some other (e.g. parent) resource. On successful
creation, return HTTP status 201, returning a Location header with a link to the newly-created
resource with the 201 HTTP status.
PUT: It is used for updating the capabilities. However, PUT can also be used to create a resource in
the case where the resource ID is chosen by the client instead of by the server. In other words, if the
PUT is to a URI that contains the value of a non-existent resource ID. On successful update, return
200 (or 204 if not returning any content in the body) from a PUT. If using PUT for create, return
HTTP status 201 on successful creation. PUT is not safe operation but it’s idempotent.
PATCH: It is used to modify capabilities. The PATCH request only needs to contain the changes to
the resource, not the complete resource. This resembles PUT, but the body contains a set of
instructions describing how a resource currently residing on the server should be modified to produce
a new version. This means that the PATCH body should not just be a modified part of the resource,
but in some kind of patch language like JSON Patch or XML Patch. PATCH is neither safe nor
idempotent.
DELETE: It is used to delete a resource identified by a URI. On successful deletion, return HTTP
status 200 (OK) along with a response body.
An exception is an unexpected event that occurs during program execution. For example,
int divideByZero = 7 / 0;
C# Exception Hierarchy
exception hierarchy in C#
The above image shows the exception hierarchy in C#. C# provides a base class named Exception
which is later derived into other classes.
The major two exception classes derived from the Exception class are:
The built-in exceptions are also called SystemException exceptions. In C#, all the built-in exception
classes are derived from the SystemException class. This class handles all the system-related
exceptions.
1. StackOverflowException - This exception is thrown when the execution stack exceeds the stack
size. Normally occurs when we use an infinite loop in the program.
OverFlowException - This exception is thrown when the result produced by the operation is out of
range. For example,
3. ValidationException - This exception is thrown when an input value is not valid. For example, if
we enter an integer value in a field that expects a DateTime value, this exception is thrown.
4. ArgumentException - This exception is thrown when we provide one invalid argument in a method.
For example, when we pass an argument of a data type that doesn't match specified parameters during
a method's call, then this exception occurs.
Example: C# SystemException
using System;
class Program
Console.WriteLine(colors[3]);
Output
In the above example, we are trying to access the index 3 element of the colors array element.
C# User-defined Exception
Till now we learned about built-in exceptions in C#. We can also create user-defined exceptions
which are known as Application level exceptions.
The ApplicationException class is the base class from which we can derive application-level
exceptions.
Suppose we want to create an exception in an application that does not allow the age of a participant
to be more than 18. Let's name that exception - InvalidAgeException.
To create the InvalidAgeException exception, we derive it from the ApplicationException class as,
{
// constructor for the InvalidAgeException class
InvalidAgeException()
Here, we have defined a user-defined exception class named InvalidAgeException which is derived
from the ApplicationException class.
We can write custom codes inside user-defined InvalidAgeException class and define the nature of
that exception class.
Now we can raise the InvalidAgeException exception whenever the age restriction is violated.
Errors represent conditions such as compilation error, syntax error, error in the logical part of the
code, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer and we should not try to handle errors.
Now we know about exceptions, we will learn about External Handling in the next tutorial.
SQL Join is used to combine two or more tables in a database based on a related column between
them. There are several types of SQL Join, each with its own uses and characteristics.
Inner Join: An Inner Join returns only the rows that have matching values in both tables being joined.
This is the most common type of join, and it is used when you want to extract data from two tables
that are related to each other.
Left Join: A Left Join returns all the rows from the left table and the matching rows from the right
table. If there are no matching rows in the right table, the result will contain NULL values for the
columns from the right table.
Right Join: A Right Join returns all the rows from the right table and the matching rows from the left
table. If there are no matching rows in the left table, the result will contain NULL values for the
columns from the left table.
Full Outer Join: A Full Outer Join returns all the rows from both tables and includes NULL val the
columns where there is no match.
Cross Join: A Cross Join returns the Cartesian product of the two tables, which means that it all the
possible combinations of rows from both tables. This type of join is used when you need combine
every row from one table with every row from another table.
In MVC, routing is a process of mapping the browser request to the controller action and return
response back. Each MVC application has default routing for the default HomeController. We can set
custom routing for newly created controller.
The RouteConfig.cs file is used to set routing for the application. Initially it contains the following
code.
// RouteConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplicationDemo
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
);
According to this setup file, Index action of Home controller will be treated as default. First time,
when application runs it produces the following output.
C# Example
@{
The greeting is: Welcome to our site! Here in Huston it is: Friday
It is a dynamic property which is similar to ViewData. It was introduced in .NET Framework version
4.0. it is used to send data from controller to the view page. ViewBag can get and set value
dynamically that's why it is called dynamic property. It does not require type conversion and convert
type dynamically.
ASP.NET MVC TempData
It represents a set of data that persists only from one request to the next. It is derived from
TempDataDictionary, we can use its object to pass data as we did in ViewData. The value of
TempData persists only from one request to the next. Retention is used to mark key to persist data so
that it can retain for the next request.
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values
in other columns in the row.
FirstName varchar(255),
);
AJAX allows you to send and receive data asynchronously without reloading the web page. So it is
fast.
AJAX allows you to send only important information to the server not the entire page. So only
valuable data from the client side is routed to the server side. It makes your application interactive and
faster.
Where it is used?
There are too many web applications running on the web that are using ajax technology like gmail,
facebook,twitter, google map, youtube etc.
deploying, and
It is a comprehensive platform that includes a large library of pre-written code and tools for
developing and running applications operating systems. I
1. Common Language Runtime (CLR): The CLR provides the runtime environment for
executing .NET code. It manages memory, performs garbage collection, and provides other essential
services to .NET applications.
2. Class Library: The .NET Class Library is a large collection of pre-written code that developers can
use to build applications. It includes classes for working with strings, files, networking, graphics, and
more.
3. Development Tools: The .NET Framework includes a set of development tools such as Visual
Studio, which is a powerful Integrated Development Environment (IDE) used for creating .NET
applications. Other tools include compilers, debuggers, and performance profiling tools.
The .NET Framework supports multiple programming languages such as C#, Visual Basic, and F#
and is designed to simplify the development of complex applications by providing a consistent and
reliable framework for developers to work with. It also includes features such as automatic memory
management, type safety, and code access security that help developers write safer and more robust
applications.
In ASP.NET MVC, a user request is routed to the appropriate controller and action method. However,
there may be circumstances where you want to execute some logic before or after an action method
executes. ASP.NET MVC provides filters for this purpose.
ASP.NET MVC Filter is a custom class where you can write custom logic to execute before or after
an action method executes. Filters can be applied to an action method or controller in a declarative or
programmatic way. Declarative means by applying a filter attribute to an action method or controller
class and programmatic means by implementing a corresponding interface.
MVC provides different types of filters. The following table list filter types, built-in filters, and
interface that must be implemented to create custom filters.
Action filters: Performs some operation before and after an action method executes.
IActionFilter
Result filters: Performs some operation before or after the execution of the view.
[OutputCache] IResultFilter
Exception filters: Performs some operation if there is an unhandled exception thrown during
the execution of the ASP.NET MVC pipeline. [HandleError] IExceptionFilter
The MVC View is a standard HTML page that may contain script. It is used to create web pages for
the application. Unlike ASP.NET Web Pages, MVC Views are mapped to the action and then
controller renders the view to the browser.
MVC has certain conventions for project structure. The view file should be located in the subdirectory
of View folder.
MVC uses Razor view engine so that we can write server side code in HTML as well. Let's create a
view and execute it to the browser.
To add view, right click on the subfolder inside the View folder and select Add-> Add View. It will
pop up for the view name etc.
Action Result is actually a data type. When it is used with action method, it is called return type. As
you know, an action is referred to as a method of the controller, the Action Result is the result of
action when it executes. In fact, Action Result is a return type. This return type has many other
derived types. First, look at the base and derived types of ActionResult.
namespace System.Web.Mvc
//
// Summary:
168.Get
Data is passed from client in the form of Url and Url data is visible to every user if you are submitting
any form then data which you are passing will be visible in Url ,so this will not safe. also we have
some restrictions on that you can pass only 1024 characters in the case of Get.
Post
On the case of post Method data will be passed through http headers so using secure http protocol and
data will be more secure and also we have no data restriction there we can pass large number of data
and binary data we can pass here also.
Web API is the enhanced form of the web application to provide services on different devices like
laptop, mobile, and others.
Today, all kind of businesses use the internet as a cost-effective way to expand their business in the
international market.
Web application helps to exchange information on the internet and also helps to perform a secure
transaction on web sites.
Web applications are popular as the web browser is available in default, we don't need any installation
of software on computers with operating systems.
For example, Facebook (a social networking web application), Flickr (a photo-sharing web
application), and Wikipedia are majorly used example of a web application.
1) Client-side scripts: JavaScript, HTML, and other client-side scripting languages are used to design
the web forms to present information to users.
2) Server-side scripts: ASP and other server-side scripting languages are used to perform business
logic and database related operations like storing and retrieving information.
Web Browsers
Mobile applications
Desktop applications
"ASP.NET Web API is an extensible framework for building HTTP (Hypertext Transfer Protocol)
services that can be accessed from any client such as browsers and mobile devices."
View State is one of the methods of the ASP.NET page framework used to preserve and store the
page and control values between round trips. It is maintained internally as a hidden field in the form
of an encrypted value and a key.
Default enables the View State for a page. When the browser renders the HTML markup, the current
state and the page values are retained and serialized into base64-encoded strings.
The View State methods differ from the cache and cookies because the cookies are accessible from all
the pages on your website, while the View State values are non-transferable, and thus you cannot
access from different pages.
The view state persists the ASP.NET page framework's control settings between post-backs and
sessions. You can use the view state to do the following:
Retain the control value on a page without storing them in a user profile or session state.
Store page values and control properties that you set or define on a page.
Create a custom View State Provider to store the view page information in a SQL Server Database or
another database.
What are the Data Objects that can be stored in the View State?
View State can handle several data objects. A few of them are:
String
Boolean Value
Array Object
Hash Table
It's possible to store other data types too. The only condition is that you must compile the class with
the Serializable attribute to serialize the values for View State.
ASP.NET Session
In ASP.NET session is a state that is used to store and retrieve values of a user.
It helps to identify requests from the same browser during a time period (session). It is used to store
value for the particular time session. By default, ASP.NET session state is enabled for all ASP.NET
applications.
Each created session is stored in SessionStateItemCollection object. We can get current session value
by using Session property of Page object. Let's see an example, how to create an access session in
asp.net application.
C# Sharp Code:
using System;
{
public static void Main()
Console.Write("\n\n");
Console.Write("---------------------------------------");
Console.Write("\n\n");
num1= Convert.ToInt32(Console.ReadLine());
rem1 = num1 % 2;
if (rem1 == 0)
else
Sample Output:
---------------------------------------
Input an integer : 10
10 is an even integer.
C# Serialization
In C#, serialization is the process of converting object into byte stream so that it can be saved to
memory, file or database. The reverse process of serialization is called deserialization.
C# SerializableAttribute
To serialize the object, you need to apply SerializableAttribute attribute to the type. If you don't apply
SerializableAttribute attribute to the type, SerializationException exception is thrown at runtime.
C# Serialization example
Let's see the simple example of serialization in C# where we are serializing the object of Student
class. Here, we are going to use BinaryFormatter.Serialize(stream, reference) method to serialize the
object.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Student
int rollno;
string name;
this.rollno = rollno;
this.name = name;
{
FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);
formatter.Serialize(stream, s);
stream.Close();
sss.txt:
C# Deserialization
In C# programming, deserialization is the reverse process of serialization. It means you can read the
object from byte stream. Here, we are going to use BinaryFormatter.Deserialize(stream) method to
deserialize the stream.
C# deserialization
C# Deserialization Example
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Student
this.rollno = rollno;
this.name = name;
Student s=(Student)formatter.Deserialize(stream);
stream.Close();
Output:
Rollno: 101
Name: sonoo
A SQL DROP TABLE statement is used to delete a table definition and all data from a table.
This is very important to know that once a table is deleted all the information available in the table is
lost forever, so we have to be very careful when using this command.
Let's see the syntax to drop the table from the database.
A truncate SQL statement is used to remove all rows (complete data) from a table. It is similar to the
DELETE statement with no WHERE clause.
Truncate table is faster and uses lesser resources than DELETE TABLE command.
Drop table command can also be used to delete complete table but it deletes table structure too.
TRUNCATE TABLE doesn't delete the structure of the table.
Let's see the syntax to truncate the table from the database.
For example, you can write following command to truncate the data of employee table
Note: The rollback process is not possible after truncate table statement. Once you truncate a table
you cannot use a flashback table statement to retrieve the content of the table.
Whenever we want to sort the records based on the columns stored in the tables of the SQL database,
then we consider using the ORDER BY clause in SQL.
The ORDER BY clause in SQL will help us to sort the records based on the specific column of a
table. This means that all the values stored in the column on which we are applying ORDER BY
clause will be sorted, and the corresponding column values will be displayed in the sequence in which
we have obtained the values in the earlier step.
Using the ORDER BY clause, we can sort the records in ascending or descending order as per our
requirement. The records will be sorted in ascending order whenever the ASC keyword is used with
ORDER by clause. DESC keyword will sort the records in descending order.
If no keyword is specified after the column based on which we have to sort the records, in that case,
the sorting will be done by default in the ascending order.
Before writing the queries for sorting the records, let us understand the syntax.
Syntax to sort the records in ascending order:
Query:
The GROUP BY statement groups rows that have the same values into summary rows, like "find the
number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(),
SUM(), AVG()) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
FROM Customers
GROUP BY Country;
SELECT column_name(s)
FROM table1
ON table1.column_name = table2.column_name;
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
SQL Injection
SQL injection is a code injection technique that might destroy your database.
SQL injection is the placement of malicious code in SQL statements, via web page input.
SQL injection usually occurs when you ask a user for input, like their username/userid, and instead of
a name/id, the user gives you an SQL statement that you will unknowingly run on your database.
Look at the following example which creates a SELECT statement by adding a variable (txtUserId) to
a select string. The variable is fetched from user input (getRequestString):
txtUserId = getRequestString("UserId");
FROM table_name
FROM Geek
GROUP BY A, B
Normalization
A large database defined as a single relation may result in data duplication. This repetition of data
may result in:
Making relations very large.
It isn't easy to maintain and update data as it would involve searching many records in relation.
So to handle these problems, we should analyze and decompose the relations with redundant data into
smaller, simpler, and well-structured relations that are satisfy desirable properties. Normalization is a
process of decomposing the relations into relations with fewer attributes.
What is Normalization?
Normalization is used to minimize the redundancy from a relation or set of relations. It is also used to
eliminate undesirable characteristics like Insertion, Update, and Deletion Anomalies.
Normalization divides the larger table into smaller and links them using relationships.
The normal form is used to reduce redundancy from the database table.
The main reason for normalizing the relations is removing these anomalies. Failure to eliminate
anomalies leads to data redundancy and can cause data integrity and other problems as the database
grows. Normalization consists of a series of guidelines that helps to guide you in creating a good
database structure.
Advertisement
Insertion Anomaly: Insertion Anomaly refers to when one cannot insert a new tuple into a relationship
due to lack of data.
Deletion Anomaly: The delete anomaly refers to the situation where the deletion of data results in the
unintended loss of some other important data.
Updatation Anomaly: The update anomaly is when an update of a single data value requires multiple
rows of data to be updated.
Normalization works through a series of stages called Normal forms. The normal forms apply to
individual relations. The relation is said to be in particular normal form if it satisfies constraints.
DBMS Normalization
2NF- A relation will be in 2NF if it is in 1NF and all non-key attributes are fully functional
dependent on the primary key.
4NF- A relation will be in 4NF if it is in Boyce Codd's normal form and has no multi-valued
dependency.
5NF- A relation is in 5NF. If it is in 4NF and does not contain any join dependency, joining should
be lossless.
Advantages of Normalization
Disadvantages of Normalization
You cannot start building the database before knowing what the user needs.
The performance degrades when normalizing the relations to higher normal forms, i.e., 4NF, 5NF.
Careless decomposition may lead to a bad database design, leading to serious problems.
Stored procedure is a pre compiled statement, it will have a faster execution when compared to a
normal query. A normal query will get compiled and get executed where as stored procedure is pre-
compiled statement, it will only execute. The operation will be very fast.
as Begin
End
Statements
Exec procedure_name
• A Stored Procedure can be stored for later use and can used many times.
• Stored procedures can reduce network traffic between clients and servers, because the
commands are executed as a single batch of code.
Question 2: Write a query to create a view(bill pdt) and to display the created view for the table
tbl_product-Columns product Name,quantity.
Definition: A view is a virtual table (Used to enhance security) and it can be QUERIED, UPDATED,
INSERTED INTO, DELETED FROM and JOINED with other tables and views. A view is a data
object which does not contain any data. Its contents are the resultant of a base table.
SYNTAX
select column1,column2,....
from table_name
Indexing
An index is used to retrieve the data faster because it will rearrange the data in the database in an
orderly manner. The create index statement is used to create indexes in tables.
SYNTAX:
ON table_Name(column_Name).
Usage: An index is used to speed up the performance of fetching the data.
No null value
It will create clustered index automatically Why only one primary key?
If more than one primary key, the table will Get confused in which order it needs to put the data.
Trigger:
A SQL trigger is a database object which fires when an event occurs in a database.
ON table_name
WHEN (condition)
[trigger_body]