Vous êtes sur la page 1sur 95

R4R provide basic SQL Tutorials concept with SQL Examples .

Through R4R you can


develop SQL programming concept. R4R provide SQL Interview Questions with
answers.R4R provide SQL Languages study materials in easy way.

SQL Tutorials

1.1 SQL Basics With Examples

SQL Interview Questions with Answers

2.1 SQL Subjective Questions with Answers


2.2 SQL Interview Questions with Answers
2.3 SQL Objective Questions And Answers
2.4 RDBMS FAQS
2.5 Oracle interview Questions
2.6 SQL FAQS

SQL Basics With Examples

1. Introduction (Database)
2. Keys & Level of Abstraction
3. Normalization
4. Other Database Model
5. Codd's Twelve Rules
6. Introduction (SQL)
7. Data types in SQL Server
8. Start with SQL Server

DATABASE

Database is an important constituent for collection and storage of data. Data provided
information after processing on them. To managing record and important data Databases
server used. Database transaction is a unit of work in database management system.
Database transaction must follow term ACID (Atomicity, Consistency, Isolation, Durability).
Any transaction started then till it completion, that transaction follow ACID, for successful
and no error. The ability to modify the schema definition in one level should not affect the
schema definition in the next higher level is called Data Independence. The application is
independent of the storage structure and access strategy of data.
Two types of Data Independence are:

1. Logical Data Independence: It is more difficult to achieve. Modification in logical level


should affect the view level.
2. Physical Data Independence: Modification in physical level should not affect the logical
level.

ACID Property
Means atomicity, consistency, isolation and durability.

Atomicity: Each transaction is said to be atomic". Means if any part of transaction fail then
whole transaction failed. In a word say "ALL OR NOTHING". The failure of transaction
commonly depend on Hard disk fail, System crash.

Consistency: Consistency means only valid data will be written to the database. If any
transaction violate any consistency rule of database the whole transaction is Rollback,
means it starts again from beginning. Each state in transaction must be consistent for
database.

Isolation: If two transactions occurs at a time then both are not impact to each other,
separate completion of each transaction. The isolation property does not ensure which
transaction will execute first, merely that they will not interfere with each other. If second
transaction depend on first then it will done, and data update after completion of traction.

Durability: Ensures that any transaction committed to the database will not be lost.
Durability is ensured through the use of database backups and transaction logs that
facilitate the restoration of committed transactions in spite of any subsequent software or
hardware failures.

KEYS

A database key is a attribute utilized to sort and identify data in some manner.
There are many keys:

1. Primary key: The primary key is a attribute of a relational table uniquely identifies the
each tuple of a table or each record in the table. It can either be a normal attribute that is
guaranteed to be unique. Such as Social Security Number in a table with no more than one
record per person. Examples: Imagine we have a employees table that contains a record for
each employee at a organization. The employee's unique employee ID number would be a
good choice for a primary key in the employees table. The employee's first and last name
would not be a good choice, as there is always the chance that more than one employee
might have the same name.

2. Foreign Key: These keys are used to create relationships between tables. Natural
relationships exist between tables in most database structures. Example: Lets assume that
the Departments table uses the Department Name column as the primary key. To create a
relationship between the two tables, we add a new column to the Employees table called
Department. We then fill in the name of the department to which each employee belongs.
We also inform the database management system that the Department column in the
Employees table is a foreign key that references the Departments table. The database will
then enforce referential integrity by ensuring that all of the values in the Departments
column of the Employees table have corresponding entries in the Departments table.

3. Candidate key, Alternate key and Composite key: Any number of attributes that are
uniquely identifying a row in a table is candidate key for the table. We select one of the
candidate key as Primary key. All candidate keys which are not chosen as "primary key" are
Alternate keys. The key which uniquely identify the rows of the table and which is made
up of more than one attribute is called composite key.
For Example: In a class we have to select Class Representative. So A, B, C and D stand for
that post. So A, B, C and D are candidate for Class Representative so these are candidate
key. We select B as Class Representative so B is primary key and A, C and D can be Class
Representative but not selected as a Class Representative so they are alternative choice. So
A, C and D are alternate key. When two students of class work together in a project then
they are composite key for the class.

LEVELS OF ABSTRACTION

Physical Level: Physical level is the lower level of abstraction. Its define how data is stored
in database.

Logical Level: The next higher level of abstraction, its describe what data be store and
each logical operation done at this level, links and concept apply here.

View Level: This is the higher level describe only part of entire database for a particular
user.

NORMALIZATION

Some rules that should followed to achieve a good database design are:

1. Each table should have an identifier.


2. Each table should store data for a single type entity
3. Columns that should store data for a single type of entity.
4. The repetition of values or columns should be avoided.

To remove the redundancy of a table as called Normalization. In other words duplicity or


repetitions of data never occur in database. Normalization is mainly minimizing redundancy,
insertion, deletion and update anomalies. Normalization achieve through functional
dependency. Normalization is much type.

Functional Dependency: Functional dependencies (FDs) are used to specify formal


measures of the "goodness" of relational designs and used to define normal forms for
relations. FDs are constraints that are derived from the meaning and interrelationships of
the data attributes. FDs are derived from the real-world constraints on the attributes
For example: A set of attributes X functionally determines a set of attributes Y if the value
of X determines a unique value for Y
X-->Y holds if whenever two tuples have the same value for X, they must have the same
value for Y If t1[X] =t2[X], then t1[Y] =t2[Y] in any relation instance r(R)
X-->Y in R specifies a constraint on all relation instances r(R)

Fully Functional dependency: A functional dependency X --> Y is full functional


dependency if any attribute A removed from X. It means that the dependency does not hold
any more then it is not Fully Functional dependence. Means each attribute is functionally
dependent.

All categories are in sequential order:

1.1NF: There is no repetition of values and data in table known as 1NF. In other words the
1NF disallows composite attributes, multivalued attributes, and nested relations, attributes
whose values for an individual tuple are non-atomic.

2.2NF: A relation schema R is in 2NF when it is in 1NF and every non-prime attribute A in R
is fully functionally dependent on primary key.

3.3NF: A relation schema R is in 3NF ,It is in 2NF and no non-prime attribute A in R is


transitively dependent on the primary key. Transitive dependent means if there a set of
attribute Z that are neither a primary or candidate key and both X-->Z and Y-->Z holds.

4.BCNF: 3NF inadequate in some situation then it was not satisfactory for the table:

1. That had multiple candidate keys.


2. Where the multiple candidate keys were composite.
3. Where the multiple candidate keys were overlapped.

A relation schema R is in BCNF, It is in 3NF and additional constraints that for every FD X ->
A, X must be a candidate key. "A relation is in the Boyce-Codd normal form (BCNF) if and
only if every determinant is a candidate key "

5.4NF: A relation schema R is said to be in 4NF, it is in BCNF and for every Multivalued
dependency X --> Y that holds over R, Either X is subset or equal to (or) XY = R. or X is a
super key.

6.5NF: A relation schema R is said to be in 5 NF, it is in 4NF and relation schema R is said
to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one the following is
true Ri = R for some i. and The join dependency is implied by the set of FD, over R in which
the left side is key of R.
Demoralization

The intentional introduction of redundancy in a table in order to improve performance is


called demoralization. The decision to demoralize results in a trade-off performance and
data integrity. Demoralization increases disk utilization.

OTHER DATABASE MODELS

Relational Database Model

Data represent in form of column and row, column means attribute and row means touples
present instance of data. This Database model came into existence with help of
mathematical concepts. Its using some other concepts like normalization, touple relational
calculus.

E-R Model in Database

E-R model stands for Entity-Relationship model. This data model is based on real world that
consists of basic objects called entities and of relationship among these objects. Entity in
database, which existence in real world with number of attributes. In a table attribute know
as column. Relationship is a logical thing which relates entities. The E-R diagram shows
structure of E-R model.

Object Oriented Database Model

This model is based on collection of objects. An object is instance variables which store
value and bodies of code, that codes are called method. These codes have written to
operate the objects. Objects that contain same types of values and the same methods are
grouped together into classes. In other words classes are a group of object. This model also
follows the some concept related to the OOPs
Hierarchical model of Database

The word hierarchy means tree form relationship, like a tree with branches. Means
Relationship formed like tree structure in a database called hierarchical model. With this
database you form relationship among many tables with certain concept. It has a downward
link to describe the nesting and they are arranged in a particular order down the same level
of the list.

Network model

This model provides greater flexibility and easy access to data. This model provide logical
relationship among many parent database. But implementing this model is more difficult
due to time consuming and cost. Its flexible because through link easily accessing of
information.

XML Database

XML databases came into existence in 2000. This database lets you organize data
irrespective of whether it is organized or not. This data can exported and serialized into the
desired format. Two major classes of XML database exist:
1. XML-enabled
2. Native XML

Codd's Twelve Rules

1. The information rule: This rule require all information to be represented as data values
in the rows and column of table.

2. The guaranteed access rule: Every data value in a relational database should be
logically accessible by specifying a combination of table name and column name.

3. Systematic treatment of NULL values: DBMS support NULL values ,in case when user
leave the column in the table.

4. Active online catalog based on relational model: DBMS maintain system catalog.
System catalog is a collection of system table.

5. The comprehensive data sublanguage rule: System must support following


functions :

1. Data definition
2. View definition
3. Data manipulation operation
4. Security and integrity constraints
5. Transaction management operation

6. The view update rule: All views that are theoretically updated must be updated by the
system.

7. High level insert, update and delete: Means update at a time many rows values. Data
are treated as set ,which are easily delete, update and insert.
8. Physical data independence: Application programs must remain unimpaired when any
changes are made in storage representation or across methods.

9. Logical data independence: Changes should not affect the user's ability to work with
the data.

10. Integrity independence: Integrity constraints must be storable in the system catalog.

11. Distribution independence: Database must allow manipulation of distributed data


located on different computer system.

12. Nonsubversion rule: This rule state that different language bypass the integrity rule
and constraints.

MS SQL Server

Fully Web Enabled

You can use HTTP to send queries to the server. It provides various feature and facility to
accesses data on web.

Highly Scalable and Reliable

SQL sever use scale up and scale out feature to fulfill requirement . In Scale up SQl server
use 32 bit Processors and 64GB of RAM to increase the load. In scale out SQL distribute
database and data load across the server. When suddenly system crash ,RDBMS recover
data quickly with minimum loss. This feature called reliability.

Client Server Architecture (Two Tier Architecture)

Data Sharing,

Reduce Duplication and maintenance


SQL

Language to access data object from the SQL server


Stands for Structured Query Language
SQL addresses data in sets of rows and column rather than addressing individual
component or a single data
SQL support automatic navigation to target the data means user find data without
knowing how to get this data and how to store the data
Using this user never waste the time on representation of data, user only
concentrate on logic

Data types

Dtatype Range Used to store


-2^31 (-2,147,483,648) to 2^31 -
int Integer data (whole numbers)
1 (2,147,483,647)
-2^15 (-32,768) to 2^15 - 1
smallint Integer data
(32,767)
tinyint 0 to 255 Integer data
-2^63 (-
9,223,372,036,854,775,808) to
bigint Integer data
2^63-1
(9,223,372,036,854,775,807)
float -1.79E + 308 to 1.79E + 308 Floating precision data
-2^63 (-
922,337,203,685,477.5808) to
money Monetary data
2^63 - 1
(+922,337,203,685,477.5807)
smallmoney -214,748.3648 to +214,748.3647 Monetary data
January 1, 1753, to December 31,
datatime Date and time data
9999
smalldatatime January 1, 1900, to June 6, 2079 Date and time data
n characters, where n can be 1 to
char(n) Fixed length character data
8000
n characters, where n can be 1 to
varchar(n) Variable length character data
8000
Maximum length of 2^31 - 1
text Character string
(2,147,483,647) characters
Maximum length of 2^30 - 1
ntext Variable length Unicode data
(1,073,741,823) characters
bit 1 or 0 value Integer data with 0 or 1
Maximum length of 2^31 - 1 Variable length binary data to
image
(2,147,483,647) bytes store images
real -3.40E + 38 to -1.18E - 38 Floating precision number
binary Maximum length of 8,000 bytes Fixed length binary data
varbinary Maximum length of 8,000 bytes Variable length binary data
Maximum length of 4,000
nchar Fixed length Unicode data
characters
Maximum length of 4,000
nvarchar Variable length Unicode data
characters
Contain rows of different
datatypes except text, ntext,
sql_varient Maximum storage size of8016 bytes
image, timestamp and
sql_variant
unique number in a database
that get updated every time a
timestamp Maximum storage size of 8 bytes
row that contains it is inserted or
updated

Start with SQL Server

1. DDL (Data Definition Language)


2. DML (Data manipulation language)
3. DCL and TCL
4. Displaying Rows Using Logical & List Operators
5. Displaying Rows Using Comparison & Range Operators
6. Displaying Rows Using String Operator
7. IS NULL and IS NOT NULL keywords & ORDER BY Clause
8. Limits the rows by using
9. TOP keyword & DISTINCT keyword
10. Using Aggregate Functions
11. Using GROUP BY Clause
12. Using COMPUTE BY Clause
13. Using String Functions
14. DATE Functions
15. Mathematical Functions
16. Some System Functions
17. Joins
18. Inner Join
19. Outer Join
20. Cross Join
21. Equi Join
22. Natural Join
23. Self Join
24. Sub queries with EXITS Clause
25. Queries with modified Comparison Operators
26. Extracting Data Into Another Table
27. Using UNION Operator
28. How to create a Data Base in SQL server
29. .mdf, .ndf and .ldf extension files
30. Viewing, Renaming and Deleting a Database
31. Data Integrity
32. Creating Constraints
33. PRIMARY KEY Constraint
34. The UNIQUE Constraint
35. The FOREIGN KEY Constraint
36. The CHECK Constraint
37. The DEFAULT Constraint
38. INDEXES
39. CLUSTERED Index
40. NONCLUSTERED Index
41. How to Create an Index
42. Programming in SQL Server
43. The IF...ELSE Statement and BEGIN...END Statement
44. The CASE statement and WHILE statement
45. Stored Procedures
46. How To Create Stored Procedure

DDL (Data Definition Language)

Data Definition Language (DDL) statements are used to define the database structure or
schema. DDL statements are used to build and modify the structure of your tables and
other objects in the database. When you execute a DDL statement, it takes effect
immediately.

1. CREATE: To create objects in the database

CREATE TABLE <table_name> ( <attribute_name 1> <data_type 1>,


...
<attribute_name n> <data_type n>);

2. ALTER: Alters the structure of the database

ALTER TABLE <table_name>


ADD CONSTRAINT <constraint_name> PRIMARY KEY (<attribute_list>);

The foreign key constraint is a bit more complicated, since we have to specify both the
Foreign Key attributes in this (child) table, and the Primary Key attributes that they link to
in the parent table.
ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name> FOREIGN KEY (<attribute_list>)
REFERENCES <parent_table_name> (<attribute_list>);

3. DROP: Delete objects from the database

DROP TABLE <table_name>;

ALTER TABLE <table_name>


DROP CONSTRAINT <constraint name>;

4. TRUNCATE: Remove all records from a table, including all spaces allocated for the
records are removed

5. COMMENT: Comments added to the data dictionary.

6. RENAME: Rename an object of the Database.

DML (Data manipulation language)

.DML statements are used to work with the data in tables. SELECT, INSERT, UPDATE,
DELETE statements are consider as a DML statement.

1. SELECT: SQL server provide the SELECT statement to retrieve data from database. The
keywords SELECT, FROM and WHERE makeup the basic SELECT statement . SELECT
statement promote the server to querying single table or multiple tables in Database and
prepare a result and return to the client application.

Selecting Columns

The column name from a table specified in the SELECT statement separated by a comma (,)
and there is no need to insert a comma after the last column name.

SELECT column_name 1,column_name 2....column_name n


FROM table_name

The above query retrieve the column data which you pass in the query from table which
you pass after From keyword.

Selecting All Columns

The SELECT statement used with an asterisk (*) symbol to display all column of the table

SELECT *
FROM table_name

2. INSERT: The insert statement is used to add new rows to a table. There will need a
separate INSERT statement for every row. The statement of Insert will be:
INSERT INTO table_name
VALUES (value 1, ... value n);

The number of attributes and the data type of each attribute


Character type values are always enclosed in single quotes
Number values are never in quotes
Date values are often in the format 'yyyy-mm-dd' (for example, '2010-12-24')

3. UPDATE: The update statement is used to change values that are already in a table.

UPDATE table_name
SET attribute_name 1 = value 1, attribute_name 2 = value 2....attribute_name n = value n
WHERE condition;

If the WHERE clause is omitted, then the specified attribute is set to the same value
in every row of the table
Set multiple attribute values at the same time with a comma-delimited list of
attribute_name=value pair

4. DELETE: The delete statement does just that, for rows in a table.

DELETE FROM table_name


WHERE condition;

If the WHERE clause is omitted, then every row of the table is deleted

5. CALL: Call a PL/SQL

6. EXPLAIN PLAN: Explain access path to data

7. LOCK TABLE: Control concurrency

DCL (Data Control Language)

DCL stands for Data Control Language


Used to create roles
Used to create permissions

1. GRANT: Gives user to access database means user privilege to database.

2. REVOKE: Withdraw access privileges given with the GRANT command

TCL (Transactional Control Language)

TCL is stands for Transactional Control Language


It is used to manage different transactions occurring within a database

1. COMMIT: This Statement used to save work done by the user.


2. SAVEPOINT: Identify the point which you can later roll back in a transaction.

3. ROLLBACK: Restore database to original.

4. SET TRANSACTION: Change transaction options like isolation level and what rollback
segment to use

Using Logical Operator

Multiple search condition done by using logical operator. They are:

1. OR: Any of the specified search condition is true.

SELECT column_list
FROM table_name
WHERE condition_expression OR condition_expression

Return all rows specific to the conditions, even if any one of the condition is true.

2. AND: When all specified search conditions are true.

SELECT column_list
FROM table_name
WHERE condition_expression AND condition_expression

Return all rows specific to the conditions, when both conditions are true.

3. NOT: Neutralizes the expression that follow it.

SELECT column_list
FROM table_name
WHERE condition_expression {OR/AND} NOT condition_expression

Return all rows specific to the conditions, except the rows that match the condition specified
after the NOT operatoor.

Using List Operator

SQl provides IN and NOT IN operators. IN operator that allowed the selection of values that
match any one of the values in a list. NOT IN operator restrict the selection of values that
match any one of the values in a list.

SELECT column_list
FROM table_name
WHERE condition list_operator('value_list')

list_operator is any valid list operator.

value_list is the list of values to be included or excluded in the condition


For Example:

SELECT *
FROM publishers
WHERE state IN ('MA','DC')

SELECT *
FROM publishers
WHERE state NOT IN ('MA','DC')

Using Comparison Operators

Comparison operator allow row retrieval from a table based on the condition specified in the
WHERE clause.

SELECT column_list
FROM table_name
WHERE expression1 comparison_operator expression2

Operator Description
= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<>,!= Not equal to
!> Not greater than
!< Not less than
() Controls precedence

For Example:

SELECT pub_id
FROM publishers
WHERE city='Boston'

Using Range Operators

The range operator is used to retrieve data between range . The range operator are:

1. BETWEEN: Specified an inclusive range to search.

SELECT column_list
FROM table_name
WHERE expression1 BETWEEN expression1 AND expression1

For Example: Below query return the attribute list value between 2000 and 5000
SELECT *
FROM titles
WHERE advance BETWEEN 2000 AND 5000

2. NOT BETWEEN: This key word used to exclude the rows from the specified range in the
result set.

SELECT column_list
FROM table_name
WHERE expression1 NOT BETWEEN expression1 AND expression1

For Example: Below query return the attribute list value which not between 2000 and 5000

SELECT *
FROM titles
WHERE advance NOT BETWEEN 2000 AND 5000

Using String Operator

String operator provide a LIKE keyword to search for a string with wild card mechanism.

Wildcard Description
% Represents any string of Zero or more character

_ Represent the single character

Represent any single character within the specified


[]
range

Represent any single character not within the


[^]
specified range

For Example:

SELECT *
FROM titles
WHERE type LIKE 'bus%'

Return all attribute from the titles table in which the type starts with 'bus'

SELECT *
FROM titles
WHERE type LIKE 'bu_'

Return all attribute from the titles table in which the type of book is the three character long
and starts with 'bu'. Increase the '_' keyword increase the number of characters.
SELECT *
FROM titles
WHERE type LIKE 'b[us]%'

Return all attribute from the titles table in which the type of book is starts with 'b' and
contain u and s on the second position followed by any number of character.

SELECT *
FROM titles
WHERE type LIKE 'b[^s]%'

Return all attribute from the titles table in which the type of book is starts with 'b' and does
not contain s on the second position followed by any number of character.

Some Examples

Expression Returns
LIKE '%ty%' All names that have the letters 'ty' in them

LIKE '_ty' All three letter names ending with 'ty'

LIKE '[AD]%' All name that begin with "A" or "K"

Using IS NULL & IS NOT NULL

In SQL server, NULL is a unknown value means the data is not available. The NULL can be
retrieve from the table using IS NULL keyword in the WHERE clause.

Note: NO two NULL values are equal. You can not compare one NULL value to other.

SELECT column_list
FROM table_name
WHERE column_name unknown_value_operator

Where unknown_value_operator is either the keyword IS NULL or IS NOT NULL.

Example:

SELECT *
FROM publishers
WHERE state IS NULL

Returns the all attributes of publisher table where state attribute contain NULL

SELECT *
FROM publishers
WHERE state IS NOT NULL

Returns the all attributes of publisher table where state attribute does not contain NULL
Using ORDER BY Clause

It retrieve and display the data in specific order. ASC is the default sort order.

SELECT column_list
FROM table_name
ORDER BY column_name ASC/DESC

For Example:

SELECT *
FROM publishers
ORDER BY pub_name DESC

Return all attributes of publishers able in order to descending alphabetically order with
respect to pub_name attribute

Using TOP keyword

The TOP clause used with the SELECT statement. It is used to limits the number of rows
returned in the result set

SELECT [TOP n] column_mame


FROM table_name
WHERE search_conditions

'n'=number of rows that you want to retrieve.

For Example:

SELECT TOP 5 pub_id,pub_name,country


FROM publishers
WHERE country LIKE 'U%'
ORDER BY pub_id DESC

Returns all top 5 rows ,pub_id, pub_name and country, from the publishers table in
descending order with respect to pub_id.

Using DISTINCT keyword

It also used to limit the result set. The DISTINCT keyword remove the duplicate row from
the returned result set. It used with the SELECT statement.

SELECT DISTINCT column_mame


FROM table_name
WHERE search_conditions

For Example:
SELECT DISTINCT country
FROM publishers
WHERE city LIKE 'B%'

Return country name which started with a 'B' alphabet but no repetition, means no
duplicate value of country.

Using Aggregate Functions

These function are specially executed for the mathematical expression.

Function
Parameters Description
Name
(ALL, DISTINCT Return the average of value in a numeric
AVG
Expression) expression
(ALL, DISTINCT Return the number of values in an
COUNT
Expression) expression
Returns the no. of rows returned by the
COUNT (*)
query
Return the highest value in the
MAX (expression)
expression
MIN (expression) Return the lowest value in the expression
(ALL, DISTINCT Return the total of value in a numeric
SUM
Expression) expression

The AVG, COUNT, MAX, MIN and SUM function ignore NULL values, whereas the COUNT (*)
function counts the NULL values.

Examples Description
SELECT 'avg'=AVG (discount)
Returns the average value of the discount
FROM discounts
SELECT 'sum'=SUM (discount)
Returns the sum value of the discount
FROM discounts
SELECT 'min'=MIN (discount) Returns the minimum value of the discount in
FROM discounts discounts table
SELECT 'max'=MAX (discount) Returns the maximum value of the discount in
FROM discounts discounts table
SELECT 'count'=COUNT
Return the number of discount value in discounts
(discount)
table
FROM discounts

Using GROUP BY Clause

Group clause summarize the result set in to a groups defined in the query using aggregate
function.

SELECT column1, column2, ... column_n, aggregate_function (expression)


FROM table_name
WHERE conditions
GROUP BY ALL column1, column2, ... column_n

expressions describe the column name (s) or expressions on which the result set of the
SELECT statement is to be grouped.

ALL is a keyword used to include those groups that do not meet the search condition.

For Example:

SELECT type, 'avg'=AVG(advance)


FROM titles
WHERE type LIKE 'b%'
GROUP BY ALL type

Out Put

type avg
-----------------------------------------------
business 5000.0000
mod_cook NULL
popular_comp NULL
psychology NULL
trad_cook NULL
UNDECIDED NULL

Return all type from table but the 'avg' display only those type which started with ' b'.
Means this keyword used to display all groups, including those exclude from WHERE clause.
The ALL keyword is meaningful for those query that contain WHERE clause.

For Example:

SELECT type,'pub Id'=pub_id, 'avg'=AVG (price)


FROM titles
GROUP BY type,pub_id

Return the 'type' and 'pub Id' and 'avg' , which calculated from titles table.

For Example:

SELECT type, 'avg'=AVG(advance)


FROM titles
WHERE title_id IN ('BU1032','PC1035')
GROUP BY ALL type

Out Put

type avg
-----------------------------------------------
business 5000.0000
mod_cook NULL
popular_comp 7000.0000
psychology NULL
trad_cook NULL
UNDECIDED NULL

Using COMPUTE Clause

Used to generate summary rows using aggregate function in the query results.
COMPUTE BY clause can be used to calculate summary values of the result set on a
group of data.
The main difference between GROUP BY and COMPUTE BY Clause is, GROUP BY
Clause is used to generate a group summary report and does not produce individual
table rows in the result set whereas COMPUTE BY Clause generate the summary
report with individual data rows from the table.

SELECT column_name
FROM table_name
ORDER BY column_name
COMPUTE aggregate_function (column_name) BY column_name 1...column_name n

For Example:

SELECT type, advance


FROM titles
ORDER BY type
COMPUTE AVG (advance) BY type

Out Put
Some points regarding the use of the COMPUTE and COMPUTE BY

The DISTINCT keyword cannot be used with the aggregate function


All columns referred to in the COMPUTE clause must appear in the select column list
The ORDER BY Clause must be used whenever the COMPUTE BY Clause is used
The ORDER BY Clause can be eliminate only when the COMPUTE BY Clause is used
The column listed in the COMPUTE BY Clause must match the columns used in the
ORDER BY Clause
More than one COMPUTE clause can be used in the SELECT statement to produce a
result with subtotals and grand total
The different aggregate function can be used on more than one column with the
COMPUTE BY Clause
More than one column or expression can be specified after the COMPUTE BY clause.
The order of columns or expression used in the COMPUTE BY clause must match the
order of columns or expression specified in the ORDER BY Clause.

Using String Functions

This function use to format data that will meet specific requirements. Mostly they are used
with the char and varchar data types. It used for implicit convert data to char to varchar.

SELECT function_name (parameter)

function_name is the name of the string function. parameter are required parameters for
the string function.

Function
Parameters Example Description
name
Return 65 the ASCII
ASCII (character_expression) SELECT ASCII ('ADI') code of the leftmost
character 'A'
Return A the character
CHAR (integer_expression) SELECT CHAR (65) equivalent of the ASCII
code value
Returns 5, the standing
SELECT position of the specified
CHARINDEX ('pattern', expression)
CHARINDEX ('O','HELLO') pattern in the
expression
Return the four
SELECT
SOUNDEX (character_expression) character code to
SOUNDEX ('ADITYA')
compare the string
Difference function
compare the SOUNDEX
(character_expression1
SELECT value of two string and
DIFFERENCE ,
DIFFERENCE ('ADITYA','ADI') return a value from 0
character_expression2)
to 4. The value 4 is
best match.
LEFT (character_expression, SELECT Return 'ADIT', which is
integer_expression) LEFT ('ADITYA','4') the part of character
string equal in size to
the integer_expression
character from the left
Return 6, the no of
LEN (character_expression) SELECT LEN ('ADITYA') character in the
(character_expression)
Return 'aditya', after
the converting
LOWER (character_expression) SELECT LOWER ('ADITYA')
(character_expression)
to the lower case
Return 'ADITYA'
without leading spaces.
LTRIM (character_expression) SELECT LTRIM (' ADITYA') It removes leading
blanks from the
character expression
Return 4, the standing
position of the first
("%pattern%, SELECT occurrence of the
PATINDEX
expression") PATINDEX ('%TY%','ADITYA') pattern in the specified
expression, or zero if
pattern is not found
Return 'AYTIDA' , the
SELECT
REVERSE (character_expression) reverse of the
REVERSE ('ADITYA')
(character_expression)
(character_expression, SELECT Return 'ITYA' , the part
RIGHT
integer_expression) RIGHT ('ADITYA',4) of the character string.
Return 'ADITYA'
without leading spaces.
RTRIM (character_expression) SELECT LTRIM ('ADITYA ') It removes leading
blanks from the
character expression
Returns 'ADITYA
TIWARI'. Two space
SELECT
SPACE (integer_expression) are inserted between
'ADITYA'+SPACE(2)+'TIWARI'
the first and second
word
Return '123.45'. It
converts numeric data
to character data
where the length is the
total length ,including
(float_expression,
STR SELECT STR (123.45,6,2) the decimal point, the
[length,[decimal]])
sign, the digits, the
spaces and the decimal
is the number of places
to the right of the
decimal point
STUFF (character_expression1 SELECT STUFF Return 'Asya'. It delete
, ('Aditya',2,3,'s') length characters from
start, length, character_expression1
character_expression2) from the start and then
inserts
character_expression2
into
character_expression1
at the start position
Returns 'dit', which is
part of a character
(expression, start, SELECT SUBSTRING string. It returns length
SUBSTRING
length) ('Aditya',2,3) character from the
start position of the
expression
Return 'ADITYA', after
the converting
UPPER (character_expression) SELECT UPPER ('aditya')
(character_expression)
to the upper case

Using DATE Functions

Date function of SQL is:

Used to manipulate date time values


Perform arithmetic operations
Perform date parsing
Add two date or subtract one date from another

SELECT date_function (parameters)

date_function is the name of date function

parameters are the required parameters of the date function

Function
Parameter Description
Name
(datepart,number,date
DATEADD Adds the number of dateparts to the date
)
Calculates the number of dateparts
DATEDIFF (datepart,date1,date2)
between two dates
Return datepart from the listed date, as
DATENAME (datepart,date)
character value (for example: March)
Returns datepart from the listed date as
DATEPART (datepart,date)
an integer
GETDATE () Returns current date and time

For Example:

SELECT getdate()

The above statement display the current system date by using getdate() function.
SELECT 'getdate'= DATEADD(yy,2,pubdate)
FROM titles

Return the all pubdate from titles table with increment of 2 in each year of the table.

SELECT datepart (yy,pubdate)


FROM titles

Return all Date from pubdate of titles table.

Using Mathematical Functions

Mathematical function perform numerical operation on mathematical data. The various


mathematical functions are:

Function Name Parameter Description


(numeric_expression
ABS Return an absolute value
)
Returns the angle in radians whose
ACOS,ASIN, ATN (float_expression) cosin,sin and tangent is a floating
point value
Returns the angle in radians whose
COS,SIN,COT,TAN (float_expression)
cosin, sin, tangent and cot of the angle
(numeric_expression Returns the smallest integer greater
DEGREES
) than or equal to the specified value
Return the exponential value of the
EXP (float_expression)
specified value
(numeric_expression Return the largest integer less than or
FLOOR
) equal to the specified value.
LOG (float_expression) Return the natural logarithm of the
specified value
Return the base-10 logarithm of the
LOG10 (float_expression)
specified value
Returns the constant value of
PI ()
3.141592653589793
(numeric_expression, Return the value of
POWER
y) numeric_expression to the value of y
(numeric_expression
RADIANS Convert from degrees to radians
)
Return a random float number
RAND ([seed])
between 0 and 1
returns a numeric expression rounded
(numeric_expression,
ROUND off to the length specified as an
length)
integer expression
(numeric_expression
SIGN Returns positive, negative or zero
)
Return the square root of the specified
SQRT (float_expression)
value

ROUND (numeric_expression,length)

numeric_expression is the numeric expression to be round off

SELECT 'value'= ROUND (123.452352,3)

Out Put:

Using System Functions

System function provide a method of querying the system tables of SQL server.

Function Definition
Returns the current host process ID number of a client
HOST_ID()
process
Return the current host computer name of a client
HOST_NAME()
process
Return the user's login name corresponding to the
SUSER_SID(['login_name'])
user's security identification number
Return the database identification number
USER_ID(['name_in_db'])
corresponding to the username
Return the user name corresponding to the database
USER_NAME(['user_id'])
identification number
DB_ID (['db_name']) Return the database ID number of the database
DB_NAME(['db_id']) Returns the database name
OBJECT_ID ('objname') Returns the database object ID number
OBJECT_NAME('object_id') Returns the database object name

JOINS

SQL server provide:

A method to retrieving a data from more than one table using join at a time
Implemented using SELECT statement, in which the SELECT statement contain the
name of columns to be retrieve from the tables
The FROM clause contains the name of the tables from which combined data is to be
retrieved
The WHERE specifies the rows to be included in the result set with the help of the
join operator

Syntax:

SELECT column name 1, column name 2....column_name n


FROM table name [CROSS, INNER, OUTER] JOIN table_name
ON [table_name.ref_column_name] join_operator [table_name.ref_column_name]
WHERE search_condition

column_name specifies the name of the columns from one or more than one table that has
to be displayed.

table_name specifies the name of the tables from which data to be retrieve.

ref_column_name specifies the name of the columns that are used to combined the two
tables using the common keys from the respective tables.

join_operator specifies the operator used to join the tables

When two tables are joined, they must share a common key that defines how the rows in
the tables correspond to each other. A primary key is validated against the foreign key
when a joined is used.

Whenever a column is referred to in a join condition, it should be referred to either by


prefixing it with the table name to which it belongs or by a table alias.

Table Alias: A table alias is required whenever an ambiguity is possible due to duplicate
column names in a multiple tables A tables alias is a keyword defined in the FROM clause of
the SELECT statement to uniquely identify the table.

Syntax:

FROM table_name table_alias

Where,
table_name specifies the name of the tables that have to be combined in the query

table_alias is the keyword used to refer to a table. It must follow the rules of identifiers

Types of JOIN

Inner Join
Outer Join
Cross Join
Equi Join
Natural Join
Self Join

Inner Join

In inner joining, data from multiple tables is displayed after comparing values present in a
common column. Only rows with values satisfying the join condition column are displayed.
Rows in both tables that do not satisfy the join condition are not displayed.

SELECT columnm_name
FROM table_name JOIN table_name
ON [table_name.ref_column_name] join_operator [table_name.ref_column_name]

For Example:

SELECT title, royaltyper, royalty


FROM titleauthor JOIN titles
ON titleauthor.title_id=titles.title_id

Return all title, royaltyper, royalty from table in which these attributes are present
Outer Join

An outer join displays NULL for the columns of the related table where it does not find
matching records

When the result set contains all rows from one table
The matching rows from other

SELECT columnm_name 1, columnm_name 2....columnm_name n


FROM table_name [LEFT,RIGHT] OUTER JOIN table_name
ON [table_name.ref_column_name] join_operator [table_name.ref_column_name]

Left Outer Join: Left outer join ensure the inclusion of rows the first table and the
matching rows from the second table.

SELECT logo,price,notes
FROM pub_info p LEFT OUTER JOIN titles t
ON p.pub_id=t.pub_id
Right Outer Join: Right outer join ensure the inclusion of rows the second table and the
matching rows from the first table.

SELECT logo,price,notes
FROM pub_info p RIGHT OUTER JOIN titles t
ON p.pub_id=t.pub_id
Cross Join

A join that included more than one table using keyword CROSS is called cross join
The output of a such type of join is called Cartesian product
In cross join each row of first table is joined to with the each row of second table
The number of rows in the result set is the multiple of the first table rows and second
table rows

SELECT column_name 1, column_name 2....column_name n


FROM table_name CROSS JOIN table_name

For example:

SELECT *
FROM sales CROSS JOIN publishers
returns 168 rows, after cross join 21 rows of sales table and 8 rows of publishers tables

Equi Join

A equi join display redundant column of data in the result set, where two or more tables are
compared for equality.

For Example:

SELECT *
FROM sales s JOIN titles t
ON s.title_id=t.title_id
JOIN publishers p
ON t.pub_id=p.pub_id

Returns the above columns in the result set.

Natural Join

A join that restrict the redundant column from the result set is known as natural join

SELECT t.title, p.pub_name


FROM titles t JOIN publishers p
ON t.pub_id=p.pub_id

Returns the all title and pub_name from respective tables.

Self Join

A join is said to self join when one row in a table correlates with the other rows in the same
table. An alias name can differentiate the two copy of the table. All join operators except the
outer join operators can be used in a self join.
For Example:

SELECT t1.title, t2.title, t1.price


FROM titles t1 JOIN titles t2 ON t1.price=t2.price
WHERE t1.price=2.99

Using EXITS Clause

A sub query used with the EXISTS clause, always returns data in terms of a TRUE or FALSE
value. It checks for the existence of a data rows according to the condition specified in the
inner query and passes the existence status to the outer query to produce the result set.

For Example:

SELECT pub_name
FROM publishers
WHERE EXISTS (SELECT * FROM titles WHERE type='business')

Out Put

Display the name of publishers who publish business related books.

SELECT title
FROM titles
WHERE advance > (SELECT avg(advance) FROM titles WHERE type='business')

Out Put
Display the titles of all those books for which the advance amount is greater than the
average advance for bussiness related books.

Queries with modified Comparison Operators

SQL server provides the ALL and ANY keywords that can be used to modify the existing
comparison operator. The sub query introduced with a modified comparison operator
returns zero or more values and can be implemented using the GROUP BY or HAVING
clause.

Operator Description
Means greater than the maximum value in the list.
>ALL
column_name>ALL (10,20,30) means 'greater than
30'
Means greater than the minimum value in the list.
>ANY
column_name>ANY (10,20,30) means 'greater than
10'
Means any of the values in the list. It acts in the same
way as the IN clause
=ANY
column_name=ANY (10,20,30) means 'equal to either
10 or 20 or 30'
Means not equal to any in the list.
<>ANY
column_name<>ANY (10,20,30) means 'not equal to
either 10 or 20 or 30'
Means not equal to all the values in the list. It acts in
the same way as the NOT IN clause.
<>ALL
column_name<>ALL (10,20,30) means 'not equal to
either 10 and 20 and 30'

For Example:
SELECT title_id ,title
FROM titles
WHERE price> ALL (SELECT price FROM titles WHERE pub_id='0736')

Out Put:

Display the title_id and title where price is greater than the maximum price of books
published by the publisher with the publisher ID 0736

SELECT title_id ,title


FROM titles
WHERE price>ANY(SELECT price FROM titles WHERE pub_id='0736')

Display the title_id and title where price is greater than the minimum price of books
published by the publisher with the publisher ID 0736

Extracting Data Into Another Table

A SELECT statement with the INTO clause is used to store the result set in a new table
without a data definition process. The SELECT INTO statement creates a new table.

If the table is already exists, then the operation fails.

The command syntax is the,


SELECT columns_list
INTO new_table_name
FROM table_name 1, table_name 2.. table_name n
WHERE condition 1, condition 2..condition n

Where coloumn_list is the list of columns to be included in the new table.

new_table_name is the name of the new table where data is to be stored.

condition is the conditions on which rows are to be included in the new table.

For Example:

Create a new table from the title table.

SELECT title_id ,title


INTO aditya
FROM titles
WHERE price>15

(8 row(s) affected)

SELECT *
FROM aditya

A new table created named aditya

Using UNION Operator

SQL server provide a unique operator known as the UNION operator that is used to combine
the result set of two or more queries.

SELECT column_list [ INTO new_table_name]


[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]..]
UNION [ALL]
SELECT column_list
[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]..]
[ORDER BY clause]
[COMPUTE BY clause]

UNION ALL is the operator used to combine two or more queries with duplicate rows from
different queries.

For Example:

SELECT au_fname,city,state
FROM authors
WHERE state='UT'
UNION
SELECT pub_name,city,state
FROM publishers

Out Put:

How to create a Data Base in SQL server

The creation of a database involves the database and determining the size of the database
and the files used to store data in the database.

CREATE DATABASE database_name


ON
[<filespace>...n]
[<filegroup>...n]
LOG ON
(NAME=logical_file_name,
FILENAME='os_file_name',
SIZE=size,
MAXSIZE=max_size,
FILEGROWTH=growth_increment)
where, data_base name is the name of new database.

ON specifies the disk files used to store the data portion of the database.

NAME=logical_file_name specifies the logical name for the file.

FILENAME=os_file_name specifies the operating system file name.

SIZE=size specifies the initial size f the file defined in the (<filespace>) list.

MAXSIZE=max_size specifies the maximum size to which the file defined in the <filespace>
list can grow.

FILEGROWTH=growth_incremet specifies the growth increament of the file defined in the


<filespace> list.

FILEGROUP filegroup_name name specifies the name of the filegroup.

LOG ON specifies the disk files used to store the log files.

For Example:

CREATE DATABASE aditya


ON
(NAME=aditya_dat,
FILENAME='C:\Program Files\Microsoft SQL Server\MSSQL\DATA\aditya.mdf',
SIZE=12,
MAXSIZE=100,
FILEGROWTH=2)
LOG ON
(NAME='aditya_log',
FILENAME='C:\Program Files\Microsoft SQL Server\MSSQL\DATA\aditya.ldf',
SIZE=4 MB,
MAXSIZE=50 MB,
FILEGROWTH=2 MB)

Out Put:

The CREATE DATABASE process is allocating 12.00 MB on disk 'aditya_dat'.


The CREATE DATABASE process is allocating 4.00 MB on disk 'aditya_log'.
Aditya named database created

mdf, .ndf and .ldf EXTENSIONS FILES

.mdf Extension

When we create a database, the CREATE command create a data file with extension
.mdf is a primary file.
It is a SQL Data files where all the data in the database objects are stored in
Like tables, stored procedures, views, triggers etc. All are stored in the .mdf file of
sql server
This is the reason whey we use .MDF file to attach the database. Once we attach
the .mdf we were able to see all the data exist in that respective database.

..ldf Extension

.ldf is the log file in the SQL server to see the data
Transaction log file with extension .ldf
The size of the log file (ldf) is determined my the logging level you have set up on
the database
Simple, full, and build logged are the options
Simple being the least, and full being the most, the logged (if in full) will allow you to
re-apply transactions to the database incase of a failure
If your looking for some performance improvement, there are a lot of things that can
be done

.ndf Extension

.ndf are secondary databse files


Same as mdf, but you can only have 1 Main database file
This file also could be stored on a separate physical drive
Advantage is that, tables that are relatively static are in another file
Tables that are written frequently are stored in one file
Having to smaller file to write to for transactions will help with throughput.
Viewing, Renaming and Deleting a Database

Viewing a Database

The information regarding database such as owner, size, date of creation, and status can be
viewed using the following:

sp_helpdb database_name

For Example:

sp_helpdb aditya

Renaming Database

The name of database can be changed. The database should not be in use when it is being
renamed, and it should be set to the single-user mode.

sp_rename 'old_name','new_name'

where, old_name is the original name of the database

new_name is the new name of datbase

Only system administrator can changed the name of a database.

Deleting a Database

A database is deleted when it is no longer required. Only the system administrator and
database owner have permission to delete a database.

DROP DATABASE database_name

where, database_name is the name of the database.

DATA INTEGRITY

There are three most important things when database is accessing:

Accurate
Consistent
Reliable , means its very tuff to maintain data integrity.
Data integrity ensures the consistency and correctness of data stored in a database. It is
broadly classified into the following four categories:

Entity Integrity

Entity integrity ensures that each row can be uniquely identified by an attribute called the
primary key. The primary key can not be NULL. For example: there might be two candidates
for interview with the same name 'alok'. they can be identified using the unique code
assigned to them.

Domain Integrity

Domain integrity ensures that only a valid range of values is allowed to be stored in a
column. It can be enforced by restricting the type of data, the range of values, and the
format of data.

For Example: Let assume that table BranchOffice, that contain various offices of a company
and this table has another column city that store the cities where branch offices are located.
Assume that offices are located in 'Delhi', 'Mumbai', 'Chanai'. By enforcing the integrity we
ensure that only valid values can be entered in the city column of the BranchOffice table.

Referential Integrity

Referential Integrity ensures that the values of the foreign key match with the value of the
corresponding primary key.

For Example: In a CollegeStudent table each student has there enrollment number in the
column, another table in university database is UniversityStudent which contain Enrollment
number that make ensure registration of each student.

User-defined Integrity

User-defined integrity refers to a set by a user, which do not belong to the entity, domain,
and referential integrity categories.

For Example: If you want a candidate who is less than 18 years to apply for a post.

CREATING CONSTRAINTS

Constraints can be be enforced at two levels.

Column level
Table level

A constraints can be defined on a column at the time of creating a table. It can be created
with the CREATE TABLE statement.

1. CREATE TABLE statement:


CREATE TABLE table_name
column_name CONSTRAINTS constraints_name constraints_type [, CONSTRAITS
constraints_name constraints_type]

where, column_name is the name of the column on which the constraints is to be defined.

constraints_name is the name of the constraints to be created and must follow the rules for
the identifier.

constraints_type is the type of constraints to be added.

2. ALTER TABLE statement:

ALTER TABLE table_name


[WITH CHECK or WITH NOCHECK]
ADD CONSTRAINTS constraints_name constraints_type

where, table_name is the name of the table that is to be altered for adding a constraints.

WITH CHECK and WITH NOCHECK specifies whether the existing data is to be checked or
not checked for a newly added constraints or a re-enabled constraints

constraints_name specifies the name of the constraints to be created and must follow the
rule for identifier.

constraints_type specifies the type of constraints.

DROPPING CONSTRAINTS

A constraints dropped using the ALTER TABLE statement in the Query Analyzer.

All constraints defined in the table are dropped automatically when the table is dropped.

ALTER TABLE table_name


DROP CONSTRAINTS constraints_name

where, table_name is the name of the table that constraints to be dropped.

constraints_name is the name of the constraints to be dropped.

TYPES OF CONSTRAINTS

[1] PRIMARY KEY constraints

[2] UNIQUE constraints

[3] FOREIGN KEY constraints

[4] CHECK constraints


[5] DEFAULT constraints

PRIMARY KEY constraints

A Primary Key constraints is defined on a column whose values uniquely identify rows in a
table. These columns are referred to as the primary key columns. A primary key column can
not contain NULL values since it is used to uniquely identify rows in a table. the primary key
ensure entity integrity.

You can define a PRIMARY KEY constraints at the time of a table creation, or you can add it
later by altering the table. While defining a PRIMARY KEY constraints, you need to specify a
name for the constraints. If a name is not specified, SQL server automatically assigns a
name to the constraints.

CREATE TABLE table_name


(column_name data_type CONSTRAINT constraints_name PRIMARY KEY),..

For Example:

CREATE TABLE employee


(emp_name char (4) CONSTRAINT pfemp_name PRIMARY KEY)

The above command creates a table employee with emp_name as the primary key. The
name of the constraints is pfemp_name.

Out Put

Primary key also created after creating a table by following command:

ALTER TABLE employee


ADD CONSTRAINT Pfemp_name PRIMARY KEY (emp_id)
For Example:

The UNIQUE Constraints

To enforce uniqueness on non-primary columns used the UNIQUE constraints. A primary key
constraints column automatically includes a restriction for uniqueness. The unique
constraint is similar to the primary key constraint except that it allows NULL values, but
there can be only one row in the table with a NULL value. Multiple Unique constraints can be
created on a table.

CREATE TABLE table_name


(coloumn_name data_type CONSTRAINT constraint_name UNIQUE)

For Example:

CREATE TABLE engineer


(eng_name char(4), eng_id char(4) CONSTRAINT uniEng_id UNIQUE)
The above command creates a UNIQUE constraint uniEng_id on the attribute eng_id in
the engineer table. The constraints would not allow the duplicate value to be inserted in the
uniEng_id attribute. However, there could be one row in the uniEng_id attribute that
contains NULL.

We create a UNIQUE constraints after the table has been created by altering the
table

ALTER TABLE engineer


ADD CONSTRAINT UNeng_SocialId UNIQUE (eng_SocialId)

The above command creates a UNIQUE constraint UNeng_SocialId on the attribute


eng_SocialId in the engineer table.

The Rules regarding to the UNIQUE constraints are:


It can be created at the column level as well as table level
It does not allow two rows to have the same non-null value in a table
Multiple UNIQUE constraints can be placed on a table

The FOREIGN KEY Constraint

FOREIGN KEY constraint to remove the inconsistency in two tables when data in one
table depends on data in another table.
A FOREIGN KEY constraint associates one or more columns of a table (the foreign
key) with an identical set of columns on which a PRIMARY KEY constraint has been
defined (a primary key column in another table).

CREATE TABLE table_name


(column_name data_type REFERENCES table_name (emp_id))

Syntax:

CONSTRAINT constraint_name FOREIGN KEY (column_name,..)


REFERENCE table_name (column_name,..)

For Example:

CREATE TABLE employee


(emp_name char(4), emp_id varchar (16) REFERENCES engineer (emp_id))

The above command creates a FOREIGN KEY on the attribute emp_id of the employee
table that reference the primary key emp_id of the engineer table. This will ensure that
the employeeID code that is inserted into the employee table is checked against the
engineer table for the validity.
If the employee table is exist and does not have foreign key defined, then table also
modified using ALTER TABLE command.

ALTER TABLE employee


ADD CONSTRAINT fkemp_id FOREIGN KEY (emp_id) REFERENCES engineer (emp_id)

The CHECK Constraint


A check constraint:

Enforces the domain integrity by restricting the values to be inserted in a column


Constraints are evaluated in the order in which they are defined
There is a possible to define multiple CHECK constraints on a single column
If check constraints defined at the table level it can be applied for the multiple
columns

Syntax:

[CONSTRAINT constraint_name ] CHECK (expression)

where, constraint_name specifies the name of the constraint to be created.

expression specifies the conditions that define the check to be made on the column. It can
be any expression arithmetic operation, relational operation or keywords :

1. The IN keyword.

2. The LIKE keyword.

3. The BETWEEN keyword.

The rules regarding the creation of the CHECK constraint are as follows:

It can be created at the column level


It can be contain user-specified search condition
It cannot contain sub queries
It does not check the existing data in the table if created with the WITH NOCHECK
option
It can reference other columns of the same table

The DEFAULT Constraint

A default constraint can be used to assign a constant value to a column, and the user need
not insert values for such a column . Only one DEFAULT constraint values can be created for
a column , but the column cannot be an IDENTITY column. The system-supplied values like
USER, CURRENT_USER, and user defined values can be assigned as defaults.

CREATE TABLE table_name


(column_name data_type DEFAULT [constant_expression])

where, constraint_name specifies the name of the constraint to be created.

constant_expression specifies an expression that contains only constant values and can
contain NULL.

For Example:
CREATE TABLE employee
(cCity char (14) DEFAULT 'New Delhi', emp_id varchar(15))

The above command use to create a DEFAULT constraint on the cCity attribute. If a city is
not specified, then the cCity attribute would contain 'New Delhi' by default.

If table already created then using ALTER command we specified the DEFAULT
constraint

ALTER TABLE employee


ADD CONSTRAINT defcCity DEFAULT 'New Delhi' FOR cCity

INDEXES
An Indexes is:

SQL server used an internal table structure that provide quick access to rows of a
table
It is totally based on the values of one or more columns
SQL Server indexes are like the indexes at the back of a book, which help in locating
content

Advantage Of Using Indexes

The primary purpose of an index is to provide faster access to data pages


When server searched anything, it searching the index at the place of searching the
whole page
Server scan the index and get the address of data storage location and directly
access the information
Indexes are also used as a mechanism of enforcing data uniqueness
An index speeds up the processing of queries that use joins or other clauses like
ORDER BY or GROUP BY, by allowing to faster access of data
Improve the speed of the execution of queries
Enforce uniqueness of data
Speed up joins between table

Disadvantage Of Using Indexes

Indexes does not indexing every column of the table


It takes time to create index
Each index create requires space to store data along with the original data source-
the table
An index gets updated each time the data is modified

Types Of INDEXES

There are two types of indexes:

1. CLUSTERED Index

2. NONCLUSTERED Index

CLUSTERED INDEX

The data is physically stored


There is only one clustered index can be created per table
Clustered index must be build on attribute that have a high percentage of unique
values and they are not modified often
A clustered indexes should be created before a nonclustered index
A clustered index changes the order of the rows.

How Clustered Indexes Work


In clustered index data are stored at the leaf level of the B-tree. The data pages of a table
are like folders stored in an alphabetically order in the filling cabinet, and the rows of the
data are like the documents stored in folders.

SQL server performs the following steps when it uses a clustered index to search for a
value:

Step 1. First SQL sever find the root page from the sysindexes table

Step 2. The search value is compared with the key values on the root page

Step 3. The page with the highest key value less than or equal to the search value is found

Step 4. The page pointer is followed the next lower level in the index

Step 5. Step 3 and 4 repeated until the data page is reached

Step 6. The rows of the data are searched on the data page until the search value is found.
If the search value is not found on the data page, no rows are returned by the query

Example: Consider the following example in which the rows of the employee table are
sorted according to the Eid attribute and stored in the table.
If the row containing Eid E006 were to be searched using the clustered index displayed in
the figure, the following step will be followed.

SQL Server starts from page 603, the root page


It searches the highest key value on the page, which is less than or equal to the
search value. The result of this search is the page containing the pointer to Eid E005
The search continues from page 602
There, the Eid E005 is found and the search continues on page 203
Page 203 is searched to find the required row

NONCLUSTERED INDEX

The physical order of the rows is not the same as the index order
Nonclustered indexes are typically created on columns used in joins and WHERE
clauses, and whose values may be modified frequently
SQL server creates nonclustered indexes by default when the CREATE INDEX
command is given
There can be as many as 249 nonclustered indexes per table
Typically, nonclustered indexes are created on foreign keys
A nonclustered index would need to be rebuilt if it is built before a clustered index

How Nonclustered Indexes Work

Step 1. First SQL sever find the root page from the sysindexes table.

Step 2. The search value is compared with the key values on the root page.

Step 3. The page with the highest key value less than or equal to the search value is found.

Step 4. The page pointer is followed the next lower level in the index.

Step 5. Step 3 and 4 repeated until the data page is reached.

Step 6. The rows are searched on the leaf page for the specified value. if a matched is not
found, the table contains no matching rows.

Step 7. If a match is found, the pointer is followed to the data page and row-ID in the
table, and the requested row is retrieved.

Example: If the row containing Eid E006 were to be searched using the nonclustered index
displayed in the figure, the following steps would be followed:

SQL Server starts from page 603, the root page


It searches the highest key value on the page, the page with a key value less than or
equal to the search value, that is, to the page containing the pointer to Eid E005
The search continues from page 602
There, the Eid E005 is found and the search continues on page 203
Page 203 is searched to find a pointer to the actual row. Page 203 is the last, or the
leaf page of the index
The search then moves to page 302 of the table to find the actual row
How to Create an INDEX

1. Identify the tables on which the index will be created.

2. Identify the attribute on which the index will be created.

3. Identify the type of index will be created.

4. Identify the name of the index to be created. (Prefix an 'idx' to the name of the index to
help in locating/identifying the index.)

5. Create the index.

Syntax:

CREATE [UNIQUE] [CLUSTERED or UNCLUSTERED] INDEX index_name


ON table_name (column_name...)

where, UNIQUE creates an index in which each row should contain a different index value.

CLUSTERED specifies a clustered index in which data is sorted on the index attribute.

NONCLUSTERED specifies a nonclustered index that organizes data only logically. the data is
not sorted physically.

index_name specifies the name of the index.


The index name should be unique in the table, but it may not be unique within a database.

table_name specifies the name of table and column_name is the name of columns on which
the index would be created.

CREATE CLUSTERED INDEX ad_name


ON employee (emp_id)

How to Verify that Indexes has been created

Syntax:

sp_helpindex table_name

CREATE NONCLUSTERED INDEX INemp_name


ON employee (emp_name)

sp_helpindex employee

Out Put:

Programming in SQL Server

Batches
Variables
Printing Messages
Comments
Control-of-flow statements

Batches

Batches are groups of SQL statement submitted together to SQL Server for
execution
A batch is parsed
A batch is optimized
A batch is compiled
A batch is executed
SQL server compiled the statements of a batch into a single unit called an execution
plane
The statement in the execution plane are then executed one at a time
There is any error in a batch, no statement in the batch is executed

Restriction

You cannot bind rules and defaults to columns and use them in the same batch
You can not define and use the CHECK constraints in the same batch
You can not drop object and recreate them in the same batch
you cannot alter a table and reference the new column in the same batch

Variables

Variable used to store a temporary value. We can declare and assign a value to a variable,
declared a variable by using DECLARE statement.

Syntax: DECLARE @variable_name data_type

The @ symbol before the variable name. This symbol is required and is used by the query
processor to identify variable.

For Exaple:

DECLARE @empID int


SELECT @empID=max(emp_id)
FROM employee
SELECT new_empID=@empID

In the first line DECLARE keyword declare a variable empID of int type, and in second line
the maximum value of emp_id attributes from employee table stored in the empID variable

Out Put: The output will be

Global Variables: Global variable are system-supplied and predefined. These variables are
distinguished from local variables by having two @ signs preceding their names
Variable name Returns
@@ version Date, version and other information on the current version
@@ servername Name of SQL server
@@ spid Server process id number of the current process
@@ procid Stored process ID of the current-executing procedure
0 if the last transaction succeeded, otherwise the last error
@@ error
number
Number of rows affected by the last query, 0 if no rows are
@@ rowcount
affected
Sum of the number of connections and the attempted
@@ connection
connections since Microsoft server was started
@@ trancount Number of currently-active transactions for a user
@@
Maximum number of simultaneous connections
max_connections
Total number of errors that have occurred during the current SQL
@@ total_errors
server session

SELECT servername='Name=' + @@servername

Printing Messages

PRINT statement display the user defined message or the content of a variable on the
screen

For Example:

DECLARE @Name char(15)


SELECT @Name='Anil Yadav'
PRINT @Name

Out Put:

Anil Yadav

For Example:

DECLARE @empID int


SELECT @empID=max(emp_id)
FROM employee
PRINT @empID

Out Put:

12348
Comment Entry

Comment entries are used to write the description of code in batches


This will help to read the description of code
Multiple line comment entries enclosed within /* and */
Single line comment entry starting with --(double hyphens)

Control-of-Flow Language

The control -of -flow language controls the flow of execution of SQL statement in batches,
stored procedures, triggers, and transactions. It is typically used when statements have to
be conditionally or repeatedly executed. The control -of -flow language transforms standard
SQL into a programming language.

The control -of -flow statements provided by SQL server :

1. The IF...ELSE statement

2. The CASE statement

3. The WHILE statement

The IF...ELSE Statement and BEGIN...END Statement

IF...ELSE Statement

Syntax:

IF boolean_expression
{sql_statement}
ELSE boolean_expression
{sql_statement}

where, boolean_expression is the condition that evaluates to either TRUE or FALSE.

sql_statement is any T-SQL statement.

statement_block is a collection of T-SQL statements.

BEGIN...END Statement

Syntax:

BEGIN
{sql_statement}
END

where, sql_statement is one or more SQL statements


The BEGIN...END block is nested and is most often used with the IF...ELSE statement and
the WHILE looops.

Example:

IF EXISTS (SELECT * FROM employee WHERE emp_name='anchal')


BEGIN
PRINT 'The Details of employee are Available'
SELECT * FROM employee WHERE emp_name='anchal'
END
ELSE
PRINT 'Employee details not Available'

Out Put: anchal related information viewed

IF EXISTS (SELECT * FROM employee WHERE emp_name='anchal')


BEGIN
PRINT 'The Details of employee are Available'
SELECT * FROM employee WHERE emp_name='Ram'
END
ELSE
PRINT 'Employee details not Available'

Out Put:

There is no information shown related to Ram

For Example: There are number of employee in the employee table and there salary
different according to there experience, the administrator want to increase there salary then
this code be written.

SELECT * FROM employee

IF (SELECT MAX (emp_sal) FROM employee )<45000


BEGIN
UPDATE employee
SET emp_sal=emp_sal+25000
END
ELSE
BEGIN
UPDATE employee
SET emp_sal=emp_sal+10000
END

SELECT * FROM employee

The CASE Statement

SQL server provide a programming construct called CASE statement


In this situation where several conditions need to be evaluated
The CASE statement evaluate a list of conditions and return one of the various
possible results
Here we can use IF statement to do same task

Syntax:

CASE
WHEN boolean_expression THEN expression
[[WHEN boolean_expression THEN expression]..]
[ELSE expression]
END

where, boolean_expression is a Boolean expression that is evaluated when using the CASE
statement.

For Example: Give the position according to there Salary.

SELECT emp_name, emp_sal, 'emp_position'= CASE


WHEN emp_sal=60000 THEN 'Team Leader'
WHEN emp_sal=45000 THEN 'Junior Developer'
WHEN emp_sal=80000 THEN 'Project Manager'
WHEN emp_sal=50000 THEN 'Developer'
ELSE 'Unknown'
END
FROM employee

Out Put:
The WHILE Statement

While statement is used in a batch, a stored procedure, a trigger, or a cursor


Its allowed a set of T-SQL statements to execute repeatedly as long as the given
condition hold true

Syntax:

WHILE boolean_expression
{sql_statement}
[BREAK]
{sql_statement}
[CONTINUE]

where, boolean_expression is an expression that evaluate to TRUE or FALSE.

sql_statement is any SQL statement.

BREAK cause the control to exit from the WHILE loop.

CONTINUE cause the WHILE loop to restart, skipping all the statements after the CONTINUE
keyword.

SQL Server provides the BREAK and CONTINUE statements that help control the statements
within the WHILE loop.

For Example: Factorial of 5

DECLARE @num int


DECLARE @fact int
SELECT @num=5
SELECT @fact=1
WHILE @num>0
BEGIN
SELECT @fact=@fact*@num
SELECT @num=@num-1
END
PRINT @fact

Out Put:

120
STORED PROCEDURES

SQL server is based on Client/Server technology. A number of clients send queries to the
central server. After receiving the query, the server parses the query and check the
syntaxes errors. After this processes the request. The query passes through the network ,
its add the network congestion and increased the traffic. A stored procedure is a solution to
these problems. It can be created through the Enterprise Manager or using the Query
Analyzer window with the CREATE PROCEDURE statement. "A Stored Procedure is a
precompiled object stored in the database."

Benefits Of Stored Procedure

Improved performance: SQL server does not have to compile the procedure
repeatedly
Reduction in network congestion: Application need not submit multiple T-SQL
statement to the server for the purpose of processing
Better Consistency: The coding logic and T-SQL statements defined in the
procedure are uniformly implemented across all applications as the procedure serves
as a single point of control
Better security mechanism: Users can be granted permission to execute a stored
procedure even if they do not own the procedure

Types Of Procedures

User Defined Stored procedure: The user defined stored procedures are created
by users and stored in the current database
System Stored Procedure: The system stored procedure have names prefixed with
sp_. Its manage SQL Server through administrative tasks. Which databases store
system stored procedures are master and msdb database
Temporary Stored procedures: The temporary stored procedures have names
prefixed with the # symbol. Temporary stored procedures stored in the tempdb
databases. These procedures are automatically dropped when the connection
terminates between client and server
Remote Stored Procedures: The remote stored procedures are procedures that are
created and stored in databases on remote servers. These remote procedures can be
accessed from various servers, provided the users have the appropriate permission
Extended Stored Procedures: These are Dynamic-link libraries (DLL's) that are
executed outside the SQL Server environment. They are identified by the prefix xp_

How To Create Stored Procedure

The CREATE PROCEDURE statement

Guideline

Identify the database in which the stored procedure has to be created


Determine the type of stored procedure
Determine the name for the stored procedure
Write the batch statement

Syntax
CREATE PROCEDURE proc_name
AS
BEGIN
sql-statement 1
sql-statement 1
END

where, proc_name specifies the name of the stored procedure.

For Example

CREATE PROCEDURE empNameList


AS
BEGIN
SELECT 'Employee'=emp_name, 'Salary'=emp_sal
FROM employee
END

Stored Procedure Created.

Check the existence of the procedure in the database

Syntax

sp_helptext proc_name

sp_helptext empNameList

Out Put

Execute the procedure

Syntax

EXECUTE proc_name

EXECUTE empNameList

Out Put
SQL Interview Questions And Answers

Page 1
Ques: 1 What are the difference between DDL, DML and DCL commands?
Ans:
SQL can be divided into two parts:
> The Data Manipulation Language (DML)
> The Data Definition Language (DDL).
The query and update commands form the DML part of SQL:
> SELECT - extracts data from a database
> UPDATE - updates data in a database
> DELETE - deletes data from a database
> INSERT INTO - inserts new data into a database
The DDL part of SQL permits database tables to be created or deleted. It also
define indexes (keys), specify links between tables, and impose constraints
between tables. The most important DDL statements in SQL are:
> CREATE DATABASE - creates a new database
> ALTER DATABASE - modifies a database
> CREATE TABLE - creates a new table
> ALTER TABLE - modifies a table
> DROP TABLE - deletes a table
> CREATE INDEX - creates an index (search key)
> DROP INDEX - deletes an index
Data Control Language (DCL) statements. Some examples:
> GRANT - gives user's access privileges to database
> REVOKE - withdraw access privileges given with the GRANT command
Ques: 2 Which one is faster DELETE/TRUNCATE?
Ans:
Truncante is more faster than delete because when we delete the records from
the database, database has to perform 2 actions.
> Delete from the database
> Write the deleted records into "rollback"
segments. But incase of "Truncate" the second activity is not required.It is
faster than becouse truncate is a ddl command so it does not produce any
rollback information and the storage space is released while the delete
command is a dml command and it produces rollback information too and space
is not deallocated using delete command.
Ques: 3 What is RDBMS?
Ans:
RDBMS stands for Relational Database Management
System. RDBMS is the basis for SQL, and for all
modern database systems like MS SQL Server, IBM
DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in
database objects
called tables. A table is a collections of
related data entries and it consists of columns
and rows.Relational Data Base Management Systems
(RDBMS) are database management systems that maintain data records and
indices in tables. Relationships may be created and maintained across and
among the data and tables. In a relational database, relationships between
data items are expressed by means of tables. Interdependencies among these
tables are expressed by data values rather than by pointers. This allows a
high degree of data independence. An RDBMS has the capability to recombine
the data items from different files, providing powerful tools for data usage.
Ques: 4 What are different normalization forms?
Ans:
normalisation have a se veral forms that a database structure can be subject
to, each with rules that constrain the database further and each creating
what is called a Normal Form. These are, in order:
> First Normal Form (1NF)
> Second Normal Form (2NF)
> Third Normal Form (3NF)
> Boyce Codd Normal Form (BCNF)
> Fourth Normal Form (4NF)
> Fifth Normal Form (5NF)
> Optimal Normal Form (ONF)
> Domain-Key Normal Form (DKNF)
Theses are defined as :
> 1NF: Eliminate Repeating Groups : Make a separate table for each set of
related attributes, and give each table a primary key. Each field contains at
most one value from its attribute domain.
> 2NF: Eliminate Redundant Data : If an attribute depends on only part of a
multi-valued key, remove it to a separate table.
> 3NF: Eliminate Columns Not Dependent On Key : If attributes do not
contribute to a description of the key, remove them to a separate table. All
attributes must be directly dependent on the primary key.
> BCNF: Boyce-Codd Normal Form : If there are non-trivial dependencies
between candidate key attributes, separate them out into distinct tables.
> 4NF: Isolate Independent Multiple Relationships : No table may contain two
or more 1:n or n:m relationships that are not directly related.
> 5NF: Isolate Semantically Related Multiple : Relationships There may be
practical constrains on information that justify separating logically related
many-to-many relationships.
> ONF: Optimal Normal Form : A model limited to only simple (elemental)
facts, as expressed in Object Role Model notation.
> DKNF: Domain-Key Normal Form : A model free from all modification anomalies.
Ques: 5 What is normalization?
Ans:
Normalisation is a process whish is the tables in a database are optimised to
remove the potential for redundancy. Two main problems may arise if this is
not done:
> Repeated data makes a database bigger.
> Multiple instances of the same values make
maintaining the data more difficult and can
create anomalies.
Ques: 6 What is Stored Procedure
Ans:
A stored procedure is a named group of SQL statements that have been
previously created and stored in the server database. Stored procedures
accept input parameters so that a single procedure can be used over the
network by several clients using different input data. And when the procedure
is modified, all clients automatically get the new version. 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
Ques: 7 What is Trigger?
Ans:
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 the referential integrity of data by
changing the data in a systematic fashion. A trigger cannot be called or
executed; the DBMS automatically fires the trigger as a result of a data
modification to the associated table. Triggers can be viewed as similar to
stored procedures in that both consist of procedural logic that is stored at
the database level. Stored procedures, however, are not event-drive and are
not attached to a specific table as triggers are. Stored procedures are
explicitly executed by invoking a CALL to the procedure while triggers are
implicitly executed. In addition, triggers can also execute stored procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic
within itself, so when the trigger is fired because of data modification it
can also cause another data modification, thereby firing another trigger. A
trigger that contains data modification logic within itself is called a
nested trigger.
Ques: 8 What is View?
Ans:
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. Rows updated or
deleted in the view are updated or deleted in the table the view was created
with. It should also be noted that as data in the original table changes, so
does data in the view, as views are the way to look at part of the original
table. The results of using a view are not permanently stored in the
database. The data accessed through a view is actually constructed using
standard T-SQL select command and can come from one to many different base
tables or even other views.
Ques: 9 What is Index?
Ans:
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. The users cannot see the indexes, they are just used
to speed up queries. Effective indexes are one of the best ways to improve
performance in a database application
. A table scan happens when there is no index available to help a query. In a
table scan SQL Server examines every row in the table to satisfy the query
results. Table scans are sometimes unavoidable, but on large tables, scans
have a terrific impact on performance.
Ques: 10 What is SQL?
Ans:
SQL is a bassically standard language for accessing and manipulating
databases. Its is defines as :
> SQL stands for Structured Query Language
> SQL lets you access and manipulate databases
> SQL is an ANSI (American National Standards Institute) standard.
SQL have a many properties, It can do :
> SQL can execute queries against a database.
> SQL can retrieve data from a database.
> SQL can insert records in a database.
> SQL can update records in a database.
> SQL can delete records from a database.
> SQL can create new databases.
> SQL can create new tables in a database.
> SQL can create stored procedures in a database.
> SQL can create views in a database.
> SQL can set permissions on tables, procedures,
and views.
Ques: 11 What are the components of physical database structure of Oracle
database?
Ans:
Physical components of oracle database are:
> Control files,
> Redo log files and
> Datafiles.

> Control file : control file is basicaly a type of file .Its read in the
mount state of database. control file is a small binary file which records
the physical structure of database which includes
* Database name
* names and locations of datafiles and online
redo log files.
* timestamp of database creation
* check point information
* current log sequence number.

Redo log files : Redo log files usually use for the saving to the files. This
files saves all the changes that are made to the database as they occur. This
plays a great role in the database recovery.

Datafiles : Datafiles are the physicalfiles which stores data of all logical
structure.
Ques: 12 What are the components of logical database structure of Oracle
database?
Ans:
The Logical Database Structure of an Oracle include :
> The schema objects,
> Data blocks,
> Extents,
> Segments and
> Tablespaces.

> schema objects : means table, index, synonyms, sequences etc.

> Data blocks : are the smallest part of the oracle database defined by
DB_BLOCK_SIZE parameter.

> Extent : A group of data blocks forms an extent.

> Segments : An extents groups tends to segments,

> Table space : lastly a group of segment forms a tablespace.


Ques: 13 What is a tablespace?
Ans:
A Tablespace is bassically a logical storage unit within an Oracle database.
It is logical because a tablespace is not visible in the file system of the
machine on which the database resides. A tablespace, in turn, consists of at
least one data file which are physically located in the file system of the
server. b/w datafile belongs to exactly one tablespace. Each table index and
so on that is stored in an Oracle database belongs to a tablespace. The
tablespace builds the bridge between the Oracle database and the filesystem
in which the table's or index' data is stored. There are three types of
tablespaces in Oracle:
> Permanent tablespaces
> Undo tablespaces
> temporary tablespaces
A tablespace is created with the create tablespace sql command.
Ques: 14 What is SYSTEM tablespace and when is it created?
Ans:
Every ORACLE database have a table space which name is SYSTEM . when the
database is created taht a time its also automatically created. The SYSTEM
tablespace always contains the data dictionary tables for the entire database.
Ques: 15 Explain the relationship among database, tablespace and data file.
Ans:
Database : Database is the Collection of data is called database.

Table Space : The table space ismany use for storing the data in the
database. When a database is created two table spaces are created.
i) System Table Space : This data file stores
all the tables related to the system and dba tables.
ii) User Table Space : This data file stores all the user related tables. We
should have separate table spaces for storing the tables and indexes so that
the access is fast.

Data Files : Every Oracle Data Base has one or more physical data files.
They store the data for the database. Every data-file is associated with only
one database. Once the Data file is created the size cannot change. To
increase the size of the database to store more data we have to add data
file.
Ques: 16 What is schema?
Ans:
Schema bassically Pronounce skee-ma, It is the structure of a database
system,It described in a formal language supported by the database management
system (DBMS). In the RDBMS (Relational database System) , the schema defines
the tables, the fields in each table, and the Schemas are generally stored in
a data dictionary . Even a schema is defined in text database language , the
term is often used to refer to a graphical depiction of the database
structure.
Ques: 17 What are Schema Objects?
Ans:
Schema is bassically a Associated with each database user . It is a
collection of schema objects. Examples of schema objects include tables,
views, sequences, synonyms, indexes, clusters, database links, snapshots,
procedures, functions, and packages. Schema objects are logical data storage
structures. Schema objects don't have a one-to-one correspondence to physical
files on disk that store their information. Even Oracle stores a schema
object logically within a tablespace of the database. The data of each object
is physically contained in one or more of the tablespace's datafiles.
Ques: 18 Can objects of the same schema reside in different table spaces?
Ans:
Yes we can objects of the same schema reside in different table space. Schema
objects can stored in different tablespace and a tablespace can contained one
or more schema objects data.
Ques: 19 Can a tablespace hold objects from different schemes?
Ans:
Yes we can a template hold objects from different schemes.
Ques: 20 What is Oracle table?
Ans:
The Collection of informations stored in the strutrued format which is in
rows and columns formate that is called a table.

SQL Interview Questions And Answers

Page 1

Ques: 1 I Have a table in which there is a chance of duplicate rows. Can you please
tell me how to eliminate the dup;licate records?
Ans:
Use primary key If column is like Id or no..Alternate way is you can apply
unique constraint on column.. hope u hv cleared ur doubts
Ans:
Deletion of duplicate records:
delete from emp a where a.rowid > (select min(b.rowid)
from emp b where a.rowid=b.rowid)

or

delete from table t1 where t1.rowid < (select max(t2.rowid) from table t2
where t2.<common column_name> = t1.<common column_name>)
Ques: 2 What is use of 'in' command?
Ans:
in command use suppose u want to choose department then you use in command

ex=select ename,sal from emp


where deptno in(10,20);
Ques: 3 Class members
Ques: 4 What is the Sql Wild card?
Ans:
SQL Wild Card is the bassically use for the searchign opration similarily
LIKE function.SQL wildcards can substitute for one or more characters when
searching for data in a database.
the following wildcards can be used:
> % - A substitute for zero or more characters
> _ - A substitute for exactly one character
> [charlist] - Any single character in charlist
> [^charlist] or [!charlist] - Any single character not in charlist
Ans:
% -
Ques: 5 Describe TO_DATE function?
Ans:
The TO_DATE function using the values when we want to be show thw timestamp
from a character string that has been interpreted using a character template.
Ques: 6 In what sequence SQL statement are processed?
Ans:
The sequence of SQL statement are processed in the following sequence (DB2):
> FROM clause
> WHERE clause
> GROUP BY clause
> HAVING clause
> SELECT clause
> ORDER BY clause
> FETCH FIRST clause
Ques: 7 What databases do you know?
Ans:
Yes we know lots of Databases, we are mentioned there :
> Informix
> DB2
> SQL
> Oracle

Ques: 8 What are the main attributes of database management system?


Ans:
A database management system have a many attributes but here we are mentioned
that DBMS is composed of five elements, Which is there :
> Computer hardware,
> Software,
> Data,
> People (users), and
> Operations procedures
Ques: 9 What are the main components of Database management systems software.
Ans:
The database management system software includes
many components are there, like :
> for storage management,
> concurrency control,
> transaction processing,
> database manipulation interface,
> database definition interface, and
> database control interface.

Ques: 10 What is query optimization?


Ans:
In the database many queries generate and executed or Query optimization is
the part of the query process in which the database system compares different
query strategies and chooses the one with the least expected cost.
Ques: 11 What Oracle lock modes do you know?
Ans:
Oracle has two lock modes :
> shared or
> exclusive.
Shared locks are set on database resources so that
many transactions can access the resource.
Exclusive locks are set on resources that ensure
one transaction has exclusive access to the database resource

Ques: 12 What is Oracle locking?


Ans:
Oracle is the bassically a database Its have a many facility, taht facilities
is onne of the name is locking which uses locking mechanisms to protect data
from being destroyed by concurrent transactions.
Ques: 13 What does COMMIT do?
Ans:
Its manly work is Saving all changes made by DML statements.
Ques: 14 Discuss about Disadvantages of cursors?
Ans:
Many disadvantages are in Cursor which is defined here :
> Occurs network roundtrip becouse Each time we fetch a row from the cursor,;
where as a normal SELECT query makes only one roundtrip, however large the
resultset is.
> It is very costly because they require more resources and temporary
storage. Further, there are restrictions on the SELECT statements that can be
used with some types of cursors.
> Another situation in which developers tend to use cursors: we need to call
a stored procedure when a column in a particular row meets certain condition.
We don't have to use cursors for this. This can be achieved using WHILE loop,
as long as there is a unique key to identify each row.
Ques: 15 What is RAID and what are different types of RAID configurations?
Ans:
Redundant Array of Inexpensive Disks is abriviation of RAID, It is maily use
for providing the facility of fault tolerance to database servers. There are
six RAID levels 0 through 5 offering different levels of performance, fault
tolerance.
Ans:
Redundant Array of Inexpensive Disks is abriviassion of RAID, Its mainly use
for providing the facility for fault tolerance to database servers. There
are six RAID levels 0 through 5 offering different levels of performance,
fault tolerance.
Ques: 16 What do you mean by Serialized?
Ans:
It is the part of the isolation level , Its bassically use for the Data read
by the current transaction cannot be changed by another transaction until the
current transaction finishes. No new data can be inserted that would affect
the current transaction.
Ques: 17 What do you mean by Repeatable Read?
Ans:
It is the defined bassically a isolation properties and its works on the
Isolation level as a Data read by a current transaction cannot be changed by
another transaction until the current transaction finishes. Any type of new
data can be inserted during a transaction.
Ques: 18 What do you mean by Read Committed?
Ans:
t is the bassically defined as a Isolation properties , It is using for the
tracsaction, which is A transaction cannot read data that is being modified
by another transaction that has not committed. This is the default isolation
level in Microsoft SQL Server.
Ques: 19 What do you mean by Read Uncommitted?
Ans:
First of all I Would like to tell every one its a Type of Isolation Level ,
It is the mainly use for the transaction, which transaction can read any
data, even if it is being modified by another transaction. This is the least
safe isolation level but allows the highest concurrency.
Ques: 20 What is a Cartesian product?
Ans:
A Cartesian product is bassically use for the results from a faulty query. It
is a row in the results for every combination in the join tables.

SQL Interview Questions And Answers

Page 1

Tot
Show al Post Your
Questions Last Post
Answers Pos Answers
ts

SQL stands Structured Query


Language? Show Post Your
1. true 17
Answers Answers jayashree
2. false

Choose correct answers:


1 SQL can execute system
applications like java ,c# .
2 SQL can delete or update or
retrieve or create records from a Show Post Your
database 6
Answers Answers hakimuddin
3.SQL never permanently change
database recodes .
4 All
5 None

Choose correct options


1. MS Access, SQL Server, MySQL are
database
2. MS Access, SQL Server, MySQL are Show Post Your 11.03.10
vendor company. 1
Answers Answers Vivak
3 MS Access, SQL Server, MySQL are
programming language
4. All
5. None.
Choose correct statements for
fallowing sql statement
SELECT * FROM r4r_emp;

1. used to select all records Show Post Your 11.03.10


from table 1
Answers Answers Vikas
2. used to select all columns
name from table
3. used to select all rows from
tables
4. None.
SELECT * FROM r4r_emp; Show 5 Post Your
Above is part of DML in SQL? Himanshu
Answers Answers
1. true
2. false
3. no such query into sql. Varshney
4. None.

DDL statements in SQL are:


1.SELECT,UPDATE, DELETE,ALTER ,
CREATE, ALTER , DROP
2.SELECT, DELETE,ALTER , CREATE, Show Post Your
ALTER , DROP 4
Answers Answers Alok Kumar Ranjan
3.SELECT,ALTER , CREATE, ALTER ,
DROP
4 None.

SELECT DISTINCT column_name(s)


FROM table_name is used for:
1. Select all records including
Show Post Your
NULL values 2
2. Select All records with Answers Answers Snehal
different values only.
3. Select no any records.
4. None
SELECT * column_name(s)
FROM table_name is used for:
1. Select all records including
Show Post Your 11.03.10
with duplicate values 1
2. Select All records with Answers Answers Rajesh Kumar
different values only.
3. Select no any records.
4. None
SELECT * FROM r4r_team WHERE
office=Lucknow is used for:
1. Select all records including
with duplicate values from
r4r_team table.
2. Select All records with
Show Post Your 04.06.10
different values only from r4r_team 2
table. Answers Answers kamalkant
3. Select no any records.
4. select all records whose has
office is Lucknow from r4r_team
table
5. None

SELECT * FROM r4r_team WHERE Show 1 Post Your 11.03.10


office=Lucknow is used for: Rajesh Kumar
Answers Answers
1. Select all records including
with duplicate values from
r4r_team table.
2. Select All records with
different values only from r4r_team
table.
3. Select no any records.
4. select all records whose has
office is Lucknow from r4r_team
table
5. Error
SELECT * FROM r4r_team WHERE
exp='2' is used for:
1. Select all records including
with duplicate values from
r4r_team table.
Show Post Your 03.07.10
2. Select All records with 3
different values only from r4r_team Answers Answers vignesh raja
table.
3. Select no any records.
4. select all records whose has
office is 2' from r4r_team table
5. Error
Which is not used into SQL
=,<>,> ,<,>=,<=,>>>
Show Post Your 13.03.10
1. all are used 2
2. only >>> not used Answers Answers gourav
3. only <>
4. None
<> and != both are same operator
into SQL
1. true.
Show Post Your 11.03.10
2 false. 1
3. both are not used into SQL. Answers Answers Rajesh Kumar
4. Both are used assembly languages
only.

Choose true option

1. BETWEEN -->>Used for range with


in values
Show Post Your 19.07.10
2. LIKE -->>Used for Search a 2
pattern Answers Answers appu
3. IN -->>return east one of the
columns in given set of values
4.1,2,3
5. None
Which is true for AND & OR

1.These are Operators .Which are


used to filter records based on Show Post Your 11.03.10
more than one conditions. 1
Answers Answers Rajesh Kumar
2.These Operators are used to join
two tables.
3.Never used in SQL
4.None
What is true for following DML SQL Show 2 Post Your 04.04.10
statement swarn
Answers Answers
SELECT username, exp, salary FROM
r4r_team ORDER BY username DESC;
1.Used to select username,exp,
salary from r4r_team which is
decreasing order by username.
2.Used to select username,exp,
salary from r4r_team which is
increasing order by username.
3.Used to select username,exp,
salary from r4r_team which is
decreasing order by exp.
4. None

Choose correct syntax to insert


values into r4r_team table

1. INSERT INTO r4r_team (id,


username, exp) VALUES (1, r4r01,
2);

2. INSERT INTO r4r_team VALUES (1,


Show Post Your
r4r01, 2); 8
Answers Answers jeetesh
3. INSERT INTO r4r_team (id,
username, exp) VALUE (1, r4r01,
2);

4. INSERT INTO table r4r_team (id,


username, exp) VALUE (1, r4r01,
2);

Question: What is RDBMS?


Answer: Relational Data Base Management Systems (RDBMS) are database management
systems that maintain data records and indices in tables. Relationships may be created and
maintained across and among the data and tables. In a relational database, relationships
between data items are expressed by means of tables. Interdependencies among these
tables are expressed by data values rather than by pointers. This allows a high degree of
data independence. An RDBMS has the capability to recombine the data items from different
files, providing powerful tools for data usage.

Question: What is normalization?


Answer: Database normalization is a data design and organization process applied to data
structures based on rules that help build relational databases. In relational database design,
the process of organizing data to minimize redundancy. Normalization usually involves
dividing a database into two or more tables and defining relationships between the tables.
The objective is to isolate data so that additions, deletions, and modifications of a field can
be made in just one table and then propagated through the rest of the database via the
defined relationships.

Question: What are different normalization forms?


Answer: 1NF: Eliminate Repeating Groups
Make a separate table for each set of related attributes, and give each table a primary key.
Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data
If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key
If attributes do not contribute to a description of the key, remove them to a separate table.
All attributes must be directly dependent on the primary key
BCNF: Boyce-Codd Normal Form
If there are non-trivial dependencies between candidate key attributes, separate them out
into distinct tables.
4NF: Isolate Independent Multiple Relationships
No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF: Isolate Semantically Related Multiple Relationships
There may be practical constrains on information that justify separating logically related
many-to-many relationships.
ONF: Optimal Normal Form
A model limited to only simple (elemental) facts, as expressed in Object Role Model
notation.
DKNF: Domain-Key Normal Form
A model free from all modification anomalies. Remember, these normalization guidelines are
cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF
database.

Question: What is Stored Procedure?


Answer: A stored procedure is a named group of SQL statements that have been previously
created and stored in the server database. Stored procedures accept input parameters so
that a single procedure can be used over the network by several clients using different input
data. And when the procedure is modified, all clients automatically get the new version.
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.

Question: What is Trigger?


Answer: 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 the referential integrity of data by changing the data in a systematic
fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as
a result of a data modification to the associated table. Triggers can be viewed as similar to
stored procedures in that both consist of procedural logic that is stored at the database
level. Stored procedures, however, are not event-drive and are not attached to a specific
table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the
procedure while triggers are implicitly executed. In addition, triggers can also execute
stored procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself,
so when the trigger is fired because of data modification it can also cause another data
modification, thereby firing another trigger. A trigger that contains data modification logic
within itself is called a nested trigger.

Question: What is View?


Answer: 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. Rows updated or deleted in the view
are updated or deleted in the table the view was created with. It should also be noted that
as data in the original table changes, so does data in the view, as views are the way to look
at part of the original table. The results of using a view are not permanently stored in the
database. The data accessed through a view is actually constructed using standard T-SQL
select command and can come from one to many different base tables or even other views.

Question: What is Index?


Answer: 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. The
users cannot see the indexes, they are just used to speed up queries. Effective indexes are
one of the best ways to improve performance in a database application. A table scan
happens when there is no index available to help a query. In a table scan SQL Server
examines every row in the table to satisfy the query results. Table scans are sometimes
unavoidable, but on large tables, scans have a terrific impact on performance. Clustered
indexes define the physical sorting of a database tables rows in the storage media. For this
reason, each database table may have only one clustered index. Non-clustered indexes are
created outside of the database table and contain a sorted list of references to the table
itself.

Oracle interview Questions

Oracle Concepts and Architecture

Database Structures

Qus. What are the components of physical database structure of Oracle database?
Ans: Oracle database is comprised of three types of files. One or more datafiles, two are
more redo log files, and one or more control files.

Qus. What are the components of logical database structure of Oracle database?
Ans: There are tablespaces and database's schema objects.

Qus. What is a tablespace?


Ans: A database is divided into Logical Storage Unit called tablespaces. A tablespace is used
to grouped related logical structures together.

Qus. What is SYSTEM tablespace and when is it created?


Ans: Every Oracle database contains a tablespace named SYSTEM, which is automatically
created when the database is created. The SYSTEM tablespace always contains the data
dictionary tables for the entire database.

Qus. Explain the relationship among database, tablespace and data file.
Ans: Each databases logically divided into one or more tablespaces one or more data files
are explicitly created for each tablespace.

Qus. What is schema?


Ans: A schema is collection of database objects of a user.
Qus. What are Schema Objects?
Ans: Schema objects are the logical structures that directly refer to the database's data.
Schema objects include tables, views, sequences, synonyms, indexes, clusters, database
triggers, procedures, functions packages and database links.

Qus. Can objects of the same schema reside in different table spaces?
Ans: Yes.

Qus. Can a tablespace hold objects from different schemes?


Ans: Yes.

Qus. . What is Oracle table?


Ans: A table is the basic unit of data storage in an Oracle database. The tables of a
database hold all of the user accessible data. Table data is stored in rows and columns.

Qus. . What is an Oracle view?


Ans: A view is a virtual table. Every view has a query attached to it. (The query is a SELECT
statement that identifies the columns and rows of the table(s) the view uses.)

Qus. . Do a view contain data?


Ans: Views do not contain or store data.

Qus. . Can a view based on another view?


Ans: Yes.

Qus. . What are the advantages of views?


Ans: - Provide an additional level of table security, by restricting access to a predetermined
set of rows and columns of a table.
- Hide data complexity.
- Simplify commands for the user.
- Present the data in a different perspective from that of the base table.
- Store complex queries.

Qus. . What is an Oracle sequence?


Ans: A sequence generates a serial list of unique numbers for numerical columns of a
database's tables.

Qus. . What is a synonym?


Ans: A synonym is an alias for a table, view, sequence or program unit.

Qus. . What are the types of synonyms?


Ans: There are two types of synonyms private and public.

Qus. . What is a private synonym?


Ans: Only its owner can access a private synonym.

Qus. . What is a public synonym?


Ans: Any database user can access a public synonym.
Qus. . What are synonyms used for?
Ans: - Mask the real name and owner of an object.
- Provide public access to an object
- Provide location transparency for tables, views or program units of a remote database.
- Simplify the SQL statements for database users.

Qus. . What is an Oracle index?


Ans: An index is an optional structure associated with a table to have direct access to rows,
which can be created to increase the performance of data retrieval. Index can be created on
one or more columns of a table.

Qus. . How are the index updates?


Ans: Indexes are automatically maintained and used by Oracle. Changes to table data are
automatically incorporated into all relevant indexes.

Qus. . What are clusters?


Ans: Clusters are groups of one or more tables physically stores together to share common
columns and are often used together.

Qus. . What is cluster key?


Ans: The related columns of the tables in a cluster are called the cluster key.

Qus. . What is index cluster?


Ans: A cluster with an index on the cluster key.

Qus. . What is hash cluster?


Ans: A row is stored in a hash cluster based on the result of applying a hash function to the
row's cluster key value. All rows with the same hash key value are stores together on disk.

Qus. . When can hash cluster used?


Ans: Hash clusters are better choice when a table is often queried with equality queries. For
such queries the specified cluster key value is hashed. The resulting hash key value points
directly to the area on disk that stores the specified rows.

Qus. . What is database link?


Ans: A database link is a named object that describes a "path" from one database to
another.

Qus. . What are the types of database links?


Ans: Private database link, public database link & network database link.

Qus. . What is private database link?


Ans: Private database link is created on behalf of a specific user. A private database link
can be used only when the owner of the link specifies a global object name in a SQL
statement or in the definition of the owner's views or procedures.
Qus. . What is public database link?
Ans: Public database link is created for the special user group PUBLIC. A public database
link can be used when any user in the associated database specifies a global object name in
a SQL statement or object definition.

Qus. . What is network database link?


Ans: Network database link is created and managed by a network domain service. A
network database link can be used when any user of any database in the network specifies
a global object name in a SQL statement or object definition.

Qus. . What is data block?


Ans: Oracle database's data is stored in data blocks. One data block corresponds to a
specific number of bytes of physical database space on disk.

Qus. . How to define data block size?


Ans: A data block size is specified for each Oracle database when the database is created. A
database users and allocated free database space in Oracle data blocks. Block size is
specified in init.ora file and cannot be changed latter.

Qus. . What is row chaining?


Ans: In circumstances, all of the data for a row in a table may not be able to fit in the same
data block. When this occurs, the data for the row is stored in a chain of data block (one or
more) reserved for that segment.

Qus. . What is an extent?


Ans: An extent is a specific number of contiguous data blocks, obtained in a single
allocation and used to store a specific type of information.

Qus. . What is a segment?


Ans: A segment is a set of extents allocated for a certain logical structure.

Qus. . What are the different types of segments?


Ans: Data segment, index segment, rollback segment and temporary segment.

Qus. . What is a data segment?


Ans: Each non-clustered table has a data segment. All of the table's data is stored in the
extents of its data segment. Each cluster has a data segment. The data of every table in the
cluster is stored in the cluster's data segment.

Qus. . What is an index segment?


Ans: Each index has an index segment that stores all of its data.

Qus. . What is rollback segment?


Ans: A database contains one or more rollback segments to temporarily store "undo"
information.
Qus. . What are the uses of rollback segment?
Ans: To generate read-consistent database information during database recovery and to
rollback uncommitted transactions by the users.

Qus. . What is a temporary segment?


Ans: Temporary segments are created by Oracle when a SQL statement needs a temporary
work area to complete execution. When the statement finishes execution, the temporary
segment extents are released to the system for future use.

Qus. . What is a datafile?


Ans: Every Oracle database has one or more physical data files. A database's data files
contain all the database data. The data of logical database structures such as tables and
indexes is physically stored in the data files allocated for a database.

Qus. . What are the characteristics of data files?


Ans: A data file can be associated with only one database. Once created a data file can't
change size. One or more data files form a logical unit of database storage called a
tablespace.

Qus. . What is a redo log?


Ans: The set of redo log files for a database is collectively known as the database redo log.

Qus. . What is the function of redo log?


Ans: The primary function of the redo log is to record all changes made to data.

Qus. . What is the use of redo log information?


Ans: The information in a redo log file is used only to recover the database from a system
or media failure prevents database data from being written to a database's data files.

Qus. . What does a control file contains?


Ans: - Database name
- Names and locations of a database's files and redolog files.
- Time stamp of database creation.

Qus. . What is the use of control file?


Ans: When an instance of an Oracle database is started, its control file is used to identify
the database and redo log files that must be opened for database operation to proceed. It is
also used in database recovery.
Data Base Administration

Qus. . What is a database instance? Explain.


Ans: A database instance (Server) is a set of memory structure and background processes
that access a set of database files. The processes can be shared by all of the users.

The memory structure that is used to store the most queried data from database. This helps
up to improve database performance by decreasing the amount of I/O performed against
data file.

Qus. . What is Parallel Server?


Ans: Multiple instances accessing the same database (only in multi-CPU environments)

Qus. . What is a schema?


Ans: The set of objects owned by user account is called the schema.

Qus. . What is an index? How it is implemented in Oracle database?


Ans: An index is a database structure used by the server to have direct access of a row in a
table. An index is automatically created when a unique of primary key constraint clause is
specified in create table command

Qus. . What are clusters?


Ans: Group of tables physically stored together because they share common columns and
are often used together is called cluster.

Qus. . What is a cluster key?


Ans: The related columns of the tables are called the cluster key. The cluster key is indexed
using a cluster index and its value is stored only once for multiple tables in the cluster.

Qus. . What is the basic element of base configuration of an Oracle database?


Ans: It consists of
one or more data files.
one or more control files.
two or more redo log files.
The Database contains
multiple users/schemas
one or more rollback segments
one or more tablespaces
Data dictionary tables
User objects (table,indexes,views etc.,)
The server that access the database consists of
SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool)
SMON (System MONito)
PMON (Process MONitor)
LGWR (LoG Write)
DBWR (Data Base Write)
ARCH (ARCHiver)
CKPT (Check Point)
RECO
Dispatcher
User Process with associated PGS

Qus. . What is a deadlock? Explain.


Ans: Two processes waiting to update the rows of a table, which are locked by other
processes then deadlock arises. In a database environment this will often happen because
of not issuing the proper row lock commands. Poor design of front-end application may
cause this situation and the performance of server will reduce drastically. These locks will be
released automatically when a commit/rollback operation performed or any one of this
processes being killed externally.

Memory Management

Qus. . What is SGA?


Ans: The System Global Area in an Oracle database is the area in memory to facilitate the
transfer of information between users. It holds the most recently requested structural
information between users. It holds the most recently requested structural information
about the database. The structure is database buffers, dictionary cache, redo log buffer and
shared pool area.

Qus. . What is a shared pool?


Ans: The data dictionary cache is stored in an area in SGA called the shared pool. This will
allow sharing of parsed SQL statements among concurrent users.

Qus. . What is mean by Program Global Area (PGA)?


Ans: It is area in memory that is used by a single Oracle user process.

Qus. . What is a data segment?


Ans: Data segment are the physical areas within a database block in which the data
associated with tables and clusters are stored.

Qus. . What are the factors causing the reparsing of SQL statements in SGA?
Ans: Due to insufficient shared pool size.
Monitor the ratio of the reloads takes place while executing SQL statements. If the ratio is
greater than 1 then increase the SHARED_POOL_SIZE.

Database Logical & Physical Architecture

Qus. . What is Database Buffers?


Ans: Database buffers are cache in the SGA used to hold the data blocks that are read from
the data segments in the database such as tables, indexes and clusters
DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size.

Qus. . What is dictionary cache?


Ans: Dictionary cache is information about the database objects stored in a data dictionary
table.

Qus. . What is meant by recursive hints?


Ans: Number of times processes repeatedly query the dictionary table is called recursive
hints. It is due to the data dictionary cache is too small. By increasing the
SHARED_POOL_SIZE parameter we can optimize the size of data dictionary cache.

Qus. . What is redo log buffer?


Ans: Changes made to the records are written to the on-line redo log files. So that they can
be used in roll forward operations during database recoveries. Before writing them into the
redo log files, they will first brought to redo log buffers in SGA and LGWR will write into files
frequently. LOG_BUFFER parameter will decide the size.

Qus. . How will you swap objects into a different table space for an existing database?
Ans: - Export the user
- Perform import using the command imp system/manager file=export.dmp
indexfile=newrite.sql. This will create all definitions into newfile.sql.
- Drop necessary objects.
- Run the script newfile.sql after altering the tablespaces.
- Import from the backup for the necessary objects.

Qus. . List the Optional Flexible Architecture (OFA) of Oracle database? How can we
organize the tablespaces in Oracle database to have maximum performance?
Ans: SYSTEM - Data dictionary tables.
DATA - Standard operational tables.
DATA2- Static tables used for standard operations
INDEXES - Indexes for Standard operational tables.
INDEXES1 - Indexes of static tables used for standard operations.
TOOLS - Tools table.
TOOLS1 - Indexes for tools table.
RBS - Standard Operations Rollback Segments,
RBS1,RBS2 - Additional/Special Rollback segments.
TEMP - Temporary purpose tablespace
TEMP_USER - Temporary tablespace for users.
USERS - User tablespace.

Qus. . How will you force database to use particular rollback segment?
Ans: SET TRANSACTION USE ROLLBACK SEGMENT rbs_name.

Qus. . What is meant by free extent?


Ans: A free extent is a collection of continuous free blocks in tablespace. When a segment is
dropped its extents are reallocated and are marked as free.

Qus. .Which parameter in Storage clause will reduce number of rows per block?
Ans: PCTFREE parameter
Row size also reduces no of rows per block.

Qus. . What is the significance of having storage clause?


Ans: We can plan the storage for a table as how much initial extents are required, how
much can be extended next, how much % should leave free for managing row updating,
etc.,
Qus. . How does Space allocation table place within a block?
Ans: Each block contains entries as follows
Fixed block header
Variable block header
Row Header, row date (multiple rows may exists)
PCTEREE (% of free space for row updating in future)

Qus. . What is the role of PCTFREE parameter is storage clause?


Ans: This is used to reserve certain amount of space in a block for expansion of rows.

Qus. . What is the OPTIMAL parameter?


Ans: It is used to set the optimal length of a rollback segment.

Qus. . What is the functionality of SYSTEM table space?


Ans: To manage the database level transactions such as modifications of the data dictionary
table that record information about the free space usage.

Qus. . How will you create multiple rollback segments in a database?


- Create a database, which implicitly creates a SYSTEM rollback segment in a SYSTEM
tablespace.
- Create a second rollback segment name R0 in the SYSTEM tablespace.
- Make new rollback segment available (after shutdown, modify init.ora file and start
database)
- Create other tablespaces (RBS) for rollback segments.
- Deactivate rollback segment R0 and activate the newly created rollback segments.

Qus. . How the space utilization takes place within rollback segments?
Ans: It will try to fit the transaction in a cyclic fashion to all existing extents. Once it found
an extent is in use then it forced to acquire a new extent (number of extents is based on the
optimal size)

Qus. . Why query fails sometimes?


Ans: Rollback segment dynamically extent to handle larger transactions entry loads.
A single transaction may wipeout all available free space in the rollback segment
tablespace. This prevents other user using rollback segments.

Qus. . How will you monitor the space allocation?


Ans: By querying DBA_SEGMENT table/view

Qus. . How will you monitor rollback segment status?


Ans: Querying the DBA_ROLLBACK_SEGS view

IN USE - Rollback Segment is on-line.


AVAILABLE - Rollback Segment available but not on-line.
OFF-LINE - Rollback Segment off-line
INVALID - Rollback Segment Dropped.
NEEDS RECOVERY - Contains data but need recovery or corrupted.
PARTLY AVAILABLE - Contains data from an unresolved transaction involving a
distributed database.

Qus. . List the sequence of events when a large transaction that exceeds beyond its
optimal value when an entry wraps and causes the rollback segment to expand into another
extend.
Ans: Transaction Begins.
An entry is made in the RES header for new transactions entry
Transaction acquires blocks in an extent of RBS
The entry attempts to wrap into second extent. None is available, so that the RBS must
extent.
The RBS checks to see if it is part of its OPTIMAL size.
RBS chooses its oldest inactive segment.
Oldest inactive segment is eliminated.
RBS extents
The data dictionary tables for space management are updated.
Transaction Completes.

Qus. . How can we plan storage for very large tables?


Ans: Limit the number of extents in the table
Separate table from its indexes.
Allocate sufficient temporary storage.

Qus. . How will you estimate the space required by a non-clustered table?
Ans: Calculate the total header size
Calculate the available data space per data block
Calculate the combined column lengths of the average row
Calculate the total average row size.
Calculate the average number rows that can fit in a block
Calculate the number of blocks and bytes required for the table.
After arriving the calculation, add 10 % additional space to calculate the initial extent size
for a working table.

Qus. . It is possible to use raw devices as data files and what are the advantages over file
system files?
Ans: Yes.
The advantages over file system files are that I/O will be improved because Oracle is bye-
passing the kernel which writing into disk. Disk corruption will be very less.

Qus. . What is a Control file?


Ans: Database's overall physical architecture is maintained in a file called control file. It will
be used to maintain internal consistency and guide recovery operations. Multiple copies of
control files are advisable.
Qus. . How to implement the multiple control files for an existing database?
Shutdown the database
Ans: Copy one of the existing control file to new location
Edit Config ora file by adding new control filename
Restart the database.

Qus. . What is redo log file mirroring? How can be achieved?


Ans: Process of having a copy of redo log files is called mirroring.
This can be achieved by creating group of log files together, so that LGWR will automatically
writes them to all the members of the current on-line redo log group. If any one group fails
then database automatically switch over to next group. It degrades performance.

Qus. . What is advantage of having disk shadowing / mirroring?


Ans: Shadow set of disks save as a backup in the event of disk failure. In most operating
systems if any disk failure occurs it automatically switchover to place of failed disk.
Improved performance because most OS support volume shadowing can direct file I/O
request to use the shadow set of files instead of the main set of files. This reduces I/O load
on the main set of disks.

Qus. . What is use of rollback segments in Oracle database?


Ans: They allow the database to maintain read consistency between multiple transactions.

Qus. . What is a rollback segment entry?


Ans: It is the set of before image data blocks that contain rows that are modified by a
transaction.
Each rollback segment entry must be completed within one rollback segment.
A single rollback segment can have multiple rollback segment entries.

Qus. . What is hit ratio?


Ans: It is a measure of well the data cache buffer is handling requests for data.
Hit Ratio = (Logical Reads - Physical Reads - Hits Misses)/ Logical Reads.

Qus. . When will be a segment released?


Ans: When Segment is dropped.
When Shrink (RBS only)
When truncated (TRUNCATE used with drop storage option)

Qus. . What are disadvantages of having raw devices?


Ans: We should depend on export/import utility for backup/recovery (fully reliable)
The tar command cannot be used for physical file backup, instead we can use dd command,
which is less flexible and has limited recoveries.

Qus. . List the factors that can affect the accuracy of the estimations?
Ans: - The space used transaction entries and deleted records, does not become free
immediately after completion due to delayed cleanout.
- Trailing nulls and length bytes are not stored.
- Inserts of, updates to and deletes of rows as well as columns larger than a single data
block, can cause fragmentation a chained row pieces.

Database Security & Administration

Qus. . What is user Account in Oracle database?


Ans: A user account is not a physical structure in database but it is having important
relationship to the objects in the database and will be having certain privileges.

Qus. . How will you enforce security using stored procedures?


Ans: Don't grant user access directly to tables within the application.
Instead grant the ability to access the procedures that access the tables.
When procedure executed it will execute the privilege of procedures owner. Users cannot
access tables except via the procedure.

Qus. . What are the dictionary tables used to monitor a database space?
Ans: DBA_FREE_SPACE
DBA_SEGMENTS
DBA_DATA_FILES.

SQL*Plus Statements

Qus. 0. What are the types of SQL statement?


Ans: Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT &
COMMIT.
Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN &
SELECT.
Transactional Control: COMMIT & ROLLBACK
Session Control: ALTERSESSION & SET ROLE
System Control: ALTER SYSTEM.

Qus. 1. What is a transaction?


Ans: Transaction is logical unit between two commits and commit and rollback.

Qus. 2. What is difference between TRUNCATE & DELETE?


Ans: TRUNCATE commits after deleting entire table i.e., cannot be rolled back.
Database triggers do not fire on TRUNCATE
DELETE allows the filtered deletion. Deleted records can be rolled back or committed.
Database triggers fire on DELETE.

Qus. 3. What is a join? Explain the different types of joins?


Ans: Join is a query, which retrieves related columns or rows from multiple tables.
Self Join - Joining the table with itself.
Equi Join - Joining two tables by equating two common columns.
Non-Equi Join - Joining two tables by equating two common columns.
Outer Join - Joining two tables in such a way that query can also retrieve rows that do not
have corresponding join value in the other table.

Qus. 4. What is the sub-query?


Ans: Sub-query is a query whose return values are used in filtering conditions of the main
query.

Qus. 5. What is correlated sub-query?


Ans: Correlated sub-query is a sub-query, which has reference to the main query.

Qus. 6. Explain CONNECT BY PRIOR?


Ans: Retrieves rows in hierarchical order eg.
select empno, ename from emp where.

Qus. 7. Difference between SUBSTR and INSTR?


Ans: INSTR (String1, String2 (n, (m)),
INSTR returns the position of the m-th occurrence of the string 2 in string1. The search
begins from nth position of string1.
SUBSTR (String1 n, m)
SUBSTR returns a character string of size m in string1, starting from n-th position of
string1.

Qus. 8. Explain UNION, MINUS, UNION ALL and INTERSECT?


Ans: INTERSECT - returns all distinct rows selected by both queries.
MINUS - returns all distinct rows selected by the first query but not by the second.
UNION - returns all distinct rows selected by either query
UNION ALL - returns all rows selected by either query, including all duplicates.

Qus. 9. What is ROWID?


Ans: ROWID is a pseudo column attached to each row of a table. It is 18 characters long,
blockno, rownumber are the components of ROWID.

Qus. 0. What is the fastest way of accessing a row in a table?


Ans: Using ROWID.
CONSTRAINTS

Qus. 1. What is an integrity constraint?


Ans: Integrity constraint is a rule that restricts values to a column in a table.

Qus. 2. What is referential integrity constraint?


Ans: Maintaining data integrity through a set of rules that restrict the values of one or more
columns of the tables based on the values of primary key or unique key of the referenced
table.
Qus. 3. What is the usage of SAVEPOINTS?
Ans: SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling
back part of a transaction. Maximum of five save points are allowed.

Qus. 4. What is ON DELETE CASCADE?


Ans: When ON DELETE CASCADE is specified Oracle maintains referential integrity by
automatically removing dependent foreign key values if a referenced primary or unique key
value is removed.

Qus. 5. What are the data types allowed in a table?


Ans: CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

Qus. 6. What is difference between CHAR and VARCHAR2? What is the maximum SIZE
allowed for each type?
Ans: CHAR pads blank spaces to the maximum length.
VARCHAR2 does not pad blank spaces.
For CHAR the maximum length is 255 and 2000 for VARCHAR2.

Qus. 7. How many LONG columns are allowed in a table? Is it possible to use LONG
columns in WHERE clause or ORDER BY?
Ans: Only one LONG column is allowed. It is not possible to use LONG column in WHERE or
ORDER BY clause.

Qus. 8. What are the pre-requisites to modify datatype of a column and to add a column
with NOT NULL constraint?
Ans: - To modify the datatype of a column the column must be empty.
- To add a column with NOT NULL constrain, the table must be empty.

Qus. 9. Where the integrity constraints are stored in data dictionary?


Ans: The integrity constraints are stored in USER_CONSTRAINTS.

Qus. 0. How will you activate/deactivate integrity constraints?


Ans: The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE
CONSTRAINT / DISABLE CONSTRAINT.

Qus. 1. If unique key constraint on DATE column is created, will it validate the rows that
are inserted with SYSDATE?
Ans: It won't, Because SYSDATE format contains time attached with it.

Qus. 2. What is a database link?


Ans: Database link is a named path through which a remote database can be accessed.

Qus. 3. How to access the current value and next value from a sequence? Is it possible to
access the current value in a session before accessing next value?
Ans: Sequence name CURRVAL, sequence name NEXTVAL. It is not possible. Only if you
access next value in the session, current value can be accessed.
Qus. 4. What is CYCLE/NO CYCLE in a Sequence?
Ans: CYCLE specifies that the sequence continue to generate values after reaching either
maximum or minimum value. After pan-ascending sequence reaches its maximum value, it
generates its minimum value. After a descending sequence reaches its minimum, it
generates its maximum.

NO CYCLE specifies that the sequence cannot generate more values after reaching its
maximum or minimum value.

Qus. 5. What are the advantages of VIEW?


Ans: - To protect some of the columns of a table from other users.
- To hide complexity of a query.
- To hide complexity of calculations.

Qus. 6. Can a view be updated/inserted/deleted? If Yes - under what conditions?


Ans: A View can be updated/deleted/inserted if it has only one base table if the view is
based on columns from one or more tables then insert, update and delete is not possible.

Qus. 7. If a view on a single base table is manipulated will the changes be reflected on the
base table?
Ans: If changes are made to the tables and these tables are the base tables of a view, then
the changes will be reference on the view.

Qus. 8. To see current user name ?


Ans: SQL> show user;

Qus. 9. Change SQL prompt name ?


Ans: SQL> set sqlprompt R4R >

Qus. 0. Switch to DOS prompt ?


Ans: SQL> host

Qus. 1. How do I eliminate the duplicate rows ?


Ans: SQL> delete from table_name where rowid not in (select max(rowid) from table group
by duplicate_values_field_name);
or
SQL> delete duplicate_values_field_name dv from table_name ta where rowid <(select
min(rowid) from table_name tb where ta.dv=tb.dv);
Example.
Table Emp
Empno Ename
101 Scott
102 Jiyo
103 Millor
104 Jiyo
105 Smith
delete ename from emp a where rowid < ( select min(rowid) from emp b where a.ename =
b.ename);
The output like,
Empno Ename
101 Scott
102 Millor
103 Jiyo
104 Smith

Qus. 2. How do I display row number with records?


Ams:To achive this use rownum pseudocolumn with query, like
SQL> select rownum, ename from emp;
Output:
1 Scott
2 Millor
3 Jiyo
4 Smith

Qus. 3. Display the records between two range


Ans: select rownum, empno, ename from emp where rowid in
(select rowid from emp where rownum <=&upto
minus
select rowid from emp where rownum<&Start);
Enter value for upto: 10
Enter value for Start: 7
ROWNUM EMPNO ENAME
--------- --------- ----------
1 7782 CLARK
2 7788 SCOTT
3 7839 KING
4 7844 TURNER

Qus. 4. I know the nvl function only allows the same data type(ie. number or char or date
Nvl(comm, 0)), if commission is null then the text Not Applicable want to display, instead
of blank space. How do I write the query?
Ans: SQL> select nvl(to_char(comm.),'NA') from emp;
Output :
NVL(TO_CHAR(COMM),'NA')
-----------------------
NA
300
500
NA
1400
NA
NA

Qus. 5. Oracle cursor ?


Ans: Implicit & Explicit cursors
Oracle uses work areas called private SQL areas to create SQL statements.
PL/SQL construct to identify each and every work are used, is called as Cursor.
For SQL queries returning a single row, PL/SQL declares all implicit cursors.
For queries that returning more than one row, the cursor needs to be explicitly declared.

Qus. 6. Explicit Cursor attributes ?


Ans: There are four cursor attributes used in Oracle
cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name
%ISOPEN

Qus. 7. Implicit Cursor attributes ?


Ans: Same as explicit cursor but prefixed by the word SQL
SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN
Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor
after executing SQL statements.
: 2. All are Boolean attributes.
11. Find out nth highest salary from emp table
SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal))
FROM EMP B WHERE a.sal<=b.sal);
Enter value for n: 2
SAL
---------
3700

Qus. 8. To view installed Oracle version information


Ans: SQL> select banner from v$version;

Qus. 9. Display the number value in Words


Ans: SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- -----------------------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like,
Rs. Three Thousand only.
SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- ------------------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.

Qus. 0. Display Odd/ Even number of records


Ans: Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
2
4
6
Qus. 1. Which date function returns number value?
Ans: months_between

Qus. 2. Any three PL/SQL Exceptions?


Ans: Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others

Qus. 3. What are PL/SQL Cursor Exceptions?


Ans: Cursor_Already_Open, Invalid_Cursor

Qus. 4. Other way to replace query result null value with a text
Ans: SQL> Set NULL N/A
to reset SQL> Set NULL

Qus. 5. What are the more common pseudo-columns?


Ans: SYSDATE, USER , UID, CURVAL, NEXTVAL, ROWID, ROWNUM

Qus. 6. What is the output of SIGN function?


Ans: 1 for positive value,
0 for Zero,
-1 for Negative value.

Qus. 7. What is the maximum number of triggers, can apply to a single table?
Ans: 12 triggers.

Database management interview questions Database

Qus. 8. What is a Cartesian product? What causes it?


Ans: A Cartesian product is the result of an unrestricted join of two or more tables. The
result set of a three table Cartesian product will have x * y * z number of rows where x, y, z
correspond to the number of rows in each table involved in the join. It is causes by
specifying a table in the FROM clause without joining it to another table.

Qus. 9. What is an advantage to using a stored procedure as opposed to passing an SQL


query from an application?
Ans: A stored procedure is pre-loaded in memory for faster execution. It allows the DBMS
control of permissions for security purposes. It also eliminates the need to recompile
components when minor changes occur to the database.

Qus. 0. What is the difference of a LEFT JOIN and an INNER JOIN statement?
Ans: A LEFT JOIN will take ALL values from the first declared table and matching values
from the second declared table based on the column the join has been declared on. An
INNER JOIN will take only matching values from both tables

Qus. 1. When a query is sent to the database and an index is not being used, what type of
execution is taking place?
Ans: A table scans.

Qus. 2. What are the pros and cons of using triggers?


Ans: A trigger is one or more statements of SQL that are being executed in event of data
modification in a table to which the trigger belongs.
Triggers enhance the security, efficiency, and standardization of databases.
Triggers can be beneficial when used:
to check or modify values before they are actually updated or inserted in the database.
This is useful if you need to transform data from the way the user sees it to some internal
database format.
to run other non-database operations coded in user-defined functions
to update data in other tables. This is useful for maintaining relationships between data or
in keeping audit trail information.
To check against other data in the table or in other tables. This is useful to ensure data
integrity when referential integrity constraints arent appropriate, or when table check
constraints limit checking to the current table only.

Vous aimerez peut-être aussi