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

Interview Question Full 2

The document discusses various SQL clauses and their usage: - WHERE clause filters records retrieved from one or more tables. GROUP BY clause groups rows based on column values. HAVING clause filters grouped results based on aggregate functions. ORDER BY clause sorts result sets by column(s). - DataReader reads data from a database and allows forward-only and read-only access. DataSet provides disconnected data access with tables and relations. DataAdapter acts as a bridge between a DataSet and database, populating the DataSet.

Uploaded by

manikandan raja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Interview Question Full 2

The document discusses various SQL clauses and their usage: - WHERE clause filters records retrieved from one or more tables. GROUP BY clause groups rows based on column values. HAVING clause filters grouped results based on aggregate functions. ORDER BY clause sorts result sets by column(s). - DataReader reads data from a database and allows forward-only and read-only access. DataSet provides disconnected data access with tables and relations. DataAdapter acts as a bridge between a DataSet and database, populating the DataSet.

Uploaded by

manikandan raja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 142

66.

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.

Different clauses available in the Structured Query Language are as follows:

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

The syntax for using WHERE in the SELECT statement is as follows:

SELECT "column_name"

FROM "table_name"

WHERE "condition";

Eg :SELECT Store_Name FROM Store_Information WHERE Sales > 1000;

Group by clause: group by clause

The usage of SQL GROUP BY clause is, to divide the rows in a table into smaller groups.

The GROUP BY clause is used with the SQL SELECT statement.

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.

SQL count group by

Syntax:

SELECT <column_list>

FROM < table name >

WHERE <condition>GROUP BY <columns>

[HAVING] <condition>;

Eg:SELECT Store_Name, SUM(Sales)

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.

It is typically located near or at the end of the SQL statement.

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:

SELECT ["column_name1"], "function type" ("column_name2")

FROM "table_name"

[GROUP BY "column_name1"]

HAVING (arithmetic function condition);

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

Store_Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

Los Angeles 300 Jan-08-1999

Boston 700 Jan-08-1999

To see only the stores with sales over $1,500, we would type,

SELECT Store_Name, SUM(Sales)

FROM Store_Information

GROUP BY Store_Name

HAVING SUM(Sales) > 1500;

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.

To sort the records in descending order, use the DESC keyword.

order by command in sql

sql tutorial , pl sql tutorial , mysql tutorial , oracle tutorial , learn sql , sql server tutorial

Syntax:

The syntax for an ORDER BY statement is as follows:

SELECT "column_name"

FROM "table_name"

[WHERE "condition"]

ORDER BY "column_name" [ASC, DESC];

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.

If neither is specified, the default is ASC.


It is possible to order by more than one column. In this case, the ORDER BY clause above becomes

ORDER BY "column_name1" [ASC, DESC], "column_name2" [ASC, DESC]

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

Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

San Diego 250 Jan-07-1999

San Francisco 300 Jan-08-1999

Boston 700 Jan-08-1999

To list the contents of Table Store_Information by Sales in descending order, we key in,

SELECT Name, Sales, Txn_Date

FROM Store_Information

ORDER BY Sales DESC;

Result:

Name Sales Txn_Date

Los Angeles 1500 Jan-05-1999

Boston 700 Jan-08-1999

San Francisco 300 Jan-08-1999

San Diego 250 Jan-07-1999

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#.

Sr.No. Class & Description and Useage


1 ArrayList

It represents ordered collection of an object that can be indexed individually.

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

It uses a 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.

3SortedList

It uses a key as well as an index to access the items in a list.

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 represents a last-in, first out collection of object.

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 represents a first-in, first out collection of object.

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

It represents an array of the binary representation using the values 1 and 0.


It is used when you need to store the bits but do not know the number of bits in advance. You can
access items from the BitArray collection by using an integer index, which starts from zero.

68.Dotnet version: .NET Framework 1.0- .NET Framework 4.8.1

69.SQL version SQL Server 2008- SQL Server 2022.

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:

protected void BindGridview() {

using(SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial


Catalog=Test")) {

con.Open();

SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location


FROM Users", conn);

SqlDataReader sdr = cmd.ExecuteReader();

gvUserInfo.DataSource = sdr;

gvUserInfo.DataBind();

conn.Close();

C#

Holds the connection open until you are finished (don't forget to close it!).

Can typically only be iterated over once

Is not as useful for updating back to the database

Here is a detailed tutorial on DataReader: DataReader in ADO.NET

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.

protected void BindGridview() {

SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial


Catalog=Test");

conn.Open();

SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM


Users", conn);

SqlDataAdapter sda = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

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:

protected void BindGridview() {

SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial


Catalog=Test");

conn.Open();

SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM


Users", conn);

SqlDataAdapter sda = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();


sda.Fill(ds);

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

All of the results are available in memory

You can iterate over it as many times as you need, or even look up a specific record by index

Has some built-in faculties for updating back to the database.

Here is a detailed tutorial on DataAdapter: DataAdapter in C#

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.

protected void BindGridview()

SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial


Catalog=Test");

conn.Open();

SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM


Users", conn);

SqlDataAdapter sda = new SqlDataAdapter(cmd);

DataTable dt = new DataTable();

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

string[] array1=new string[5];

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.

In an array we cannot store null.

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;

ArrayList a1 = new ArryList();

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.

Add() - Add single element to ArrayList.

Insert() - Allow inserting a single element at the specific position.

Remove() - Remove single elemet from ArrayList.

RemoveAt() - Remove element from specific postion.

To use ArrayList you must add a namespace System.Collection.

ArrayList can store null.

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.

Example of defining a VARCHAR column:

CREATE TABLE Employee (

EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50));

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.

Example of defining an NVARCHAR column:

CREATE TABLE Employe( EmployeeID INT PRIMARY KEY,FirstName NVARCHAR(50),

LastName NVARCHAR(50)

);

Data reader and data set which is faster

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.

You create a DataReader by calling Command.ExecuteReader after creating an instance of the


Command object.

This is a connected architecture: The data is available as long as the connection with database exists.

You need to open and close the connecton manually in code.

The following code statement is used to retrieve rows from a data source.

//opening connection is must

conn.open();

string SQLquery = "SELECT CustomerID, CompanyName FROM dbo.Customers";

SqlCommand cmd = new SqlCommand(SQLquery, conn);

// Call ExecuteReader to return a DataReader

SqlDataReader myReader = cmd.ExecuteReader();

//The Read method of the DataReader object is used to obtain a row from the results of the executed
query.

while(myReader.Read())

Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));

//Once you're done with the data reader, call the Close method to close a data reader:

myReader.Close();

//close the connection

conn.close();

Here are detailed tutorials on DataReader:

DataReader in ADO.NET

DataReader in C#

DataSet

The DataSet is a in-memory representation of data.


It can be used with multiple data sources. That is A single DataSet can hold the data from different
data sources holdng data from different databases/tables.

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.

No need to manually open and close connection in code.

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.

string SQLquery = "SELECT CustomerID, CompanyName FROM dbo.Customers";

// create DataSet that will hold your Tables/data

DataSet ds = new DataSet("CustomerDataSet");

//Create SqlDataAdapter which acts as bridge to put the data in DataSet,(data is table available by
executing your SQL query)

SqlDataAdapter myAdapter = new SqlDataAdapter(SQLquery, conn);

//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.

Note: Indexers and destructors cannot be static.

Advantage of C# static keyword

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.

C# static field example

Let's see the simple example of static field in C#.

using System;

public class Account

public int accno;

public String name;

public static float rateOfInterest=8.8f;

public Account(int accno, String name)

this.accno = accno;

this.name = name;

public void display()

Console.WriteLine(accno + " " + name + " " + rateOfInterest);

class TestAccount{

public static void Main(string[] args)

Account a1 = new Account(101, "Sonoo");

Account a2 = new Account(102, "Mahesh");


a1.display();

a2.display();

Output:

101 Sonoo 8.8

102 Mahesh 8.8

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.

Serialization is internally used in remote applications.

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;

public Student(int rollno, string name)

this.rollno = rollno;

this.name = name;

public class SerializeExample

public static void Main(string[] args)

FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);

BinaryFormatter formatter=new BinaryFormatter();

Student s = new Student(101, "sonoo");

formatter.Serialize(stream, s);

stream.Close();

sss.txt:

JConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Student rollnoname


e sonoo

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

Hash set is implemented using HashTable

The tree set is implemented using a tree structure.

Null Object

HashSet allows a null object

The tree set does not allow the null object. It throws the null pointer exception.

Methods

Hash set use equals method to compare two objects

Tree set use compare method for comparing two objects.

Heterogeneous object

Hash set doesn't now allow a heterogeneous object

Tree set allows a heterogeneous object

Ordering

HashSet does not maintain any order

TreeSet maintains an object in sorted order

Example of TreeSet

class TreeSetExmaple {

public static void main(String[] args){

TreeSet<String> treeset = new TreeSet<String>();

treeset.add("Good");

treeset.add("For");

treeset.add("Health");
//Add Duplicate Element

treeset.add("Good");

System.out.println("TreeSet : ");

for (String temp : treeset) {

System.out.println(temp);

Output

TreeSet:

For

Good

Health

Example of HashSet

class HashSetExample {

public static void main(String[] args){

HashSet<String> hashSet = new HashSet<String>();

hashSet.add("Good");

hashSet.add("For");

hashSet.add("Health");

//Add Duplicate Element

hashSet.add("Good");

System.out.println("HashSet: ");

for (String temp : hashSet) {

System.out.println(temp);

}
Output

HashSet:

Health

For

Good

80.Difference between Exception and Error

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

Exception: An exception is an object that represents an exceptional or abnormal condition or event


that occurs during the execution of a program. Exceptions are typically caused by runtime errors,
invalid input, or exceptional circumstances that prevent the normal flow of program execution.

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

int result = Divide(10, 0); // This will throw an exception

Console.WriteLine(result);

catch (DivideByZeroException ex)

Console.WriteLine("Error: Cannot divide by zero");

// Handle the exception

int Divide(int dividend, int divisor)

if (divisor == 0)

throw new DivideByZeroException();

return dividend / divisor;

Example | Error

int[] array = new int[int.MaxValue]; // This will throw an OutOfMemoryError

// The program will terminate due to the critical 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("Parameter less constructor called");

public Demo(int firstNumber, int secondNumber) : this(){

System.Console.WriteLine($"{firstNumber} {secondNumber}");

public Demo(int firstNumber, int secondNumber, int thirdNumber) : this(firstNumber,


secondNumber){

System.Console.WriteLine($"{firstNumber} {secondNumber} {thirdNumber}");

class Program{

static void Main(){

Demo obj = new Demo(1, 2, 3);

Console.ReadLine();

Output

Parameter less constructor called

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.

Here, are some important phases of SDLC life cycle:

Software Engineering SDLC Models

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

Testing and Turnover

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

It is a particular implementation of a software development life cycle that focuses on an initial,


simplified implementation, which then progressively gains more complexity and a broader feature set
until the final system is complete. In short, iterative development is a way of breaking down the
software development of a large application into smaller pieces.

Big bang model


Big bang model is focusing on all types of resources in software development and coding, with no or
very little planning. The requirements are understood and implemented when they come.

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.

84.SQL Server JOINS

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.

In a JOIN query, a condition indicates how two tables are related:


Choose columns from each table that should be used in the join. A join condition indicates a foreign
key from one table and its corresponding key in the other table.

Specify the logical operator to compare values from the columns like =, <, or >.

Types of JOINS in SQL Server

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

SQL Server JOINS

Let us discuss each of these joins in detail.

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:

SQL Server JOINS

INNER JOIN Syntax

The following syntax illustrates the use of INNER JOIN in SQL Server:

SELECT columns

FROM table1

INNER JOIN table2 ON condition1

INNER JOIN table3 ON condition2

INNER JOIN Example


Let us first create two tables "Student" and "Fee" using the following statement:

CREATE TABLE Student (

id int PRIMARY KEY IDENTITY,

admission_no varchar(45) NOT NULL,

first_name varchar(45) NOT NULL,

last_name varchar(45) NOT NULL,

age int,

city varchar(25) NOT NULL

);

CREATE TABLE Fee (

admission_no varchar(45) NOT NULL,

course varchar(45) NOT NULL,

amount_paid int,

);

Next, we will insert some records into these tables using the below statements:

INSERT INTO Student (admission_no, first_name, last_name, age, city)

VALUES (3354,'Luisa', 'Evans', 13, 'Texas'),

(2135, 'Paul', 'Ward', 15, 'Alaska'),

(4321, 'Peter', 'Bennett', 14, 'California'),

(4213,'Carlos', 'Patterson', 17, 'New York'),

(5112, 'Rose', 'Huges', 16, 'Florida'),

(6113, 'Marielia', 'Simmons', 15, 'Arizona'),

(7555,'Antonio', 'Butler', 14, 'New York'),

(8345, 'Diego', 'Cox', 13, 'California');


INSERT INTO Fee (admission_no, course, amount_paid)

VALUES (3354,'Java', 20000),

(7555, 'Android', 22000),

(4321, 'Python', 18000),

(8345,'SQL', 15000),

(5112, 'Machine Learning', 30000);

Execute the SELECT statement to verify the records:

Table: Student

SQL Server JOINS

Table: Fee

SQL Server JOINS

We can demonstrate the INNER JOIN using the following command:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid

FROM Student

INNER JOIN Fee

ON Student.admission_no = Fee.admission_no;

This command gives the below result:

SQL Server JOINS

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.

SELF JOIN Syntax

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.

SELECT T1.col_name, T2.col_name...

FROM table1 T1, table1 T2

WHERE join_condition;

Example

We can demonstrate the SELF JOIN using the following command:

SELECT S1.first_name, S2.last_name, S2.city

FROM Student S1, Student S2

WHERE S1.id <> S2.iD AND S1.city = S2.city

ORDER BY S2.city;

This command gives the below result:

SQL Server JOINS

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:

SQL Server JOINS

CROSS JOIN Syntax

The following syntax illustrates the use of CROSS JOIN in SQL Server:

SELECT column_lists

FROM table1

CROSS JOIN table2;

Example

We can demonstrate the CROSS JOIN using the following command:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid

FROM Student

CROSS JOIN Fee

WHERE Student.admission_no = Fee.admission_no;

This command gives the below result:

SQL Server JOINS

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.

We can categories the OUTER JOIN further into three types:

LEFT OUTER JOIN

RIGHT OUTER JOIN

FULL OUTER JOIN

LEFT OUTER JOIN


The LEFT OUTER JOIN retrieves all the records from the left table and matching rows from the right
table. It will return NULL when no matching record is found in the right side table. Since OUTER is
an optional keyword, it is also known as LEFT JOIN.

The below visual representation illustrates the LEFT OUTER JOIN:

SQL Server JOINS

LEFT OUTER JOIN Syntax

The following syntax illustrates the use of LEFT OUTER JOIN in SQL Server

SELECT column_lists

FROM table1

LEFT [OUTER] JOIN table2

ON table1.column = table2.column;

Example

We can demonstrate the LEFT OUTER JOIN using the following command:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid

FROM Student

LEFT OUTER JOIN Fee

ON Student.admission_no = Fee.admission_no;

This command gives the below result:

SQL Server JOINS

This output shows that the unmatched row's values are replaced with NULLs in the respective
columns.

RIGHT OUTER JOIN

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.

The below visual representation illustrates the RIGHT OUTER JOIN:

freestar

SQL Server JOINS

RIGHT OUTER JOIN Syntax

The following syntax illustrates the use of RIGHT OUTER JOIN in SQL Server:
SELECT column_lists

FROM table1

RIGHT [OUTER] JOIN table2

ON table1.column = table2.column;

Example

The following example explains how to use the RIGHT OUTER JOIN to get records from both
tables:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid

FROM Student

RIGHT OUTER JOIN Fee

ON Student.admission_no = Fee.admission_no;

This command gives the below result.

SQL Server JOINS

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.

FULL OUTER JOIN

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 below visual representation illustrates the FULL OUTER JOIN:

SQL Server JOINS

FULL OUTER JOIN Syntax

The following syntax illustrates the use of FULL OUTER JOIN in SQL Server:

SELECT column_lists

FROM table1

FULL [OUTER] JOIN table2

ON table1.column = table2.column;

Example
The following example explains how to use the FULL OUTER JOIN to get records from both tables:

SELECT Student.admission_no, Student.first_name, Student.last_name, Fee.course, Fee.amount_paid

FROM Student

FULL OUTER JOIN Fee

ON Student.admission_no = Fee.admission_no;

This command gives the below result:

SQL Server JOINS

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

string connetionString = "Data Source=.;Initial Catalog=DB name;Integrated


Security=True;MultipleActiveResultSets=True";

88.Write a C# Sharp program to swap two numbers.

C# Sharp: swapping two variables

The act of swapping two variables refers to mutually exchanging the values of the variables. Generall,
this is done with the data in memory.

Using a temporary variable :

The simplest method to swap two variables is to use a third temporary variable :

define swap(x, y)

temp := x

x := y

y := temp

C# sharp Exercises: swap two variables

Sample Solution:
C# Sharp Code:

using System;

public class Exercise5

public static void Main(string[] args)

int number1, number2, temp;

Console.Write("\nInput the First Number : ");

number1 = int.Parse(Console.ReadLine());

Console.Write("\nInput the Second Number : ");

number2 = int.Parse(Console.ReadLine());

temp = number1;

number1 = number2;

number2 = temp;

Console.Write("\nAfter Swapping : ");

Console.Write("\nFirst Number : "+number1);

Console.Write("\nSecond Number : "+number2);

Console.Read();

Sample Output:

Input the First Number : 2

Input the Second Number : 5

After Swapping :

First Number : 5
Second Number : 2

What is System Testing?

What is System Testing?

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.

Types of System Tests:

System testing in Test Life Cycle

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

public class RouteConfig

public static void RegisterRoutes(RouteCollection routes)

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

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.

CREATE TRIGGER schema.trigger_name

ON table_name

AFTER {INSERT, UPDATE, DELETE}

[NOT FOR REPLICATION]

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.

Palindrome number algorithm

Get the number from user

Hold the number in temporary variable

Reverse the number

Compare the temporary number with reversed number

If both numbers are same, print palindrome number

Else print not palindrome number

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;

public class PalindromeExample


{

public static void Main(string[] args)

int n,r,sum=0,temp;

Console.Write("Enter the Number: ");

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

Console.Write("Number is not Palindrome");

Output:

Enter the Number=121

Number is Palindrome.

Enter the number=113

94.Number iFibonacci Series in C#

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.

Let's see the fibonacci series program in C#.


using System;

public class FibonacciExample

public static void Main(string[] args)

int n1=0,n2=1,n3,i,number;

Console.Write("Enter the number of elements: ");

number = int.Parse(Console.ReadLine());

Console.Write(n1+" "+n2+" "); //printing 0 and 1

for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed

n3=n1+n2;

Console.Write(n3+" ");

n1=n2;

n2=n3;

Output:

Enter the number of elements: 15

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 s not Palindrome.

95.Prime Number Program in C#

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;

public class PrimeNumberExample

public static void Main(string[] args)

int n, i, m=0, flag=0;

Console.Write("Enter the Number to check Prime: ");

n = int.Parse(Console.ReadLine());

m=n/2;

for(i = 2; i <= m; i++)

if(n % i == 0)

Console.Write("Number is not Prime.");

flag=1;

break;

if (flag==0)

Console.Write("Number is Prime.");

Output:

Enter the Number to check Prime: 17

Number is Prime.
Enter the Number to check Prime: 57

Number is not Prime.

C# Program to reverse number

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.

Let's see a simple C# example to reverse a given number.

using System;

public class ReverseExample

public static void Main(string[] args)

int n, reverse=0, rem;

Console.Write("Enter a number: ");

n= int.Parse(Console.ReadLine());

while(n!=0)

rem=n%10;

reverse=reverse*10+rem;

n/=10;

Console.Write("Reversed Number: "+reverse);

Output:

Enter a number: 234

Reversed Number: 432

96.C# Program to swap two numbers without third variable

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 /

Program 1: Using ∗ and /

Let's see a simple C# example to swap two numbers without using third variable.

using System;

public class SwapExample

public static void Main(string[] args)

int a=5, b=10;

Console.WriteLine("Before swap a= "+a+" b= "+b);

a=a*b; //a=50 (5*10)

b=a/b; //b=5 (50/10)

a=a/b; //a=10 (50/5)

Console.Write("After swap a= "+a+" b= "+b);

Output:

Before swap a= 5 b= 10

After swap a= 10 b= 5

Program 2: Using + and -

Let's see another example to swap two numbers using + and -.

using System;

public class SwapExample

{
public static void Main(string[] args)

int a=5, b=10;

Console.WriteLine("Before swap a= "+a+" b= "+b);

a=a+b; //a=15 (5+10)

b=a-b; //b=5 (15-10)

a=a-b; //a=10 (15-5)

Console.Write("After swap a= "+a+" b= "+b);

Output:

Before swap a= 5 b= 10

After swap a= 10 b= 5

99.C# Method Overloading

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.

You can perform method overloading in C# by two ways:

By changing number of arguments

By changing data type of the arguments

C# Method Overloading Example: By changing no. of arguments

Let's see the simple example of method overloading where we are changing number of arguments of
add() method.

using System;

public class Cal{

public static int add(int a,int b){


return a + b;

public static int add(int a, int b, int c)

return a + b + c;

public class TestMemberOverloading

public static void Main()

Console.WriteLine(Cal.add(12, 23));

Console.WriteLine(Cal.add(12, 23, 25));

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.

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;

public class Animal{


public virtual void eat(){

Console.WriteLine("Eating...");

public class Dog: Animal

public override void eat()

Console.WriteLine("Eating bread...");

public class TestOverriding

public static void Main()

Dog d = new Dog();

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.

Dependency Injection CSharp

We have the following ways to implement Dependency Injection.

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.

The following is an example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace propertyinjuction

public interface text

void print();

class format : text

public void print()

Console.WriteLine(" here is text format");

// constructor injection

public class constructorinjection

private text _text;


public constructorinjection(text t1)

this._text = t1;

public void print()

_text.print();

class constructor

static void Main(string[] args)

constructorinjection cs = new constructorinjection(new format());

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.

The following is an example:


public interface INofificationAction

void ActOnNotification(string message);

class atul {

INofificationAction task = null;

public void notify(INofificationAction at ,string messages)

this.task = at;

task.ActOnNotification(messages);

class EventLogWriter : INofificationAction

public void ActOnNotification(string message)

// Write to event log here

class Program

static void Main(string[] args)

//services srv = new services();

//other oth = new other();

//oth.run();

//Console.WriteLine();
EventLogWriter elw = new EventLogWriter();

atul at = new atul();

at.notify(elw, "to logg");

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.

The following is an example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace propertyinjuction

public interface Iset

void print();

public class servic : Iset


{

public void print()

Console.WriteLine("print........");

public class client

private Iset _set;

public void run(Iset serv)

this._set = serv;

Console.WriteLine("start");

this._set.print();

class method

public static void Main()

client cn = new client();

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

Instance variables or Non – Static Variables

Static Variables or Class Variables

Constant Variables

Readonly Variables

Local Variables

A variable defined within a block or method or constructor is called local variable.

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

// the local variables

using System;

class StudentDetails {

// Method

public void StudentAge()

// local variable age

int age = 0;
age = age + 10;

Console.WriteLine("Student age is : " + age);

// Main Method

public static void Main(String[] args)

// Creating object

StudentDetails obj = new StudentDetails();

// calling the function

obj.StudentAge();

Output:

Student age is : 10

Instance Variables or Non – Static Variables

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:

// C# program to illustrate the

// Instance variables

using System;
class Marks {

// These variables are instance variables.

// These variables are in a class and

// are not inside any function

int engMarks;

int mathsMarks;

int phyMarks;

// Main Method

public static void Main(String[] args)

// first object

Marks obj1 = new Marks();

obj1.engMarks = 90;

obj1.mathsMarks = 80;

obj1.phyMarks = 93;

// second object

Marks obj2 = new Marks();

obj2.engMarks = 95;

obj2.mathsMarks = 70;

obj2.phyMarks = 90;

// displaying marks for first object

Console.WriteLine("Marks for first object:");

Console.WriteLine(obj1.engMarks);
Console.WriteLine(obj1.mathsMarks);

Console.WriteLine(obj1.phyMarks);

// displaying marks for second object

Console.WriteLine("Marks for second object:");

Console.WriteLine(obj2.engMarks);

Console.WriteLine(obj2.mathsMarks);

Console.WriteLine(obj2.phyMarks);

Output :

Marks for first object:

90

80

93

Marks for second object:

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.

102.What is this keyword

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.

It can be used to pass current object as a parameter to another method.

It can be used to declare indexers.

C# this example

Let's see the example of this keyword in C# that refers to the fields of current class.

using System;

public class Employee

public int id;

public String name;

public float salary;

public Employee(int id, String name,float salary)

this.id = id;

this.name = name;

this.salary = salary;

public void display()

Console.WriteLine(id + " " + name+" "+salary);

class TestEmployee{

public static void Main(string[] args)

Employee e1 = new Employee(101, "Sonoo", 890000f);

Employee e2 = new Employee(102, "Mahesh", 490000f);


e1.display();

e2.display();

Output:

101 Sonoo 890000

102 Mahesh 490000

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;

public interface Drawable

void draw();

public class Rectangle : Drawable

public void draw()

Console.WriteLine("drawing rectangle...");
}

public class Circle : Drawable

public void draw()

Console.WriteLine("drawing circle...");

public class TestInterface

public static void Main()

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

The C# if statement tests the condition. It is executed if condition is true.

Syntax:

if(condition){

//code to be executed

}
C# If Example

using System;

public class IfExample

public static void Main(string[] args)

int num = 10;

if (num % 2 == 0)

Console.WriteLine("It is even number");

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)

//code if condition is true

}else{

//code if condition is false

C# If-else Example

using System;

public class IfExample

public static void Main(string[] args)


{

int num = 11;

if (num % 2 == 0)

Console.WriteLine("It is even number");

else

Console.WriteLine("It is odd number");

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:

//code to be executed if all cases are not matched;

break;

C# Switch Example

using System;

public class SwitchExample

public static void Main(string[] args)

Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());

switch (num)

case 10: Console.WriteLine("It is 10"); break;

case 20: Console.WriteLine("It is 20"); break;

case 30: Console.WriteLine("It is 30"); break;

default: Console.WriteLine("Not 10, 20 or 30"); break;

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:

C# For Loop Example

using System;

public class ForExample

public static void Main(string[] args)

for(int i=1;i<=10;i++){
Console.WriteLine(i);

Output:

10

3. Breaks in Loop

Code

>using System;

public class Program

public static void Main()

for (int i = 0; i < 8; i++)

if( i == 4 )

break;

Console.WriteLine("Value of i: {0}", i);


}

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);

C# do-while Loop Example

Let's see a simple example of C# do-while loop to print the table of 1.

using System;

public class DoWhileExample

public static void Main(string[] args)

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

Let's see a simple example of while loop to print table of 1.

using System;

public class WhileExample

public static void Main(string[] args)

int i=1;

while(i<=10)

Console.WriteLine(i);

i++;

}
}

Output:

10

C# Access Modifiers / Specifiers

C# Access modifiers or specifiers are the keywords that are used to specify accessibility or scope of
variables and functions in the C# application.

C# provides five types of access specifiers.

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

Public It specifies that access is not restricted.

Protected It specifies that access is limited to the containing class or in derived class.

Internal It specifies that access is limited to the current assembly.

protected

internal It specifies that access is limited to the current assembly or types derived from the
containing class.

Private It specifies that access is limited to the containing type.

Now, let's create examples to check accessibility of each access specifier.

1) C# Public Access Specifier

It makes data accessible publicly. It does not restrict data to the declared block.

Example

using System;

namespace AccessSpecifiers

class PublicTest

public string name = "Shantosh Kumar";

public void Msg(string msg)

Console.WriteLine("Hello " + msg);

class Program

static void Main(string[] args)

{
PublicTest publicTest = new PublicTest();

// Accessing public variable

Console.WriteLine("Hello " + publicTest.name);

// Accessing public function

publicTest.Msg("Peter Decosta");

Output:

Hello Shantosh Kumar

Hello Peter Decosta

2) C# Protected Access Specifier

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

protected string name = "Shashikant";

protected void Msg(string msg)

Console.WriteLine("Hello " + msg);

class Program
{

static void Main(string[] args)

ProtectedTest protectedTest = new ProtectedTest();

// Accessing protected variable

Console.WriteLine("Hello "+ protectedTest.name);

// Accessing protected function

protectedTest.Msg("Swami Ayyer");

Output:

Compile time error

'ProtectedTest.name' is inaccessible due to its protection level.

Example2

Here, we are accessing protected members within child class by inheritance.

using System;

namespace AccessSpecifiers

class ProtectedTest

protected string name = "Shashikant";

protected void Msg(string msg)

Console.WriteLine("Hello " + msg);


}

class Program : ProtectedTest

static void Main(string[] args)

Program program = new Program();

// Accessing protected variable

Console.WriteLine("Hello " + program.name);

// Accessing protected function

program.Msg("Swami Ayyer");

Output:

Hello Shashikant

Hello Swami Ayyer

3) C# Internal Access Specifier

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

internal string name = "Shantosh Kumar";


internal void Msg(string msg)

Console.WriteLine("Hello " + msg);

class Program

static void Main(string[] args)

InternalTest internalTest = new InternalTest();

// Accessing internal variable

Console.WriteLine("Hello " + internalTest.name);

// Accessing internal function

internalTest.Msg("Peter Decosta");

Output:

freestar

Hello Shantosh Kumar

Hello Peter Decosta

4) C# Protected Internal Access Specifier

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

protected internal string name = "Shantosh Kumar";

protected internal void Msg(string msg)

Console.WriteLine("Hello " + msg);

class Program

static void Main(string[] args)

InternalTest internalTest = new InternalTest();

// Accessing protected internal variable

Console.WriteLine("Hello " + internalTest.name);

// Accessing protected internal function

internalTest.Msg("Peter Decosta");

Output:

Hello Shantosh Kumar

Hello Peter Decosta

5) C# Private Access Specifier

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

private string name = "Shantosh Kumar";

private void Msg(string msg)

Console.WriteLine("Hello " + msg);

class Program

static void Main(string[] args)

PrivateTest privateTest = new PrivateTest();

// Accessing private variable

Console.WriteLine("Hello " + privateTest.name);

// Accessing private function

privateTest.Msg("Peter Decosta");

Output:

Compile time error


'PrivateTest.name' is inaccessible due to its protection level.

C# Private Specifier Example 2

using System;

namespace AccessSpecifiers

class Program

private string name = "Shantosh Kumar";

private void Msg(string msg)

Console.WriteLine("Hello " + msg);

static void Main(string[] args)

Program program = new Program();

// Accessing private variable

Console.WriteLine("Hello " + program.name);

// Accessing private function

program.Msg("Peter Decosta");

Output:

Hello Shantosh Kumar

Hello Peter Decosta

112.ASP.NET is a web application framework developed and marketed by Microsoft to allow


programmers to build dynamic web sites. It allows you to use a full featured programming language
such as C# or VB.NET to build web applications easily.
113.A Composite Key is a key that consists of two or more attributes (columns or fields) in a table. It
can also be described as a Primary key created on multiple columns.Using the composite key, we can
uniquely identify any record in a database table. A combination of these columns guarantees
uniqueness, though the individual column may or may not guarantee for the uniqueness in a table.

Here are some important points about the Composite Key −

A Composite Key may or may not be a part of the Foreign key.

A Composite Key can not be NULL.

A Composite Key also can be created by combining more than one Candidate Key.

It is also known as Compound key.

All the attributes in a compound keys are foreign keys.

Why do we need Composite 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

Following is the syntax to create a COMPOSITE KEY while creating a table −

CREATE TABLE TABLE_NAME(COLUMN1, COLUMN2, COLUMN3…., CONSTRAINT


COMPOSITE_KEY_NAME PRIMARY KEY(COLUMN1, COLUMN2,..);

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.

Following is the statement to create table in SQL −


CREATE TABLE CUSTOMERS(

ID INT NOT NULL,

NAME VARCHAR (20) NOT NULL,

AGE INT NOT NULL,

ADHARCARD_ID BIGINT,

MOBILE_NO BIGINT,

ADDRESS CHAR (25) ,

SALARY DECIMAL (18, 2),

CONSTRAINT CK_CUSTOMERS PRIMARY KEY (ADHARCARD_ID, MOBILE_NO)

);

Where the CK_CUSTOMERS is the name of a composite of this table.

Output

Following is the output of the above statement −

(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.

Methods and Properties of the Hashtable Class

The following table lists some of the commonly used properties of the Hashtable class −

Sr.No. Property & Description

Count
Gets the number of key-and-value pairs contained in the Hashtable.

IsFixedSize

Gets a value indicating whether the Hashtable has a fixed size.

IsReadOnly

Gets a value indicating whether the Hashtable is read-only.

Item

Gets or sets the value associated with the specified key.

Keys

Gets an ICollection containing the keys in the Hashtable.

Values

Gets an ICollection containing the values in the Hashtable.

Example

The following example demonstrates the concept −

Live Demo

using System;

using System.Collections;

namespace CollectionsApplication {

class Program {

static void Main(string[] args) {

Hashtable ht = new Hashtable();


ht.Add("001", "Zara Ali");

ht.Add("002", "Abida Rehman");

ht.Add("003", "Joe Holzner");

ht.Add("004", "Mausam Benazir Nur");

ht.Add("005", "M. Amlan");

ht.Add("006", "M. Arif");

ht.Add("007", "Ritesh Saikia");

if (ht.ContainsValue("Nuha Ali")) {

Console.WriteLine("This student name is already in the list");

} else {

ht.Add("008", "Nuha Ali");

// Get a collection of the keys.

ICollection key = ht.Keys;

foreach (string k in key) {

Console.WriteLine(k + ": " + ht[k]);

Console.ReadKey();

When the above code is compiled and executed, it produces the following result −

001: Zara Ali


002: Abida Rehman

003: Joe Holzner

004: Mausam Benazir Nur

005: M. Amlan

006: M. Arif

007: Ritesh Saikia

008: Nuha Ali

116. Data Manipulation Language

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.

Here are some commands that come under DML:

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

INSERT INTO TABLE_NAME

(col1, col2, col3,.... col N)

VALUES (value1, value2, value3, .... valueN);

Or

INSERT INTO TABLE_NAME


VALUES (value1, value2, value3, .... valueN);

For example:

INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE


CONDITION]

For example:

UPDATE students

SET User_Name = 'Sonoo'

WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.

Syntax:

DELETE FROM table_name [WHERE condition];

For example:

DELETE FROM javatpoint

WHERE Author="Sonoo";

117. Data Definition Language (DDL)

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.

Here are some commands that come under DDL:

CREATE

ALTER

DROP

TRUNCATE
a. CREATE It is used to create a new table in the database.

Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

DROP TABLE table_name;

Example

DROP TABLE EMPLOYEE;

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:

To add a new column in the table

ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));

ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.

Syntax:

TRUNCATE TABLE table_name;


Example:

TRUNCATE TABLE EMPLOYEE;

SQL SELECT Statement

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.

Syntax of SELECT Statement in SQL

SELECT Column_Name_1, Column_Name_2, ....., Column_Name_N FROM Table_Name;

SELECT * FROM table_name;

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 is a DML(Data Manipulation Language) command.

It deletes rows one at a time and applies same criteria to each deletion.

The WHERE clause serves as the condition in this case.

All rows are locked after deletion.

It makes a record of each and every transaction in the log file.

It consumes a greater amount of transaction space compared to TRUNCATE command

If there is an identity column, the table identity is not reset to the value it had when the table was
created.

It requires authorization to delete.

When it comes to large databases, it is much slower.

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.

It is a DDL(Data Definition Language) command.


When you use the TRUNCATE command, the modifications made to the table are committed
automatically.

It removes all of the information in one go.

The WHERE Clause is not available.

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 takes comparatively less amount of transaction space.

It returns the table identity to a value it was given as a seed.

It requires table alter permission.

It is much faster.

The SQL TRUNCATE TABLE Statement

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 basic syntax of a TRUNCATE TABLE command is as follows.

TRUNCATE TABLE table_name;

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.

SQL DELETE TABLE Statement

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 −

DELETE FROM table_name;

SQL DELETE TABLE with WHERE Clause

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 −

DELETE FROM table_name

WHERE condition;

123.C# is oops are not.

It is completely oops concept

126.C# Data Types

A data type specifies the type of data that a variable can store such as integer, floating, character etc.

CSHRAP Data types 1

There are 3 types of data types in C# language.

Types Data Types


Value Data Type short, int, char, float, double etc

Reference Data Type String, Class, Object and Interface

Pointer Data Type Pointers

Value Data Type

The value data types are integer-based and floating-point based. C# language supports both signed
and unsigned literals.

There are 2 types of value data type in C# language.

1) Predefined Data Types - such as Integer, Boolean, Float, etc.

2) User defined Data Types - such as Structure, Enumerations, etc.

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.

Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 4 byte -2,147,483,648 to -2,147,483,647

signed int 4 byte -2,147,483,648 to -2,147,483,647

unsigned int 4 byte 0 to 4,294,967,295

long 8 byte ?9,223,372,036,854,775,808 to 9,223,372,036,854,775,807


signed long 8 byte ?9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

unsigned long 8 byte 0 - 18,446,744,073,709,551,615

float 4 byte 1.5 * 10-45 - 3.4 * 1038, 7-digit precision

double 8 byte 5.0 * 10-324 - 1.7 * 10308, 15-digit precision

decimal 16 byte at least -7.9 * 10?28 - 7.9 * 1028, with at least 28-digit precision

Reference Data Type

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.

There are 2 types of reference data type in C# language.

1) Predefined Types - such as Objects, String.

2) User defined Types - such as Classes, Interface.

Pointer Data Type

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

Symbols used in pointer

Symbol Name Description

& (ampersand sign) Address operator Determine the address of a variable.

* (asterisk sign) Indirection operator Access the value of an address.

Declaring a pointer

The pointer in C# language can be declared using * (asterisk symbol).

int * a; //pointer to int

char * c; //pointer to char

127.What is CTE (Common Table Expression)?

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.

Why do we need CTE?

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

Following is the syntax of the CTE −

WITH CTE_NAME (column_name) AS (query)

SELECT * FROM CTE_NAME;

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.

ORDER BY unless you also use as a TOP clause.

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.

Following is the customers table −

+------+----------+------+-----------+--------+

| ID | NAME | AGE | ADDRESS | SALARY |

+------+----------+------+-----------+--------+

| 1 | Ramesh | 32 | Ahmedabad | 2000 |

| 2 | Aman | 23 | Ranchi | 40000 |

| 3 | kaushik | 23 | Kota | 2000 |

| 4 | Chaitali | 25 | Mumbai | 6500 |

+------+----------+------+-----------+--------+

Following is the query to fetch the details using the CTE −

WITH customer_AGE

AS (SELECT * FROM customers WHERE AGE = 23)

SELECT ID, NAME, AGE FROM customer_AGE;


Output

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.

There are a few rules that subqueries must follow −

Subqueries must be enclosed within parentheses.

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.

A subquery cannot be immediately enclosed in a set function.

The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be
used within the subquery.

Subqueries with the SELECT Statement

Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −

SELECT column_name [, column_name ]

FROM table1 [, table2 ]

WHERE column_name OPERATOR

(SELECT column_name [, column_name ]

FROM table1 [, table2 ]

[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.

The difference between the id and class is tabulated as follows.

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

We can attach multiple class selectors to an element.

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.

We can attach only one ID selector to an element.

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).

The container class is used to create boxed content.

There are two container classes in Bootstrap:

container

container-fluid

See the basic layout of a container:

<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>

Bootstrap container example

<!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>

What are the validations that u have used in C#

1. Required field validation: Ensures that a field is not left empty.

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.

5. Custom validation: Allows for the creation of custom validation rules.

6. Remote validation: Validates a field's value by sending a request to the server.

What is Full Stack Development?

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.

Difference between Html and Html5

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.

Storage: The HTML browser uses cache memory as temporary storage.

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.

Storage: Uses cookies to store data.

Vector and Graphics: Vector graphics are possible with the help of technologies like VML,
Silverlight, Flash,etc.

Shapes: It is not possible to create shapes like circles, rectangles, triangles.

Doc type: Doctype declaration in html is too long


Multimedia support: Audio and video are not the part of HTML4.

<! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.01 // EN"
"http://www.w3.org/TR/html4/strict.dtd">

Character Encoding: Character encoding in HTML is too long.

<! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.0 Transitional // EN">

Browser Support:Works with all older browsers

Html5: HTML5 is a new version of HTML with new functionalities with markup language with
Internet technologies.

HTML5 supports both video and audio.

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.

In HTML5, vector graphics are supported by default.

The HTML5 has the JavaScript Web Worker API, which allows the browser interface to run in
multiple threads.

Uses local storage instead of cookies

Vector graphics is an integral part of HTML5, SVG and canvas.

We can draw shapes like circles, rectangles, triangles.

The DOCTYPE declaration in html5 is very simple "<! DOCTYPE html>

Character encoding declaration is simple <meta charset = "UTF-8">

Audio and video are essential parts of HTML5,like: <Audio>, <Video>.

A new browser supports this.


What is HTTP?

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and
servers.

HTTP works as a request-response protocol between a client and server.

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.

The GET Method

GET is used to request data from a specified resource.

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

Some notes on GET requests:

GET requests can be cached

GET requests remain in the browser history

GET requests can be bookmarked

GET requests should never be used when dealing with sensitive data

GET requests have length restrictions

GET requests are only used to request data (not modify)

The POST Method

POST is used to send data to a server to create/update a resource.


The data sent to the server with POST is stored in the request body of the HTTP request:

POST /test/demo_form.php HTTP/1.1

Host: w3schools.com

name1=value1&name2=value2

Some notes on POST requests:

POST requests are never cached

POST requests do not remain in the browser history

POST requests cannot be bookmarked

POST requests have no restrictions on data length

Question 1: What is stored procedure?

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.

SYNTAX for creating Stored Procedure

Create procedure procedure_name

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

Create view view_name as

select column1,column2,....

from table_name

QUESTION 3: What is indexing?

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:

CREATE INDEX INDEX_NAME

ON table_Name(column_Name).

Usage: An index is used to speed up the performance of fetching the data.

Maintain unique data

No null value

Only one primary key can be created

It will create clustered index automatically Why only one primary key?

Index will arrange the data in an order

If more than one primary key, the table will Get confused in which order it needs to put the data.

Increase the performance by ordering Create Index table

If index is created, primary key is Not created

If primary key is created, index will Be created.

If primary key is deleted, the associated Index will get deleted.

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.

What is Web.Config File?

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.

Usage of configuration file

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/>

Different types of Configuration files

Machine.config - Server or machine-wide configuration file

Web.config - Application configuration files which deal with a single application

139.Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

ExampleGet your own C# Server

int MyMethod(int x)

float MyMethod(float x)

double MyMethod(double x, double y)


Consider the following example, which have two methods that add numbers of different type:

Example

static int PlusMethodInt(int x, int y)

return x + y;

static double PlusMethodDouble(double x, double y)

return x + y;

static void Main(string[] args)

int myNum1 = PlusMethodInt(8, 5);

double myNum2 = PlusMethodDouble(4.3, 6.26);

Console.WriteLine("Int: " + myNum1);

Console.WriteLine("Double: " + myNum2);

Int: 13

Double: 10.559999999999999

140.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.
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;

public class Animal{

public virtual void eat(){

Console.WriteLine("Eating...");

public class Dog: Animal

public override void eat()

Console.WriteLine("Eating bread...");

public class TestOverriding

public static void Main()

Dog d = new Dog();

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.

string s1 = "hello";//creating string using string keyword

String s2 = "welcome";//creating string using String class

C# String Example

using System;

public class StringExample

public static void Main(string[] args)

string s1 = "hello";

char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };

string s2 = new string(ch);

Console.WriteLine(s1);

Console.WriteLine(s2);

Output:

hello

csharp
143.C# Exception Handling

Exception Handling in C# is a process to handle runtime errors. We perform exception handling so


that normal flow of the application can be maintained even after runtime errors.

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

System.DivideByZeroExceptionhandles the error generated by dividing a number with zero.

System.NullReferenceExceptionhandles the error generated by referencing the null object.

System.InvalidCastException handles the error generated by invalid typecasting.

System.IO.IOException handles the Input Output errors.

System.FieldAccessException handles the error generated by invalid private or protected field


access.

C# Exception Handling Keywords

In C#, we use 4 keywords to perform exception handling:

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

Following is the syntax −

try {

// statements causing exception

} catch( ExceptionName e1 ) {

// error handling code

} catch( ExceptionName e2 ) {

// error handling code

} catch( ExceptionName eN ) {

// error handling code

} finally {

// statements to be executed

Example

Let us see an example to implement the finally block −

Live Demo

using System;

public class Demo {

int result;

Demo() {

result = 0;
}

public void division(int num1, int num2) {

try {

result = num1 / num2;

} catch (DivideByZeroException e) {

Console.WriteLine("Exception caught = {0}", e);

} finally {

Console.WriteLine("Result = {0}", result);

public static void Main(string[] args) {

Demo d = new Demo();

d.division(100, 0);

Output

This will produce the following output −

Exception caught = System.DivideByZeroException: Attempted to divide by zero.

at Demo.division(Int32 num1, Int32 num2) in d:\Windows\Temp

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 −

public delegate int MyDelegate (string s);

The preceding delegate can be used to reference any method that has a single string parameter and
returns an int type variable.

Syntax for delegate declaration is −

delegate <return type> <delegate-name> <parameter list>

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

public delegate void printString(string s);

...

printString ps1 = new printString(WriteToScreen);

printString ps2 = new printString(WriteToFile);

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;

delegate int NumberChanger(int n);

namespace DelegateAppl {

class TestDelegate {

static int num = 10;


public static int AddNum(int p) {

num += p;

return num;

public static int MultNum(int q) {

num *= q;

return num;

public static int getNum() {

return num;

static void Main(string[] args) {

//create delegate instances

NumberChanger nc1 = new NumberChanger(AddNum);

NumberChanger nc2 = new NumberChanger(MultNum);

//calling the methods using the delegate objects

nc1(25);

Console.WriteLine("Value of Num: {0}", getNum());

nc2(5);

Console.WriteLine("Value of Num: {0}", getNum());

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

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

ExampleGet your own C# Server

Create a variable of type string and assign it a value:

string greeting = "Hello";

146.ArrayList represents an ordered collection of an object that can be indexed individually. It is


basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and
sorting items in the list.

Properties of ArrayList Class:

Elements can be added or removed from the Array List collection at any point in time.

The ArrayList is not guaranteed to be sorted.

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.

It also allows duplicate elements.

Using multidimensional arrays as elements in an ArrayList collection is not supported.

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:

// C# code to create an ArrayList

using System;

using System.Collections;

using System.Collections.Generic;

class GFG {

// Driver code

public static void Main()

// Creating an ArrayList

ArrayList myList = new ArrayList();

// Adding elements to ArrayList

myList.Add("Hello");

myList.Add("World");

Console.WriteLine("Count : " + myList.Count);

Console.WriteLine("Capacity : " + myList.Capacity);

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.

Characteristics of Array Class:

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.

The default size of an Array is 2GB.

Array objects with the same array type share the same Type object.

Example:

// C# program to creating an array

// of the string as coffee name, store

// coffee name in the store,

// and prints each value.

using System;

namespace geeksforgeeks {

class GFG {

// Main Method

public static void Main()

{
// declares an 1D Array of string

string[] store;

// allocating memory for coffee names.

store = new string[] {"Americano, ", "Cafe au lait, ",

"Espresso, ", "Cappuccino, ",

"Long Black, ", "Macchiato" };

// Displaying Elements of the array

Console.WriteLine("Different types of coffee: ");

Console.WriteLine();

foreach(string coffeename in store)

Console.WriteLine(coffeename + " ");

Output:

Different types of coffee:

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;

public interface Drawable

void draw();

public class Rectangle : Drawable

public void draw()

Console.WriteLine("drawing rectangle...");

public class Circle : Drawable

public void draw()


{

Console.WriteLine("drawing circle...");

public class TestInterface

public static void Main()

Drawable d;

d = new Rectangle();

d.draw();

d = new Circle();

d.draw();

Output:

drawing ractangle...

drawing circle...

Can we create an object of an abstract class in c#?

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

abstract class Diagram {

double dim1;

double dim2;

Diagram(double a, double b) {

dim1 = a;

dim2 = b;

// area is now an abstract method

abstract double area();

class Rectangle extends Diagram {

Rectangle(double a, double b) {

super(a, b);

// override area for rectangle

double area() {

System.out.println("Inside Area for Rectangle.");

return dim1 * dim2;

class Triangle extends Diagram {

Triangle(double a, double b) {

super(a, b);

// override area for triangle

double area() {
System.out.println("Inside Area for Triangle.");

return dim1 * dim2 / 2;

public class Test {

public static void main(String args[]) {

// Diagram d = new Diagram(10, 10); // illegal now

Rectangle r = new Rectangle(9, 5);

Triangle t = new Triangle(10, 8);

Diagram diagRef; // This is OK, no object is created

diagRef = r;

System.out.println("Area of Rectangle is: " + diagRef.area());

diagRef = t;

System.out.println("Area of Triangle is:" + diagRef.area());

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

Inside Area for Rectangle.

Area of Rectangle is: 45.0

Inside Area for Triangle.

Area of Triangle is:40.0

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.

NOTE: POST is neither safe nor idempotent.

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.

151.C# Exception and It's Types

An exception is an unexpected event that occurs during program execution. For example,

int divideByZero = 7 / 0;

The above code causes an exception as it is not possible to divide a number by 0.

Let's learn about C# Exceptions in detail.

C# Exception Hierarchy

two classes derived from the base class - Exception

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:

SystemException - also called built-in exceptions

ApplicationException - also called user-defined exceptions

Let's learn about both of them in detail.


C# Built-in Exception

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.

Some of the common system exceptions are:

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.

2. ArithmeticException - This exception is thrown for errors in arithmetic, casting, or conversion. It is


a base class for exception classes like:

DivideByZeroException - This exception is thrown when an integer is divided by 0. For example,


when we try to perform 5 divided by 0.

NotFiniteNumberException - This exception is thrown when a floating-point value is positive or


negative infinity or NaN (Not-a-Number).

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

// an array containing string values

static string[] colors = { "Red", "Green", "Pink" };


static void Main()

// print the array element present at 3rd index position

Console.WriteLine(colors[3]);

Output

Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the


array.

In the above example, we are trying to access the index 3 element of the colors array element.

Since there is no element at index 3, the program throws a system exception


IndexOutOfRangeException.

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,

// user-defined exception class derived from

// the ApplicationException base class

class InvalidAgeException : ApplicationException

{
// constructor for the InvalidAgeException class

InvalidAgeException()

Console.WriteLine("Exception occurred: Invalid Age");

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.

C# Error and Exception

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.

Exceptions can be caught and handled by the program.

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.

Here are the most common types of SQL Join:

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.

ASP.NET MVC Routing

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

public class RouteConfig

public static void RegisterRoutes(RouteCollection routes)

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

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.

156.Razor supports both C# (C sharp) and VB (Visual Basic).


Main Razor Syntax Rules for C#

Razor code blocks are enclosed in @{ ... }

Inline expressions (variables and functions) start with @

Code statements end with semicolon

Variables are declared with the var keyword

Strings are enclosed with quotation marks

C# code is case sensitive

C# files have the extension .cshtml

C# Example

<!-- Single statement block -->

@{ var myMessage = "Hello World"; }

<!-- Inline expression or variable -->

<p>The value of myMessage is: @myMessage</p>

<!-- Multi-statement block -->

@{

var greeting = "Welcome to our site!";

var weekDay = DateTime.Now.DayOfWeek;

var greetingMessage = greeting + " Here in Huston it is: " + weekDay;

<p>The greeting is: @greetingMessage</p>

The value of myMessage is: Hello World

The greeting is: Welcome to our site! Here in Huston it is: Friday

158.ASP.NET MVC ViewBag

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.

159. SQL CHECK Constraint

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.

SQL Server / Oracle / MS Access:

CREATE TABLE Persons (

ID int NOT NULL,

LastName varchar(255) NOT NULL,

FirstName varchar(255),

Age int CHECK (Age>=18)

);

160.AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related


technologies like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest etc.

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.

162. .net framework


The .NET Framework is a software framework developed by Microsoft that provides a runtime
environment for building,

deploying, and

executing applications and services.

It is a comprehensive platform that includes a large library of pre-written code and tools for
developing and running applications operating systems. I

The .NET Framework consists of three main components:

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.

ASP.NET MVC- Filters

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.

Filter Type Description Built-in Filter Interface


Authorization filters: Performs authentication and authorizes before executing an action method.
[Authorize], [RequireHttps] IAuthorizationFilter

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

167.ASP.NET MVC View

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.

Creating View to the Application

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 in ASP.NET MVC

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

public abstract class ActionResult

//

// Summary:

// Initializes a new instance of the System.Web.Mvc.ActionResult class.


protected ActionResult();

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.

I have a application from where i will pass data

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.

169.What is Web API?

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.

Technically, a web application consists of two types of scripts:

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.

A web application is Human-System interaction.


Either it can be single page application just to provide information for some business, or it can be a
collection of web pages that are used to take some information from the user and providing the
services to the user.

Who uses API?

These services can be accessed by different kind of users like:

Web Browsers

Mobile applications

Desktop applications

IOTs (Internet of Things)

ASP.NET Web API

API stands for the Application Programming Interface.

"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."

170.What is View State in ASP.NET?

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.

What are the Features of the View State in ASP.NET?

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.

Kickstart Your UI/UX Career Right Here!

UI/UX Design ExpertEXPLORE PROGRAMKickstart Your UI/UX Career Right Here!

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

Array List Object

Hash Table

Custom type Converters

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 class Exercise2

{
public static void Main()

int num1, rem1;

Console.Write("\n\n");

Console.Write("Check whether a number is even or odd :\n");

Console.Write("---------------------------------------");

Console.Write("\n\n");

Console.Write("Input an integer : ");

num1= Convert.ToInt32(Console.ReadLine());

rem1 = num1 % 2;

if (rem1 == 0)

Console.WriteLine("{0} is an even integer.\n",num1);

else

Console.WriteLine("{0} is an odd integer.\n",num1);

Sample Output:

Check whether a number is even or odd :

---------------------------------------

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.

Serialization is internally used in remote applications.


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;

public Student(int rollno, string name)

this.rollno = rollno;

this.name = name;

public class SerializeExample

public static void Main(string[] args)

{
FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);

BinaryFormatter formatter=new BinaryFormatter();

Student s = new Student(101, "sonoo");

formatter.Serialize(stream, s);

stream.Close();

sss.txt:

JConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Student rollnona

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

Let's see the simple example of deserialization in C#.

using System;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

[Serializable]

class Student

public int rollno;

public string name;


public Student(int rollno, string name)

this.rollno = rollno;

this.name = name;

public class DeserializeExample

public static void Main(string[] args)

FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);

BinaryFormatter formatter=new BinaryFormatter();

Student s=(Student)formatter.Deserialize(stream);

Console.WriteLine("Rollno: " + s.rollno);

Console.WriteLine("Name: " + s.name);

stream.Close();

Output:

Rollno: 101

Name: sonoo

SQL DROP TABLE

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.

DROP TABLE "table_name";

SQL TRUNCATE TABLE

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 Vs DELETE TABLE

Truncate table is faster and uses lesser resources than DELETE TABLE command.

TRUNCATE TABLE Vs DROP TABLE

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.

TRUNCATE TABLE table_name;

For example, you can write following command to truncate the data of employee table

TRUNCATE TABLE Employee;

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.

SQL ORDER BY Clause

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:

SELECT ColumnName1,...,ColumnNameN FROM TableName ORDER BY ColumnName ASC;

Query:

mysql> SELECT *FROM customers ORDER BY Name ASC;

The SQL GROUP BY Statement

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);

Eg: SELECT COUNT(CustomerID), Country

FROM Customers

GROUP BY Country;

Inner join syntax

SELECT column_name(s)

FROM table1

INNER JOIN table2

ON table1.column_name = table2.column_name;

Eg: SELECT Orders.OrderID, Customers.CustomerName

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 one of the most common web hacking techniques.

SQL injection is the placement of malicious code in SQL statements, via web page input.

SQL in Web Pages

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):

ExampleGet your own SQL Server

txtUserId = getRequestString("UserId");

txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

How to Find Duplicate Values in a SQL Table

SELECT col1, col2, ...COUNT(*)

FROM table_name

GROUP BY col1, col2, ...

HAVING COUNT(*) > 1;

SELECT A, B, COUNT(*) AS num

FROM Geek

GROUP BY A, B

HAVING COUNT(*) > 1;

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.

Wastage and poor utilization of disk space and resources.

The likelihood of errors and inconsistencies increases.

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 the process of organizing the data in the database.

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.

Why do we need Normalization?

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

Data modification anomalies can be categorized into three types:

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.

Types of Normal Forms:

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.

Following are the various types of Normal forms:

DBMS Normalization

Normal Form Description

1NF- A relation is in 1NF if it contains an atomic value.

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.

3NF- A relation will be in 3NF if it is in 2NF and no transition dependency exists.

BCNF- A stronger definition of 3NF is known as Boyce Codd's normal form.

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

Normalization helps to minimize data redundancy.

Greater overall database organization.

Data consistency within the database.

Much more flexible database design.

Enforces the concept of relational integrity.

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.

It is very time-consuming and difficult to normalize relations of a higher degree.

Careless decomposition may lead to a bad database design, leading to serious problems.

Question 1: What is stored procedure?


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.

SYNTAX for creating Stored Procedure

Create procedure procedure_name

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

Create view view_name as

select column1,column2,....

from table_name

QUESTION 3: What is indexing?

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:

CREATE INDEX INDEX_NAME

ON table_Name(column_Name).
Usage: An index is used to speed up the performance of fetching the data.

Maintain unique data

No null value

Only one primary key can be created

It will create clustered index automatically Why only one primary key?

Index will arrange the data in an order

If more than one primary key, the table will Get confused in which order it needs to put the data.

Increase the performance by ordering Create Index table

If index is created, primary key is Not created

If primary key is created, index will Be created.

If primary key is deleted, the associated Index will get deleted.

Trigger:

A SQL trigger is a database object which fires when an event occurs in a database.

CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF }

{INSERT [OR] | UPDATE [OR] | DELETE}

ON table_name

[FOR EACH ROW]

WHEN (condition)

[trigger_body]

You might also like