You are on page 1of 10

1. What are the types of SQL Statement?

Data Definition Language CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO


AUDIT & COMMIT
Data Manipulation INSERT, UPDATE, DELETE, LOCK TABLE,
Language EXPLAIN PLAN & SELECT
Transactional Control COMMIT & ROLLBACK
Session Control ALTERSESSION & SET ROLE
System Control ALTER SYSTEM
2. What is a transaction?
Transaction is logical unit between two commits and commit and rollback.

3. What is the difference between TRUNCATE table & DELETE table?

TRUNCATE TABLE DELETE TABLE


TRUNCATE TABLE also deletes all the DELETE TABLE is a logged operation,
rows in a table, but it won't log the so the deletion of each row gets
deletion of each row, instead it logs logged in the transaction log, which
the de-allocation of the data pages makes it slow.
of the table, which makes it faster.
Of course, TRUNCATE TABLE can be
rolled back.
TRUNCATE does not allow filtered DELETE allows the filtered deletion.
deletion. It commits after deleting Deleted records can be rolled back
the entire table i.e., can not be or committed. Database triggers fire
rolled back. Database triggers do on DELETE.
not fire on TRUNCATE.

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

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 in such a way that query can
also retrieve
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.

5. What is the Subquery?

Subquery is a query whose return values are used in filtering conditions of the
main query.
6. What is correlated sub-query?

Correlated subquery is a subquery which has reference to the main query. A


correlated subquery is a nested select that refers to a column from the outer
select. In some cases they can rank among the poorest performing SQL
statements imaginable because the inner result set must be constructed for every
single row that is a candidate for inclusion in the outer result set. If both the
inner and outer result sets are large the amount of processing required can be
huge.

7. Explain Connect by Prior?

Retrieving rows in hierarchical order.


Example: select empno, ename from emp;

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

Each SQL statement within the query for Intersect, Minus, Union, Union ALL must
have the same number of fields in the result sets with similar data types.

UNION The UNION query allows you to combine the


result sets of 2 or more "select" queries. It
removes duplicate rows between the various
"select" statements.
UNION ALL The UNION ALL query allows you to combine
the result sets of 2 or more "select" queries. It
returns all rows (even if the row exists in more
than one of the "select" statements).
INTERSECT The INTERSECT query allows you to return the
results of 2 or more "select" queries. However,
it only returns the rows selected by all queries.
If a record exists in one query and not in the
other, it will be omitted from the INTERSECT
results.
MINUS The MINUS query returns all rows in the first
query that are not returned in the second
query.

9. What is a database Link?

Database Link is a named path through which a remote database can be


accessed. An object stored in the local database that identifies a remote
database, a communication path to the remote database, and optionally, a
username and password for it. Once defined, a database link can be used to
perform queries on tables in the remote database
10. What are the advantages of VIEW?

1) To protect some of the columns of a table from other users.


2) To hide complexity of a query.
3) To hide complexity of calculations.

11. Can a view be updated/inserted/deleted? If Yes under what conditions?

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.

12. What are Triggers?

Triggers allow us to execute a batch of SQL code when an insert, update or delete
command is executed against a specific table. Triggers are "attached" to a single
table and allow us to setup our database in such a way that whenever a record is
added, updated, or deleted from a table, then SQL server will automatically
execute a batch of SQL code after that table modification takes place.

Syntax:

CREATE TRIGGER trigger_name


ON { table | view }
[ WITH ENCRYPTION ]
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ]
[ ...n ]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ ...n ]
}]
sql_statement [ ...n ]
}
}

FOR INSERT:
When SQL server processes this "INSERT" command, it creates a new virtual
table, which contains all of the fields in the "INSERT" command. This table is
named "Inserted", and is passed to the actual trigger. The table is named
"Inserted" because it contains all of the newly added fields and values from our
"INSERT" command.

FOR DELETE:
If we created a trigger that was activated when we deleted a record from the
"authors table (using the "FOR DELETE" syntax), then the virtual table would
contain all of the fields and values from the deleted record(s), and would be
named "Deleted".

FOR UPDATE:
Likewise, if we created a trigger for when an authors details were updated (using
the "FOR UPDATE" syntax), then both the "Inserted" and "Deleted" virtual tables
would be created and available from within the trigger. The "Deleted" table would
contain all of the fields and values for the row(s) before they were updated, and
the "Inserted" table would contain the new row(s) with the updated fields and
values.

When dealing with triggers, you must understand how they actually operate on
the data contained within their virtual tables. Let’s say that we run an "UPDATE"
command on the "authors" table, which has a trigger attached to it. The
"UPDATE" command might affect more than one row. When this is the case, the
"UPDATE" trigger is called for each row that was affected by the update
command. So, at any one time, each trigger only deals with one row.

13. Instead of Triggers:

In previous versions of SQL Server, triggers were sections of code that were
attached to tables and executed automatically after pre-defined updates took
place on a specified table. These of course still exist in SQL Server 2000. Instead
of triggers are attached to a table in a similar way, but the code inside them is
executed in place of the original updating statement.

Take this simple example:

create table test1 (descr varchar(32))


go
insert test1
select 'Quick demo of' union
select 'instead of triggers' |
go
create trigger tr_test1_io on test1 instead of update as
BEGIN
select descr as 'Inserted Columns' from inserted
select descr as 'Deleted Columns' from deleted
select descr as 'Table test1' from test1
END -- trigger def
go
update test1 set descr = NULL
go
drop table test1

Note that the trigger still has access to the Inserted and Deleted tables, which
work in the same way as old-style triggers. What is different is the contents the
test1 table as displayed from within the trigger: For old-style triggers the
contents of the test1 table would more closely match the contents of the Inserted
table because the trigger fires after the update, but here the data selected from
test1 is unchanged because no update is actually taking place (remember--the
trigger happens instead of the update)
14. Multiple Triggers

You cannot create more than one "Instead Of" trigger on a table or view for each
operation (Insert, Update or Delete) but you can have "(instead Of" triggers
mixing with the old style of triggers. If you do, then the following rules apply.

1) The "Instead Of" triggers fire first

2) If there is no update to the original target table defined in the "Instead of"
trigger, subsequent triggers on that table will not fire

3) If the "Instead Of" trigger does update the original target table, then other
triggers defined on that table will fire as appropriate

4) If the "Instead Of" trigger converts the update operation type (for example
converting an Update into Delete and Insert operations) then the triggers that
relate to the operation defined inside the "Instead of" trigger will fire.

15. Can you use a commit statement within a database trigger?


Yes. I tried using commit and Rollback in Instead of Triggers and it worked fine.

16. What is a server Side SQL Cursor?

Cursor is a database object used by applications to manipulate data in a set on a


row-by-row basis, instead of the typical SQL commands that operate on all the
rows in the set at one time.

17. What is Normalization?

Normalization is the process of organizing the contents of a database. This


includes creating tables and establishing relationships between those tables
according to rules designed both to protect the data and to make the database
more flexible.

In relational database design, the process of organizing data to minimize


duplication is called Normalization. Normalization usually involves in dividing a
database into more tables and defining relationships between the tables. The
objective is to isolate the data, so that addition, deletion and modifications of a
field can be made in just one table and then propagate through the rest of the
database via the defined relationships.

18. Define First Normal Form:


A relationship is said to be in first normal form, if and only if all the cells in a
table contain atomic values.
19. Define second Normal Form:
A relation is said to be in second normal form (2NF) if and only if it is in 1NF and
every non-key attribute is fully dependent on the primary key.

20. Define Third Normal Form:


A relation R is in third normal form (3NF) if and only if it is in 2NF and every non-
key attribute is non-transitively dependent on the primary key. An attribute C is
transitively dependent on attribute A if there exists an attribute B such that: A 
B and B  C. Note that 3NF is concerned with transitive dependencies which do
not involve candidate keys. A 3NF relation with more than one candidate key will
clearly have transitive dependencies of the form:

primary_key  other_candidate_key  any_non-key_column.

21. Define Boyce-Codd Normal Form:


A relation R is in Boyce-Codd normal form (BCNF) if and only if every
determinant is a candidate key.

The definition of BCNF addresses certain (rather unlikely) situations which 3NF
does not handle. The characteristics of a relation which distinguish 3NF from
BCNF are given below. To be precise, the definition of 3NF does not deal with a
relation that:

1) has multiple candidate keys, where


2) those candidate keys are composite, and
3) the candidate keys overlap (i.e., have at least one common attribute)

22. What is denormalization and when would you go for it?


As the name indicates, denormalization is the reverse process of normalization.
It's the controlled introduction of redundancy in to the database design. It helps
improve the query performance as the number of joins could be reduced.

23. What are user defined data types and when you should go for them?
User defined data types let you extend the base SQL Server data types by
providing a descriptive name, and format to the database. Take for example, in
your database, there is a column called Flight_Num which appears in many
tables. In all these tables it should be varchar(8). In this case you could create a
user defined data type called Flight_num_type of varchar(8) and use it across all
your tables.

See sp_addtype, sp_droptype in books online.

24. What is bit data type and what's the information that can be stored
inside a bit column?
Bit data type is used to store Boolean information like 1 or 0 (true or false). Until
SQL Server 6.5 bit data type could hold either a 1 or 0 and there was no support
for NULL. But from SQL Server 7.0 onwards, bit data type can represent a third
state, which is NULL.
25. Define candidate key, alternate key, and composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a
candidate key becomes the primary key of the table. If the table has more than
one candidate key, one of them will become the primary key, and the rest are
called alternate keys.

A key formed by combining at least two or more columns is called composite key.

26. What are defaults? Is there a column to which a default can't be bound?
A default is a value that will be used by a column, if no value is supplied to that
column while inserting data. IDENTITY columns and timestamp columns can't
have defaults bound to them.

27. What is a transaction and what are ACID properties?


A transaction is a logical unit of work in which, all the steps must be performed or
none. ACID stands for Atomicity, Consistency, Isolation, and Durability. These are
the properties of a transaction.

28. Explain different isolation levels.


An isolation level determines the degree of isolation of data between concurrent
transactions. The default SQL Server isolation level is Read Committed.

Here are the other isolation levels (in the ascending order of isolation):

1) Read Uncommitted
2) Read Committed
3) Repeatable Read
4) Serializable

29. CREATE INDEX myIndex ON myTable(myColumn)


What type of Index will get created after executing the above
statement?

Non-clustered index. Important thing to note: By default a clustered index gets


created on the primary key, unless specified otherwise.

30. What's the maximum size of a row?


8060 bytes. Don't be surprised with questions like 'what is the maximum number
of columns per table'.

31. What are constraints? Explain different types of constraints.


Constraints enable the RDBMS enforce the integrity of the database
automatically, without needing you to create triggers, rule or defaults.
Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

32. What's the difference between a primary key and a unique key?
Both primary key and unique key enforce uniqueness of the column on which
they are defined. But by default primary key creates a clustered index on the
column, where are unique creates a non-clustered index by default. Another
major difference is that, primary key doesn't allow NULLs, but unique key allows
one NULL only.

33. What is a check constraint?


A check constraint allows you to specify a condition on each row in a table.

Note:

1) Check constraint can NOT be defined on a VIEW.

2) The check constraint defined on a table must refer to only columns in that
table. It can not refer to columns in other tables.

3) A check constraint can NOT include a SUBQUERY.

4) A check constraint can be defined in either a CREATE TABLE statement or an


ALTER TABLE statement.

The syntax for creating a check constraint using a CREATE TABLE statement is:

CREATE TABLE table_name


(column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]);

The DISABLE keyword is optional. If you create a check constraint using the
DISABLE keyword, the constraint will be created, but the condition will not be
enforced.

Example:
CREATE TABLE suppliers
(supplier_id numeric(4),
supplier_name varchar2(50),
CONSTRAINT check_supplier_id
CHECK (supplier_id BETWEEN 100 and 9999)
);

34. How do we Add, Drop, Enable and Disable a check Constraint?

ADD Check Constraint:


The syntax for creating a check constraint in an ALTER TABLE statement is:
ALTER TABLE table_name
add CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE];

The DISABLE keyword is optional. If you create a check constraint using the
DISABLE keyword, the constraint will be created, but the condition will not be
enforced.

DROP Check Constraint:


The syntax for dropping a check constraint is:

ALTER TABLE table_name


drop CONSTRAINT constraint_name;

ENABLE Check Constraint:


The syntax for enabling a check constraint is:

ALTER TABLE table_name


enable CONSTRAINT constraint_name;

DISABLE Check Constraint:


The syntax for disabling a check constraint is:

ALTER TABLE table_name


disable CONSTRAINT constraint_name;

Disadvantages of using stored procedures.


Here are some disadvantages of a stored procedure

1) Stored procedures split your code between the one program and process and
another program and process. Obviously, it is more convenient to have to program in
only one place. Program partitioning is an artifact of bandwidth limitations, not
something invented just to make programming easier.

2) Stored procedures have NO access to functions, variables and data in your


program unless somehow passed as parameters. Native functions generally cannot
be passed. (Remember the control tables? They often cannot be processed
remotely.)

3) Stored procedures are neither standardized nor likely to be in the same language
that you are using.

4) The advantages of runtime engine (.NET Framework) like automatic Garbage


collection, Exception handling, Object oriented programming etc cannot be used in a
stored procedure.

Ideally it would be easier to process the records locally to avoid separate


programming spaces. However, for speed purposes, it often makes sense to let the
database engine handle the record processing if possible.

You might also like