Beruflich Dokumente
Kultur Dokumente
1. What is a database?
Organized collection of interrelated data and the data in the database is integrated, can be shared and can be
accessed concurrently.
10. What is data model? Name two widely used data models?
A data model is a conceptual tool to describe data, data relationships, data semantics and consistency
constraints. Two widely used data models are
1. Object based logical model (E-R model).
2. Record based logical model.
12. What is cardinality of a relationship? What are the different types of cardinality relationship?
Cardinality of a relationship defines the type of relationship between two participating entities. There are 4 types
of cardinality relationship. Those are
1. One to one relationship
2. One to many relationship
3. Many to one relationship
4. Many to many relationship
22. What are the difference between char and varchar2 data types?
Ex. A. Name varchar2 (20): B. Name char (20)
If you store string of length of 10 characters the varchar2 uses 10 character spaces and remaining memory is
given to the OS where as in case of char the remaining spaces will be wasted.
39. What are the different operators that can be used within where clause?
The operators used with where are
1. Comparison operators (=, <>, <, <=, >, >=)
2. Logical operators (and, or ,not)
3. Between, in, like
4. Is null, is not null
JOINS
VIEWS
69. Why do we use data control language statements? What are those?
DCL statements are used to control access to the data base and the data. It is used to enforce data security. The
DCL statements are Grant, revoke.
EMBEDDED SQL
TRANSACTIONS
82. What is a transaction processing system? What are the different transaction systems are there?
The transaction processing (TP) systems which mimic the real life system like salary processing, library, banking,
air line, defence missile systems are basically divided into three categories. Those are
1. Batch transaction Systems
2. Online transaction processing systems
3. Real time transaction processing systems
93. What are the different restrictions that we can put on the foreign key at the time of creation?
1. On delete restrict: do not allow delete the parent table data if it is referred in the child table.
2. On delete set null: on delete the parent table data, set null value in the child table wherever the deleted data
is referred.
3. On delete set default: set the null values to child rows on deletion of parent records.
4. On delete set cascade: delete all the child table record from the parent table on the deletion of parent record
in the parent table.
MISCELLANEOUS QUESTIONS:
6. What is an attribute?
It is a particular property, which describes the entity.
14. What are partial, alternate, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is
sometime called as Discriminator.
Alternate Key:
All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key:
If no obvious key either stands alone or compound is available, then the last resort is to simply create a key, by
assigning a unique number to each record or occurrence. Then this is known as developing an artificial key.
Compound Key:
If no single data element uniquely identifies occurrences within a construct, then combining multiple elements
to create a unique identifier for the construct is known as creating a compound key.
Natural Key:
When one of the data elements stored within a construct is utilized as the primary key, then it is called the
natural key.
15. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.
Types:
Ø Binary search style indexing
Ø B-Tree indexing
Ø Inverted list indexing
Ø Memory resident table
Ø Table indexing
22. Define SQL and state the differences between SQL and other conventional programming Languages
SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational
database structures. The primary difference between SQL and other conventional programming languages is that
SQL statements specify what data operations should be performed rather than how to perform them.
27. What are stored-procedures? And what are the advantages of using them.
Stored procedures are database objects that perform a user defined operation. A stored procedure can have a
set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the
client. Stored procedures are used to reduce network traffic.
31. What’s the difference between a primary key and a unique key?
Both primary key and unique 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.
32. 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.
33. 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.
35. What’s the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes
it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won’t log the deletion of each row, instead it
logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be
rolled back.
37. What are the steps you will take to improve performance of a poor performing query?
There could be a lot of reasons behind the poor performance of a query. But some general issues that you could
talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of
stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily
complicated joins, too much normalization, excess usage of cursors and temporary tables. Some of the
tools/ways that help you troubleshooting performance problems are:
SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET
STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in
Query Analyzer.
38. What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you
avoid cursors?
Cursors allow row-by-row processing of the result sets. Types of cursors: Static, Dynamic, Forward-only, Keyset-
driven. Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip;
where as a normal SELECT query makes only one roundtrip, however large the result set is. Cursors are also
costly because they require more resources and temporary storage (results in more IO operations). Further,
there are restrictions on the SELECT statements that can be used with some types of cursors. Most of the times,
set based operations can be used instead of cursors. Here is an example:
If you have to give a flat hike to your employees using the following criteria:
Salary between 30000 and 40000 — 5000 hike
Salary between 40000 and 55000 — 7000 hike
Salary between 55000 and 65000 — 9000 hike
In this situation many developers tend to use a cursor, determine each employee’s salary and update his salary
according to the above formula. But the same can be achieved by multiple update statements or can be
combined in a single UPDATE statement as shown below:
UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END
Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in
a particular row meets certain condition. You 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. For examples of using WHILE loop for row by
row processing, check out the ‘My code library’ section of my site or search for WHILE.
39. What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?
Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or
DELETE operation takes place on a table. In SQL Server 6.5 you could define only 3 triggers per table, one for
INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you
could create multiple triggers per each action. But in 7.0 there’s no way to control the order in which the triggers
fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder
Triggers can’t be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE,
DELETE) happens on the table on which they are defined. Triggers are generally used to implement business
rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use
constraints for this purpose, instead of triggers, as constraints are much faster. Till SQL Server 7.0, triggers fire
only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server
2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers. Also check
out books online for ‘inserted table’, ‘deleted table’ and COLUMNS_UPDATED () There is a trigger defined for
INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and
pass the newly inserted rows to it for some custom processing. What do you think of this implementation? Can
this be implemented better? Instantiating COM objects is a time consuming process and since you
are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails
from triggers. This scenario can be better implemented by logging all the necessary data into a separate table,
and have a job which periodically checks this table and does the needful.
42. Is it possible to have primary key and foreign key in one table if yes so what is the use of foreign key?
Yes, we can have.
Foreign key is used to make relationship with another table. We can think foreign key as a copy of primary key
from another relational table.
43. What is the difference between Primary Key and Aggregate Key What is the difference between varchar
and varchar2?
Primary Key is a much similar to unique key. Only difference is that unique key can be null but primary key
cannot be null. Primary key is used to avoid duplication of data. A primary key consists of more than one column.
Also known as a concatenated key or Aggregate Key. it is also called as composite key.
Example for varchar & varchar2()
Emp_name varchar(10) - if you enter value less than 10 then remaining space cannot be deleted. it used total 10
spaces.
Emp_name varchar2(10) – if you enter value less than 10 then remaining space is automatically deleted.
SAMPLE QUERIES:
1.DDL STATEMENTS.
2. DML STATEMENTS:
4. where clause:
There are many operators used in where clause to specify the condition.
Consider this SQL statement and corresponding where clause explanation follows.
Select * from emp where[*********]
1. comparator operators
Ex. where empno=1001;(= is comparison operator)( we can have <, >, <>,>=,<=)
2. Special operators.
These are used to retrieve data very fast. These are
1. in, not in 2. Between, not between
3. like, not like 4. Is null, is not null
Ex. 1. Where empno in (1001,1005,1111)
Above statement retrieves data from all the three records if three record found else retrieves from the records
found from the specified empno.s.’ not in’ is just opposite of this
We can use ‘in’ statement with numbers, dates and characters.
2. Where joining _date between 12-aug-07 and 31-dec-07;sss
where sal between 10000 and 20000;
In the above statements between is used with numbers and dates. Between takes both the extremes. And not
between is opposite to between.
3.where ename like ‘s%’;
Above statement retrieves all the names which start with ‘s’
Above statement retrieves patterns. Like has got Meta characters i.e. _ and %
_ represents single character
% represents 0 or more characters
and ‘like’ always deals with characters only.
4. where sal is null;
Above statement retrieves the records whose sal is a null value . Is null operator is used to compare null
values. We can’t compare a null value with another null value. Where as ‘is not null’ is 0pposite of ‘is null’ .
1. Arithmetic functions :
select ename ,abs(commission-sal) from emp;
select power (2,4), sin(10), ln (10),log (10,100),exp(2),sign(5),round (123.25.2),trunc(123.25.2),
mod (5,2) from dual;
In the above statement, many arithmetic functions have been used. These are already pre defined or built ins.
2. Character functions:
Select initcap(S), lower(S), upper(S), length(S), reverse(S) from dual;
In the above statement S stands for a string. Initcap function gives initials as the caps and remaining letters as
small letters
Ex. If input is yugander jetty and the output will be Yugander Jetty
And length function gives length of string.
Select ascii(c)(i.e. c is a character), chr(n), concat(s1,s2) from dual;s
The above statement ascii function gives the equivalent ascii value, chr fuction takes input as a number and gives
its equivalent ascii character and concat is fuction used to concat 2 strings
3. Date functions:
These are applicable to dates only.
Select sysdate from the dual;
Select add_months(d,+ or – n), months_between(d1,d2) from dual;
In the above statements sysdate is pseudo column it gives the today’s date. Add_months () is a function used to
add n months to the given date d. Months_between () gives no.of months between given dates
4. General functions:
Select least(100,10,7,99), greatest(100,10,7,99) from dual;
In above statement, least() gives least value in the given list and greatest() gives biggest of the list values.
Select vsize(ename) from dual;
Gives the memory occupied by that coloumn.
Select ename, job, deptno, decode( deptno, 10,sal*0.20,20, sal*0.35, 30, sal*0.40) bonus from emp;
Decode () in the above statement, for dept=10, 20, 30 calculates the bonus and generates a report on each
person with his name, job, deptno and bonus.
It is a very important function to check multiple conditions while manipulating and retrieving it is equivalent to if
statement in C
6. Group by clause:
it is used to group the rows based on specified column.
Select deptno,sum(sal) from emp group by deptno;
Above statements groups the rows based on deptno and gives the total sal dept. Wise
7. Having clause:
Select job, count(*), sum (sal), avg(sal) from emp where deptno=30 group by job,
having count(*) > 1 ;
This select statement gives the output as , first it takes deptno=30 and then groups according to job and checks
for count after the grouping is done.
Having clause is used to check on the grouped results.
8. Order by:
Select * from emp order by sal desc;
This statement gives sal in descending order. Default order is ascending for order by clause.
9. Joins:
1. Select empno, ename, sal, emp.deptno, dname, loc from emp, dept where emp.deptno=dept.deptno;
This is an inner join (equi join). Here deptno is present in both the tables. It is needed to mention table name in
front of column name. This retrieves the rows from the both table which ever satisfy the condition mentioned.
2. select fname, cname from faculty, course;
Here faculty, course are the two table with a single column and fname, cname are the columns. fname is in
faculty and cname is in course.
Above statement is a join called Cartesian join. It is used to retrieve data from more than one table without any
condition. It retrieves all the possible combinations of rows.
3. select empno,ename, sal, emp.deptno, dname ,loc from emp, dept where emp.deptno=dept.deptno(+);
This is called left outer join all the rows from the dept table and common rows from the emp table
In the above case If + is on the left side then it is called right outer join then common rows from the dept table
and all the rows from the emp table will be in output.
4.left+ right outer join will give you full outer join here ‘+’ will be union operator.
5. select worker .ename “subordinate” , manager.ename “superior” from emp worker,emp superior where
worker.mgr=superior.mgr;
Here emp table is joined to itself . it is acting once as worker table and once as superior
Set operators
Select job from emp where deptno=10
Intersect
Select job from emp where deptno=20;
This query gives the output as common job from10 and 20 dept.s from emp table.
Different set operators are union, union all, minus and intersect.
12. SUBQUERIS
1. Select * from emp where empno in(select distinct empno from incr);
Here first inner select will be executed and then based on that result, outer query is evaluated.
2. select * from emp where sal > any (select sal from emp where deptno=10);
Or
Select * from emp where sal>(select min(sal) from the emp);
It lists all the employees whose sal is more than lowest sal of deptno.
In above query replace ‘any’ with ‘all’ and in the next query min() with max() we will get max sal
15. CONSTRAINTS
1. Imposing all the key constraints (Column level) at the time of table creation.
Create table emp(empno number(4) primary key, ename varchar2(20) not null, sex char(1) check( sex in(‘m’,
‘n’)), job varchar2(20), hire_date default sysdate, e-mail unique, deptno references dept(deptno));
Here in above query the key constraints are are imposed at the time of creation. It is a good practice to give
name to the imposed constraints. So this example after naming the constraints.
2. Write a query to activate default constraint
Here consider that dept is table, at the time of creation of table we have provided loc as Hyderabad.
So the query as follows
Insert into dept values(30, ‘import’, default);
3. Write a query to explain referential integrity
On delete cascade clause:
Consider table emp the attributes are empno, ename, deptno and this deptno references to deptno of dept
table.
Take one more table called incr, the attributes are empno, amount . empno of incr references to empno of emp
table.
First if i want to delete emp table it won’t be deleted because child rows will be existing. The same thing
happens if dept table is deleted.
In order to avoid these things it is needed to include on delete cascade clause with reference key at the time of
creating a table.
Ex. Create table dept(deptno number(2), dname varchar(20));
Create table emp(empno number(4) primary key, ename varchar2(20), deptno number(2) references
dept(deptno) on delete cascade);
Create table incr(empno number(4) references emp( empno) on delete cascade, amount number(8,2));
If the table are defined as shown above, there won’t be problem if you delete a table which has got children. It
automatically removes all the child rows whenever parent record is removed.
Cascade constraints:
If this constraint is applied with reference key constraint, it automatically removes foreign key constraint when
parent table is dropped.
Child rows will not be removed
Table constraints
The constraints defined next to table definition are called table constraints.
Create table customer_details(
Cust_id_number(5) constraint Nnull Not Null,
Cust_name varchar2(20) constraint Nnull2 Not Null,
Account_num number(5),
Account_type varchar2(10) constraint Nnull3 Not Null,
Bank_branch varchar2(25) constraint Nnull4 Not Null,
Cust_email varchar2(30),
Constraint Pkey1 primary key(cust_id,account_num));