100% found this document useful (1 vote)
132 views

Foreign Keys Prevents Any Actions That Would Destroy Links Between Tables With

Primary keys uniquely identify each row in a table and cannot be null. Foreign keys reference the primary key of another table to link data between tables and enforce referential integrity. Unique keys enforce uniqueness of values within a set of columns and allow one null value.

Uploaded by

Naresh Naidu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
132 views

Foreign Keys Prevents Any Actions That Would Destroy Links Between Tables With

Primary keys uniquely identify each row in a table and cannot be null. Foreign keys reference the primary key of another table to link data between tables and enforce referential integrity. Unique keys enforce uniqueness of values within a set of columns and allow one null value.

Uploaded by

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

1) What are primary keys, foreign keys and Unique Keys?

A: Primary keys are the unique identifiers for each row. They must contain unique
values and cannot be null. Due to their importance in relational databases,
Primary keys are the most fundamental of all keys and constraints.
A table can have only one Primary key. Primary key creates unique clustered
indexes

Foreign keys prevents any actions that would destroy links between tables with
the corresponding data values. A column in a table that points to the primary key
in another table. It enforces data integrity of the relationship between tables.
It can accept NULLs but it is not recommended.

Unique key enforces the uniqueness of the values in a set of columns, so no


duplicate values are entered, it uniquely identifies a row in a table and cannot be
repeated and Can accept only one NULL value. There can be more than one
unique keys in one table. Unique key creates unique non-clustered indexes

2) What is data integrity? Explain constraints?


A: Data integrity is an important feature in SQL Server. When used properly, it
ensures that data is accurate, correct, and valid. It also acts as a trap for otherwise
undetectable bugs within applications.
3) What is Stored Procedure?
A: A stored procedure is a named group of SQL statements that have been previously
created and stored in the server database. Stored procedures can be used over the
network by several clients using different input data.
Stored procedures reduce network traffic and improve performance.
Stored procedures can be used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.

4) What is Trigger ?
A: A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or
UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used
to maintain integrity of data by changing the data in a systematic fashion.

5) What is normalization?
A: Database normalization is a data design and organization process applied to data
structures based on rules that help build relational databases. Normalization usually
involves dividing a database into two or more tables and defining relationships
between the tables.

6) What is De-normalization?
A: De-normalization is the process of attempting to optimize the performance of a
database by adding redundant data. It is a technique to move from higher to lower
normal forms of database modeling in order to speed up database access.
7) What is View?
A: A simple view can be thought of as a subset of a table. It can be used for retrieving
data, as well as updating or deleting rows. Views are database objects which are
mainly used to implement security at rows and columns levels on the base table.
• One can create a view on top of other views.
• View just needs a result set (SELECT statement).We use views just like regular
tables when it comes to query writing. (joins, sub-queries, grouping....)
• We can perform DML operations (INSERT, DELETE, UPDATE) on a view.
• It actually affects the underlying tables only those columns can be affected which
are visible in the view.

Types of views:
Regular View: It is a type of view in which you are free to make any DDL
changes on the underlying table.
Schema binding View: It is a type of view in which the schema of the view
(column) are physically bound to the schema of the
underlying table. We are not allowed to perform any
DDL changes to the underlying table for the columns
that are referred by the schema binding view structure.
Indexed View
8) What is Index?
A: An index is a physical structure containing pointers to the data. Indices are created in
an existing table to locate rows more quickly and efficiently. It is possible to create an
index on one or more columns of a table, and each index is given a name. Effective
indexes are one of the best ways to improve performance in a database application.

9) What is the difference between clustered and a non-clustered index?


A: A clustered index is a special type of index that reorders the way records in the table
are physically stored. Therefore table can have only one clustered index. The leaf
nodes of a clustered index contain the data pages.
A non-clustered index is a special type of index in which the logical order of the index
does not match the physical stored order of the rows on disk. The leaf node of a
non-clustered index does not consist of the data pages. Instead, the leaf nodes
contain index rows.

10) What are the SET Operators?


A: SQL set operators allows you to combine results from two or more SELECT statements.
Syntax: SELECT Col1, Col2, Col3 FROM T1
<SET OPERATOR>
SELECT Col1, Col2, Col3 FROM T2
Rule 1: The number of columns in first SELECT statement must be same as the number
of columns in the second SELECT statement.
Rule 2: The metadata of all the columns in first SELECT statement must be exactly same
as the metadata of all the columns in second SELECT statement accordingly.
Rule 3: ORDER BY clause do not work with first SELECT statement.
UNION, UNION ALL, INTERSECT, EXCEPT

11) What are Sequence Objects in SQL Server


A: Sequence objects are used to sequentially generate numeric values. They were
introduced in SQL Server 2012.
Sequence objects are similar to the IDENTITY column in any SQL table. However,
unlike the IDENTITY column, they are independent and are not attached to any
table.
Sequence objects are used both independently and within the DML statements i.e.
INSERT, UPDATE and DELETE.

Syntax :
CREATE SEQUENCE [schema].[Name_of_Sequence]
[ AS <data type> ]
[ START WITH <value> ]
[ INCREMENT BY <value> ]
Ex: CREATE SEQUENCE [dbo].[NewCounter]
AS INT
START WITH 5
INCREMENT BY 5
12) Explain Execution Plan.
A: To Execute a Query we make an execution plan.
Execution Plan is a plan to execute a query with the most optimal way which is
generated by Query Optimizer.
Every query has an execution plan.

Query Optimizer analyzes statistics, resources used, I/O and CPU processing time
and etc. and comes up with a number of plans. Then it evaluates those plans and
the most optimized plan out of the plans is Execution Plan. It is shown to users as a
graphical flow chart that should be read from right to left and top to bottom.

13) What are packages?


A: A package is an organized collection of connections, control flow elements, data
flow elements, event handlers, variables, parameters, and configurations, that you
assemble using either the graphical design tools that SQL Server Integration
Services provides, or build programmatically.
14) What is a synonym in SQL Server?
A: In SQL Server, a synonym is an alias or alternative name for a database object such
as a table, views, stored procedure, user-defined function, and sequence.

It Provides an alternative name for another database object, referred to as the base
object, that can exist on a local or remote server.
A synonym provides you with many benefits if you use it properly.

SQL Server CREATE SYNONYM statement syntax


To create a synonym, you use the CREATE SYNONYM statement as follows:
1CREATE SYNONYM [ schema_name_1. ] synonym_name
2 FOR object;
The object is in the following form:
1 [ server_name.[ database_name ] . [ schema_name_2 ]. object_name
In this syntax:

First, specify the target object that you want to assign a synonym in the FOR clause
Second, provide the name of the synonym after the CREATE SYNONYM keywords

Note: The object for which you create the synonym does not have to exist at the time
the synonym is created.
15) What is cursors?
A: Cursor is a database object used by applications to manipulate data in a set on a
row-by-row basis, instead of the typical SQL commands that operate on all the
rows in the set at one time.

In order to work with a cursor we need to perform some steps in the following
order:
Declare cursor
Open cursor
Fetch row from the cursor
Process fetched row
Close cursor
Deallocated cursor

16) What is the use of DBCC commands?


A: DBCC stands for database consistency checker. We use these commands to
check the consistency of the databases, i.e., maintenance, validation task and
status checks.

E.g.: DBCC CHECKDB - Ensures that tables in the db and the indexes are
correctly linked.
DBCC CHECKALLOC - To check that all pages in a db are correctly allocated.
DBCC CHECKFILEGROUP - Checks all tables file group for any damage.
17) What is difference between DELETE & TRUNCATE commands?
A: Delete command removes the rows from a table based on the condition that we
provide with a WHERE clause.
Truncate will actually remove all the rows from a table and there will be no data
in the table after we run the truncate command.

18) What is SQL Profiler?


A: SQL Profiler is a graphical tool that allows system administrators to monitor
events in an instance of Microsoft SQL Server. You can capture and save data
about each event to a file or SQL Server table to analyze later.
For example, you can monitor a production environment to see which stored
procedures are hampering performance by executing too slowly.

Use SQL Profiler to monitor only the events in which you are interested.
Monitoring too many events adds overhead to the server.

19) What types of Joins are possible with Sql Server?


A: Joins are used in queries to explain how different tables are related. Joins also
let you select data from a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs.
OUTER JOINs are further classified as,
LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
INNER JOIN: Gets all the matching records from both the left and right tables
based on joining columns.

CROSS JOIN: Returns the Cartesian product.

OUTER JOIN:

Left Outer Join: Gets all non-matching records from left table &
AND one copy of matching records from both the tables based on
the joining columns.

Right Outer Join: Gets all non-matching records from right table
& AND one copy of matching records from both the tables based on
the joining columns.

Full Outer Join: Gets all non-matching records from left table &
all non-matching records from right table & one copy of matching
records from both the tables.

SELF JOIN: Joining a table to itself

Restricted Left Outer Join: gets all non-matching records from left side
Restricted Right Outer Join : gets all non-matching records from right side
20) What is a sub-query?
A: It is a query within a query
Syntax: SELECT <column_name> FROM <table_name>
WHERE <column_name> IN/NOT IN
(
<another SELECT statement>
)
Everything that we can do using sub queries can be done using Joins, but anything
that we can do using Joins may/may not be done using Sub-query.

Sub-Query consists of an inner query and outer query.


Inner query is a SELECT statement the result of which is passed to the outer
query.
Outer query can be SELECT, UPDATE, DELETE. The result of the inner query is
generally used to filter what we select from the outer query.

We can also have a sub-query inside of another sub-query and so on. This is called
a nested Sub-query. Maximum one can have is 32 levels of nested Sub-Queries.
21) What are parameters?
A: Parameters are used to exchange data between stored procedures and functions
and the application or tool that called the stored procedure or function:
Input parameters allow the caller to pass a data value to the stored procedure or
function.
Output parameters allow the stored procedure to pass a data value or a cursor
variable back to the caller. User-defined functions cannot specify output
parameters.

Every stored procedure returns an integer return code to the caller. If the stored
procedure does not explicitly set a value for the return code, the return code is 0.

22) What is a function in Sql ?


A: A function is a database object in SQL Server. Basically, it is a set of SQL statements
that accept only input parameters, perform actions and return the result.
A function can return an only a single value or a table. We can’t use a function to
Insert, Update, Delete records in the database tables.

Types of SQL Server Function


User Defined function: User defined functions are create by a user.
System Defined Function: System functions are built in database functions.
23) What is User Defined Functions and System Defined Functions?
A: User-Defined Functions allow to define its own T-SQL functions that can accept 0 or
more parameters and return a single scalar data value or a table data type.
UDFs are a database object and a precompiled set of TSQL

There are three types of User-Defined functions in SQL Server 2000


1. Scalar,
2. Inline Table-Valued and
3. Multi-statement Table-valued.

System Defined Function are defined by SQL Server for a different purpose.

We have two types of system defined function in SQL Server


1. Scalar Function: Scalar functions operates on a single value and returns a single
value.
2. Aggregate Functions: SQL Server aggregate functions perform a calculation on a
set of values and return a single value. With the exception
of the COUNT aggregate function.
All other aggregate functions ignore NULL values.
Aggregate functions are frequently used with the GROUP BY
clause of the SELECT statement.
24) What are Temporary Tables and difference between a local and a global variable?

A: They are tables just like regular tables but the main difference is its scope.
The scope of temp tables is temporary whereas regular tables permanently reside.
Temporary table are stored in tempDB.
We can do all kinds of SQL operations with temporary tables just like regular tables
like JOINs, GROUPING, ADDING CONSTRAINTS etc.

Two types of Temporary Variables :


1) A local temporary table
2) A Global temporary table

1) A local temporary Table:


It exists only for the duration of a connection or, if defined inside a compound
statement, for the duration of the compound statement.
■ Local
● #LocalTempTableName -- single pound sign
● Only visible in the session in which they are created.
● It is session-bound.
2) A global temporary table :
It remains in the database permanently, but the rows exist only within a given
connection. When connection are closed, the data in the global temporary table
disappears. However, the table definition remains with the database for access
when database is opened next time.
■ Global
● ##GlobalTempTableName -- double pound sign
● Global temporary tables are visible to all sessions after they are created,
and are deleted when the session in which they were created in is
disconnected.
● It is last logged-on user bound. In other words, a global temporary table
will disappear when the last user on the session logs off.

25) Explain Variables.


A: Variable is a memory space (place holder) that contains a scalar value EXCEPT
table variables, which is 2D data.
Variable in SQL Server are created using DECLARE Statement.
Variables are BATCH-BOUND.
Variables that start with @ are user-defined variables.
○ Syntax: DECLARE @var INT
Variables that start with @@ are system variables.
26) What is Table Variable? Explain its advantages and disadvantages.
A: If we want to store tabular data in the form of rows and columns into a variable
then we use a table variable.
t is able to store and display 2D data (rows and columns).
We cannot perform DDL (CREATE, ALTER, DROP).

Advantages:
■ Table variables can be faster than permanent tables.
■ Table variables need less locking and logging resources.
Disadvantages:
■ Scope of Table variables is batch bound.
■ Table variables cannot have constraints.
■ Table variables cannot have indexes.
■ Table variables do not generate statistics.
■ Cannot ALTER once declared (Again, no DDL statements).
27) What are the differences between Temporary Table and Table Variable?

A:
Temporary Table Table Variable
Statement (or Can perform both Can perform only
Operation) DML and DML, but not
DDL DDL

Scope Session bound Batch bound


Syntax CREATE TABLE DECLARE @var
#temp TABLE(...)
Index Can have indexes Cannot have
indexes
28) What are Derived Tables in SQL?
A: A derived table is a technique for creating a temporary set of records which can
be used within another query in SQL. You can use derived tables to shorten long
queries, or even just to break a complex process into logical steps.

29) What is CTE?


A: The CTE is an abbreviation of “Common Table Expression.” CTE was introduced in
SQL Server. It works as a temporary result set that is defined within the execution
scope of a single select, insert, update, delete statements. CTE is typically the
result of complex sub queries. Similar to temporary tables CTE doesn’t store as an
object; the scope is limited to the current query. CTE improves readability and
ease in maintenance of complex queries and sub-queries.
CTE is easy to implement compared to complex queries which involves several
sub-queries.

Ex : WITH CTE(Emp_ID, Emp_Name, Project_Name)


AS
(
SELECTe.Emp_Id, e.EmployeeName, p.Project_NameFROMdbo.Employee e
INNERJOIN dbo.Project p ON e.Emp_Id = p.Project_Id
)
SELECT * FROM CTE
30) What are OLTP and OLAP and what’s the difference between OLTP and OLAP?
A: OLTP stands for Online Transactional Processing
OLAP stands for Online Analytical Processing
OLTP OLAP

Normalization highly normalized highly de-normalized


Level
Usage database data warehouse
Data type current data historical data
Processing fast for delta operations fast for read operations
Speed (dml)
Purpose to control and run business to help with analyzing
tasks business information
Size many small tables few big flat tables
Operation delta operation (update, read operation (select)
insert, delete) aka DML Terms Used table,
columns and
relationships
dimension table, fact table
31). How differently would you use CHAR() and VARCHAR()?
A: VARCHAR() is used when you are not sure about the maximum length of its
value (for variable length). VARCHAR() is also used for saving memories as well.
■ Ex: first name, last name, email...
CHAR() is used when you know the length of fixed characters.
■ Ex: SSN, Phone Number...

You can do VARCHAR(MAX). MAX can contain information up to 2gb.

32) What are DDL,DML,TCL and DCL commands?


A:
DML
DML is abbreviation of Data Manipulation Language. It is used to retrieve,
store, modify, delete, insert and update data in database.
SELECT – Retrieves data from a table
INSERT – Inserts data into a table
UPDATE – Updates existing data into a table
DELETE – Deletes all records from a table
DDL
DDL is abbreviation of Data Definition Language. It is used to create and
modify the structure of database objects in database.
CREATE – Creates objects in the database
ALTER – Alters objects of the database
DROP – Deletes objects of the database
TRUNCATE – Deletes all records from a table and resets table identity to
initial value.

DCL
DCL is abbreviation of Data Control Language. It is used to create roles,
permissions, and referential integrity as well it is used to control access to database
by securing it.
GRANT – Gives user’s access privileges to database
REVOKE – Withdraws user’s access privileges to database given with the
GRANT command
TCL
TCL is abbreviation of Transactional Control Language. It is used to manage
different transactions occurring within a database.
COMMIT – Saves work done in transactions
ROLLBACK – Restores database to original state since the last COMMIT
command in transactions
SAVE TRANSACTION – Sets a savepoint within a transaction

You might also like