Académique Documents
Professionnel Documents
Culture Documents
SQL Tutorials
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:
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.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.
4.BCNF: 3NF inadequate in some situation then it was not satisfactory for the table:
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
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 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.
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
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.
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.
12. Nonsubversion rule: This rule state that different language bypass the integrity rule
and constraints.
MS SQL Server
You can use HTTP to send queries to the server. It provides various feature and facility to
accesses data on web.
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.
Data Sharing,
Data types
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.
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>);
4. TRUNCATE: Remove all records from a table, including all spaces allocated for the
records are removed
.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.
The above query retrieve the column data which you pass in the query from table which
you pass after From keyword.
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);
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.
If the WHERE clause is omitted, then every row of the table is deleted
4. SET TRANSACTION: Change transaction options like isolation level and what rollback
segment to use
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.
SELECT column_list
FROM table_name
WHERE condition_expression AND condition_expression
Return all rows specific to the conditions, when both conditions are true.
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.
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')
SELECT *
FROM publishers
WHERE state IN ('MA','DC')
SELECT *
FROM publishers
WHERE state NOT IN ('MA','DC')
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'
The range operator is used to retrieve data between range . The range operator are:
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
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
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
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
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
The TOP clause used with the SELECT statement. It is used to limits the number of rows
returned in the result set
For Example:
Returns all top 5 rows ,pub_id, pub_name and country, from the publishers table in
descending order with respect to pub_id.
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.
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.
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
Group clause summarize the result set in to a groups defined in the query using aggregate
function.
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:
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:
Return the 'type' and 'pub Id' and 'avg' , which calculated from titles table.
For Example:
Out Put
type avg
-----------------------------------------------
business 5000.0000
mod_cook NULL
popular_comp 7000.0000
psychology NULL
trad_cook NULL
UNDECIDED NULL
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:
Out Put
Some points regarding the use of the COMPUTE and COMPUTE BY
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.
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
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.
ROUND (numeric_expression,length)
Out Put:
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
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:
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.
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.
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:
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:
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
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
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
Natural Join
A join that restrict the redundant column from the result set is known as natural join
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:
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
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.
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
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
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.
condition is the conditions on which rows are to be included in the new table.
For Example:
(8 row(s) affected)
SELECT *
FROM aditya
SQL server provide a unique operator known as the UNION operator that is used to combine
the result set of two or more queries.
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:
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.
ON specifies the disk files used to store the data portion of the database.
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.
LOG ON specifies the disk files used to store the log files.
For Example:
Out Put:
.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
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'
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.
DATA INTEGRITY
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
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.
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.
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.
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.
TYPES OF 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.
For Example:
The above command creates a table employee with emp_name as the primary key. The
name of the constraints is pfemp_name.
Out Put
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.
For Example:
We create a UNIQUE constraints after the table has been created by altering the
table
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).
Syntax:
For Example:
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.
Syntax:
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.
The rules regarding the creation of the CHECK constraint are as follows:
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.
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
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
Types Of INDEXES
1. CLUSTERED Index
2. NONCLUSTERED Index
CLUSTERED INDEX
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 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.
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
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 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:
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.)
Syntax:
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.
table_name specifies the name of table and column_name is the name of columns on which
the index would be created.
Syntax:
sp_helpindex table_name
sp_helpindex employee
Out Put:
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.
The @ symbol before the variable name. This symbol is required and is used by the query
processor to identify variable.
For Exaple:
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
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
Printing Messages
PRINT statement display the user defined message or the content of a variable on the
screen
For Example:
Out Put:
Anil Yadav
For Example:
Out Put:
12348
Comment Entry
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.
IF...ELSE Statement
Syntax:
IF boolean_expression
{sql_statement}
ELSE boolean_expression
{sql_statement}
BEGIN...END Statement
Syntax:
BEGIN
{sql_statement}
END
Example:
Out Put:
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.
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.
Out Put:
The WHILE Statement
Syntax:
WHILE boolean_expression
{sql_statement}
[BREAK]
{sql_statement}
[CONTINUE]
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.
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."
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_
Guideline
Syntax
CREATE PROCEDURE proc_name
AS
BEGIN
sql-statement 1
sql-statement 1
END
For Example
Syntax
sp_helptext proc_name
sp_helptext empNameList
Out Put
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.
> Data blocks : are the smallest part of the oracle database defined by
DB_BLOCK_SIZE parameter.
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.
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
Page 1
Tot
Show al Post Your
Questions Last Post
Answers Pos Answers
ts
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. 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. Can objects of the same schema reside in different table spaces?
Ans: Yes.
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.
Memory Management
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.
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. .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. . 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. . 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 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. . 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.
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. 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. 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. 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. 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. 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. 4. Other way to replace query result null value with a text
Ans: SQL> Set NULL N/A
to reset SQL> Set NULL
Qus. 7. What is the maximum number of triggers, can apply to a single table?
Ans: 12 triggers.
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.