You are on page 1of 8

SQL MT

1.What is the role of Statics IO?Explain with syntax and example.

ANS-Causes SQL Server to display information regarding the amount of disk activity
generated by Transact-SQL statements.
SYNTAX-
SET STATISTICS IO { ON | OFF }

When STATISTICS IO is ON, statistical information is displayed. When OFF, the


information is not displayed.
After this option is set ON, all subsequent Transact-SQL statements return the
statistical information until the option
is set to OFF.
EX-
This example shows how many logical and physical reads are used by SQL Server as
it processes the statements.
USE AdventureWorks2012;
GO
SET STATISTICS IO ON;
GO
SELECT *
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
GO
SET STATISTICS IO OFF;
GO

2.what are joins? explain the various type of joins.

ANS-The SQL Joins clause is used to combine records from two or more tables in a
database. A JOIN is a means for
combining fields from two tables by using values common to each.

SQL Join Types:


There are different types of joins available in SQL:

INNER JOIN: returns rows when there is a match in both tables.

LEFT JOIN: returns all rows from the left table, even if there are no matches in
the right table.

RIGHT JOIN: returns all rows from the right table, even if there are no matches in
the left table.

FULL JOIN: returns rows when there is a match in one of the tables.

SELF JOIN: is used to join a table to itself as if the table were two tables,
temporarily renaming at least one
table in the SQL statement.

CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two
or more joined tables.

JOIN =JOIN TWO TABLE DATA.An SQL JOIN clause is used to combine rows from two or
more tables, based
on a common field between them.
INNER JOIN(simple join)= check on behalf same record condition.its the default
join.
An SQL INNER JOIN return all rows from multiple tables where the join condition
is met.
Returns all rows when there is at least one match in BOTH tables

select pr.sid,pr.name,pr.marks,pl.address from performance pr join personal


personal pl pr.sid=pl.sid

outer join= display all match record and show null on not match record

left outer join= all record first table and matching record of second table
select pr.sid,pr.name,pr.marks,pl.address from performance pr left outer
join personal
personal pl pr.sid=pl.sid
right outer join= all record first table and matching record of second table
select pr.sid,pr.name,pr.marks,pl.address from performance pr right outer
join personal
personal pl pr.sid=pl.sid
full outer join= all record first table and second table matching record one time
noT matching record =null
select pr.sid,pr.name,pr.marks,pl.address from performance pr right outer
join personal
personal pl pr.sid=pl.sid

cross join= match each record one table to each record of second table.multiply
from coloumn.

equi join= display all coloumn.USING foreign key.


SELECT * FROM HumanResources.EmployeeDepartmentHistory D JOIN
HumanResources.Employee E ON D.EmployeeID=E.EmployeeID JOIN
HumanResources.Department P ON P.DepartmentID=D.DepartmentID

self join= join table itself.

3.DBCC Command=?

ANS-The Transact-SQL programming language provides DBCC statements that act as


Database Console Commands for SQL Server.
Database Console Command statements are grouped into the following categories.
Command category
Perform
Maintenance
Maintenance tasks on a database, index, or filegroup.
Miscellaneous
Miscellaneous tasks such as enabling trace flags or removing a DLL from memory.
Informational
Tasks that gather and display various types of information.
Validation
Validation operations on a database, table, index, catalog, filegroup, or
allocation of database pages.
DBCC commands take input parameters and return values. All DBCC command parameters
can accept both Unicode and DBCS
literals.

4.What is the use of the FOR XML clause in SQL Server? What are the various models
of the FOR XML clause?
ANS-A SELECT query returns results as a rowset. You can optionally retrieve formal
results of a SQL query as XML
by specifying the FOR XML clause in the query. The FOR XML clause can be used in
top-level queries and in sub queries.
The top-level FOR XML clause can be used only in the SELECT statement. In sub
queries, FOR XML can be used in the
INSERT, UPDATE, and DELETE statements. It can also be used in assignment
statements.
In a FOR XML clause, you specify one of these modes:
RAW
AUTO
EXPLICIT
PATH
The RAW mode generates a single <row> element per row in the rowset that is
returned by the SELECT statement. You can
generate XML hierarchy by writing nested FOR XML queries.

The AUTO mode generates nesting in the resulting XML by using heuristics based on
the way the SELECT statement is
specified. You have minimal control over the shape of the XML generated. The nested
FOR XML queries can be written
to generate XML hierarchy beyond the XML shape that is generated by AUTO mode
heuristics.

The EXPLICIT mode allows more control over the shape of the XML. You can mix
attributes and elements at will in
deciding the shape of the XML. It requires a specific format for the resulting
rowset that is generated because of
query execution. This rowset format is then mapped into XML shape. The power of
EXPLICIT mode is to mix attributes
and elements at will, create wrappers and nested complex properties, create space-
separated values

The PATH mode together with the nested FOR XML query capability provides the
flexibility of the EXPLICIT mode
in a simpler manner.

These modes are in effect only for the execution of the query for which they are
set. They do not affect the
results of any subsequent queries.
FOR XML is not valid for any selection that is used with a FOR BROWSE clause.
Example
The following SELECT statement retrieves information from the Sales.Customer and
Sales.SalesOrderHeader tables
in the AdventureWorks2012 database. This query specifies the AUTO mode in the FOR
XML clause:
USE AdventureWorks2012
GO
SELECT Cust.CustomerID,
OrderHeader.CustomerID,
OrderHeader.SalesOrderID,
OrderHeader.Status
FROM Sales.Customer Cust
INNER JOIN Sales.SalesOrderHeader OrderHeader
ON Cust.CustomerID = OrderHeader.CustomerID
FOR XML AUTO

2.explain the use of PIVOT and UNPIVOT clauses in SQL Server?


ANS-CREATE SUMMMARIZED DATA REPORTS USING PIVOT CLAUSE.USING SELECT STATEMENT.
UNPIVOT USE TO NORMALIZE THE DATA .
You can use the PIVOT and UNPIVOT relational operators to change a table-valued
expression into another table.
PIVOT rotates a table-valued expression by turning the unique values from one
column in the expression into multiple
columns in the output, and performs aggregations where they are required on any
remaining column values that are
wanted in the final output. UNPIVOT performs the opposite operation to PIVOT by
rotating columns of a
table-valued expression into column values.

The syntax for PIVOT provides is simpler and more readable than the syntax that may
otherwise be specified in a
complex series of SELECT...CASE statements. For a complete description of the
syntax for PIVOT, see FROM (Transact-SQL).
The following is annotated syntax for PIVOT.
SELECT <non-pivoted column>,
[first pivoted column] AS <column name>,
[second pivoted column] AS <column name>,
...
[last pivoted column] AS <column name>
FROM
(<SELECT query that produces the data>)
AS <alias for the source query>
PIVOT
(
<aggregation function>(<column being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
<optional ORDER BY clause>;

Basic PIVOT Example


The following code example produces a two-column table that has four rows.
USE AdventureWorks2008R2 ;
GO
SELECT DaysToManufacture, AVG(StandardCost) AS AverageCost
FROM Production.Product
GROUP BY DaysToManufacture;

UNPIVOT performs almost the reverse operation of PIVOT, by rotating columns into
rows. Suppose the table produced
in the previous example is stored in the database as pvt, and you want to rotate
the column identifiers Emp1,
Emp2, Emp3, Emp4, and Emp5 into row values that correspond to a particular vendor.
This means that you must
identify two additional columns. The column that will contain the column values
that you are rotating
(Emp1, Emp2,...) will be called Employee, and the column that will hold the values
that currently reside
under the columns being rotated will be called Orders. These columns correspond to
the pivot_column and
value_column, respectively, in the Transact-SQL definition. Here is the query.
--Create the table and insert values as portrayed in the previous example.
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO

3.Guidelines of VIEW?

ANS-You can create views only in the current database. However, the tables and
views referenced by the new view
can exist in other databases or even other servers if the view is defined using
distributed queries.
View names must follow the rules for identifiers and must be unique for each
schema. Additionally, the name must
not be the same as any tables contained by that schema.
You can build views on other views. Microsoft SQL Server allows views to be nested.
Nesting may not exceed 32 levels.
The actual limit on nesting of views may be less depending on the complexity of
the view and the available memory.
You cannot associate rules or DEFAULT definitions with views.
You cannot associate AFTER triggers with views, only INSTEAD OF triggers.
The query defining the view cannot include the COMPUTE or COMPUTE BY clauses, or
the INTO keyword.
The query defining the view cannot include the ORDER BY clause, unless there is
also a TOP clause in the select list
of the SELECT statement.
The query defining the view cannot contain the OPTION clause specifying a query
hint.
The query defining the view cannot contain the TABLESAMPLE clause.
You cannot define full-text index definitions on views.
You cannot create temporary views, and you cannot create views on temporary tables.
Views, tables, or functions participating in a view created with the SCHEMABINDING
clause cannot be dropped, unless
the view is dropped or changed so that it no longer has schema binding. In
addition, ALTER TABLE statements on tables
that participate in views having schema binding will fail if these statements
affect the view definition.
If a view is not created with the SCHEMABINDING clause, sp_refreshview should be
run when changes are made to the
objects underlying the view that affect the definition of the view. Otherwise, the
view might produce unexpected
results when it is queried.
You cannot issue full-text queries against a view, although a view definition can
include a full-text query if the
query references a table that has been configured for full-text indexing.
You must specify the name of every column in the view if:
Any of the columns in the view are derived from an arithmetic expression, a built-
in function, or a constant.
Two or more of the columns in the view would otherwise have the same name (usually
because the view definition
includes a join and the columns from two or more different tables have the same
name).
You want to give any column in the view a name different from the column from which
it is derived. (You can also
rename columns in the view.) A view column inherits the data type of the column
from which it is derived, whether
or not you rename it.
NoteNote
This rule does not apply when a view is based on a query containing an outer join,
because columns may change
from not allowing null values to allowing them.

4.Denormlization=?

ANS-Denormalization is the process of attempting to optimize the performance of a


database by adding redundant data
or by grouping data. In some cases, denormalization helps cover up the
inefficiencies inherent in relational database
software. A relational normalized database imposes a heavy access load over
physical storage of data even if it is well
tuned for high performance.

1.User defined function? explain also.

ANS-SQL Server user-defined functions are routines that accept parameters, perform
an action, such as a
complex calculation, and return the
result of that action as a value. The return value can either be a single scalar
value or a result set.
Types of Functions
Scalar Function
User-defined scalar functions return a single data value of the type defined in the
RETURNS clause. For an inline
scalar function, there is no function body; the scalar value is the result of a
single statement. For a multistatement
scalar function, the function body, defined in a BEGIN...END block, contains a
series of Transact-SQL statements
that return the single value. The return type can be any data type except text,
ntext, image, cursor, and timestamp.
Table-Valued Functions
User-defined table-valued functions return a table data type. For an inline table-
valued function, there is no
function body; the table is the result set of a single SELECT statement.
System Functions
SQL Server provides many system functions that you can use to perform a variety of
operations. They cannot be
modified. For more information, see Built-in Functions (Transact-SQL), System
Stored Functions (Transact-SQL),
and Dynamic Management Views and Functions (Transact-SQL).

2.what are various command used to control the data access and updated? explain
with syntax.

ANS-DDL
Data Definition Language (DDL) statements are used to define the database structure
or schema. Some examples:
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
COMMENT - add comments to the data dictionary
RENAME - rename an object
DML

Data Manipulation Language (DML) statements are used for managing data within
schema objects. Some examples:
SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency
DCL

Data Control Language (DCL) statements. Some examples:


GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command
TCL

Transaction Control (TCL) statements are used to manage the changes made by DML
statements. It allows statements
to be grouped together into logical transactions.
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
SET TRANSACTION - Change transaction options like isolation level and what rollback
segment to use

3.Transaction and possess of ACID ?

ANS-ACID properties

When a transaction processing system creates a transaction, it will ensure that the
transaction will have certain
characteristics. The developers of the components that comprise the transaction
are assured that these characteristics
are in place. They do not need to manage these characteristics themselves. These
characteristics are known as the ACID
properties. ACID is an acronym for atomicity, consistency, isolation, and
durability.
Atomicity
The atomicity property identifies that the transaction is atomic. An atomic
transaction is either fully completed, or
is not begun at all. Any updates that a transaction might affect on a system are
completed in their entirety. If for
any reason an error occurs and the transaction is unable to complete all of its
steps, the then system is returned to
the state it was in before the transaction was started. An example of an atomic
transaction is an account transfer
transaction. The money is removed from account A then placed into account B. If
the system fails after removing the
money from account A, then the transaction processing system will put the money
back into account A, thus returning
the system to its original state. This is known as a rollback, as we said at the
beginning of this chapter..
Consistency
A transaction enforces consistency in the system state by ensuring that at the end
of any transaction the system is
in a valid state. If the transaction completes successfully, then all changes to
the system will have been properly
made, and the system will be in a valid state. If any error occurs in a
transaction, then any changes already made
will be automatically rolled back. This will return the system to its state before
the transaction was started.
Since the system was in a consistent state when the transaction was started, it
will once again be in a consistent
state.
Looking again at the account transfer system, the system is consistent if the total
of all accounts is constant.
If an error occurs and the money is removed from account A and not added to
account B, then the total in all accounts
would have changed. The system would no longer be consistent. By rolling back the
removal from account A, the total
will again be what it should be, and the system back in a consistent state.
Isolation
When a transaction runs in isolation, it appears to be the only action that the
system is carrying out at one time.
If there are two transactions that are both performing the same function and are
running at the same time,
transaction isolation will ensure that each transaction thinks it has exclusive use
of the system. This is
important in that as the transaction is being executed, the state of the system may
not be consistent. The
transaction ensures that the system remains consistent after the transaction ends,
but during an individual
transaction, this may not be the case. If a transaction was not running in
isolation, it could access data
from the system that may not be consistent. By providing transaction isolation,
this is prevented from happening.
Durability
A transaction is durable in that once it has been successfully completed, all of
the changes it made to the
system are permanent. There are safeguards that will prevent the loss of
information, even in the case of
system failure. By logging the steps that the transaction performs, the state of
the system can be recreated
even if the hardware itself has failed. The concept of durability allows the
developer to know that a completed
transaction is a permanent part of the system, regardless of what happens to the
system later on.

4. Statics? how can be created &updated?

You might also like