Database Drill

1.What is DDL and DML ?

DDL :-  Data defination Language

its having four commands

 Create , Alter , Drop , Truncate

DML :- Data manuplation language

 Insert , Update , Delete , select

2.How can you compare a part of the name rather than the entire name ?

SELECT * FROM people WHERE empname LIKE ‘%ab%’
Would return a recordset with records consisting empname the sequence ‘ab‘ in empname .

3.How could I get distinct entries from a table ?

The SELECT statement in conjunction with DISTINCT lets you select a set of distinct values from a table in a database. The values selected from the database table would of course depend on the various conditions that are specified in the SQL query. 

   SELECT DISTINCT empname FROM emptable

4.How to get the results of a Query sorted in any order ?

You can sort the results and return the sorted results to your program by using ORDER BY keyword thus saving you the pain of carrying out the sorting yourself. The ORDER BY keyword is used for sorting.

   SELECT empname, age, city FROM emptable ORDER BY empname

5.How can I find the total number of records in a table ?

   You could use the COUNT keyword , example
       SELECT COUNT(*) FROM emp WHERE age>40

6.What is GROUP BY ?

The GROUP BY keywords have been added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called. Without the GROUP BY functionality, finding the sum for each individual group of column values was not possible

7.What is the difference among “dropping a table”, “truncating a table” and “deleting all records” from a table ?

Dropping :  (Table structure  + Data are deleted), Invalidates the dependent objects ,Drops the indexes

Truncating:  (Data alone deleted), Performs an automatic commit, Faster than delete

Delete : (Data alone deleted), Doesn’t perform automatic commit

8.What are the Large object types suported by Oracle ?

Blob and Clob

9.Difference between a “where” clause and a “having” clause ?

Having clause is used only with group functions whereas Where is not used with.

10.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 nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

11.What are triggers? 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.

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.

12. What is a join and explain different types of joins ?

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of  Joins

INNER JOINS: It will pull all the rows from both tables where there is a match.

SELECT postid, posts.title, commentid, comments.title FROM posts INNER JOIN comments ON posts.postid = comments.postid

LEFT OUTER JOIN: It will pull all the rows from left side of a join regardless of whether there is a match on the right side of join. Anything missing on the right side will be replaced by NULL.

SELECT postid, posts.title, commentid, comments.title FROM posts LEFT OUTER JOIN comments ON posts.postid = comments.postid

RIGHT OUTER JOIN: It will pull all the rows from the right side of a join regardless of whether there is a match on the left side of join. Anything missing on the left side will be replaced by NULL.

SELECT postid, posts.title, commentid, comments.title FROM posts
RIGHT OUTER JOIN comments ON posts.postid = comments.postid

CROSS JOIN: It returns a row of each combination of rows between the two tables. If you had 5 rows in each table, you’ed end up with 25 rows in the result set.

SELECT Products.ProductName, Products.UnitPrice, Temporary.Amount FROM Products CROSS JOIN Temporary ORDER BY Products.ProductName, Temporary.Amount

13.What is a Self Join ?

Self join is just like any other join, except that two instances of the same table will be joined in the query.

SELECT DISTINCT c1.ContactName, c1.Address, c1.City, c1.Region
FROM Customers AS c1, Customers AS c2
WHERE c1.Region = c2.Region
AND c1.ContactName <> c2.ContactName
ORDER BY c1.Region, c1.ContactName;

14.What is Cursor  ?

It is private SQL area to execute the sql quries and store the information. There are two types of cursors implicit cursors and explicit cursors.

Implicit cursors are system defined and returns one row. Explicit cursors are user defined and returns multiple rows

15.How do you get Column names only for a table (SQL Server)  ?

select name from syscolumns
where id=(select id from sysobjects where name=’user_hdr’)
order by colid –user_hdr is the table name

16.How to find stored procedures  ?

select procedure_name from all_procedures

17.What are Extended stored procedures  ?

Extended stored procedures let you create your own external routines in a programming language such as C. Extended stored procedures are DLLs that an instance of Microsoft SQL Server can dynamically load and run. Extended stored procedures run directly in the address space of an instance of SQL Server and are programmed by using the SQL Server Extended Stored Procedure API.

18. Explain about Cursors ?

Cursors are database objects used to traverse the results of an SQL query. They point to a certain location within a recordset and allow the operator to move forward (and sometimes backward, depending upon the cursor type) through the results one record at a time. There are different types of  cursors: Static, Dynamic, Forward-only, Keyset-driven.

Cursors extend result processing by:

  • Allowing positioning at specific rows of the result set.
  • Retrieving one row or block of rows from the current position in the result set.
  • Supporting data modifications to the rows at the current position in the result set.
  • Supporting different levels of visibility to changes made by other users to the database data that is presented in the result set.
  • Providing Transact-SQL statements in scripts, stored procedures, and triggers access to the data in a result set.

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 rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Example:

CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;

CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;
end if;

close c1;

RETURN cnumber;

END;

19.Explain about Stored Procedures ?

A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server.For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.

No Param
CREATE OR REPLACE PROCEDURE myproc IS
BEGIN
INSERT INTO oracle_table VALUES(‘string 1’);
END;
IN Param
CREATE OR REPLACE PROCEDURE myprocin(x VARCHAR) IS
BEGIN
INSERT INTO oracle_table VALUES(x);
END;
OUT Param
CREATE OR REPLACE PROCEDURE myprocout(x OUT VARCHAR) IS
BEGIN
INSERT INTO oracle_table VALUES(‘string 2’);
x := ‘outvalue’; // Assign a value to x
END;
IN/OUT Param
CREATE OR REPLACE PROCEDURE myprocinout(x IN OUT VARCHAR) IS
BEGIN
INSERT INTO oracle_table VALUES(x); // Use x as IN parameter
x := ‘outvalue’; // Use x as OUT parameter
END;

20.Explain about Views ?

View is a virtual or logical table composed of the result set of a query. Unlike orginary tables in a relational database, a view is not part of the physical schema. It is a dynamic virtual table computed or collated from data in the database. Chainging the data in a table alters the data shown in the view.

Views can provide advantages over tables

  • They can subset the data contained in a table
  • They can join and simplify multiple tables into a single virtual table
  • Views can act as aggregated tables, where aggregated data (sum,average etc.) are calculated and presented as part of the data
  • Views can hide the complexity of data,
  • Views do not incur any extra storage overhead
  • Depending on the SQL engine used, views can provide extra security.
  • Limit the exposure to which a table or tables are exposed to outer world
  • Rows in a view are not sorted. So we cannot use ORDER BY clause in the view definition.

          CREATE VIEW V_Customer
          AS SELECT First_Name, Last_Name, Country
         FROM Customer

 

21.Stored Function Vs Stored Procedure

Function :

1. Should return atleast one output parameter.Can return more than one parameter using OUT argument.

2. Parsed and compiled at runtime.

3.Cannot affect the state of database.

4.Can be invoked from SQL statement e.g. SELECT.

5. Functions are mainly used to compute values.

Procedure:

1. Doesn’t need to return values, but can return value.

2.Stored as a pseudo-code in database i.e. compiled form.

3.Can affect the state of database using commit etc.

4.Cannnot be invoked from SQL statements e.g. SELECT.

5.Procedures are mainly used to process the tasks.

Java based DB Questions

1.How do you call a Stored Procedure from JDBC ? 

The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure.

	CallableStatement cs =
		con.prepareCall("{call SHOW_SUPPLIERS}");
	ResultSet rs = cs.executeQuery();

2.What is cold backup, hot backup ? 

Cold backup means all these files must be backed up at the same time, before the databaseis restarted. Hot backup or online backup is a backup taken of each tablespace while the database is running and is being accessed by the users.

3.What is a “dirty read” ? 

Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. While you can easily command a database to disallow dirty reads, this usually degrades the performance of your application due to the increased locking overhead. Disallowing dirty reads also leads to decreased system concurrency.

4.What is Metadata and why should I use it  

Metadata (’data about data’) is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns

5.Different types of Transaction Isolation Levels

The isolation level describes the degree to which the data being updated is visible to other transactions. This is important when two transactions are trying to read the same row of a table. Imagine two transactions: A and B. Here three types of inconsistencies can occur:

  • Dirty-read: A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong if A rolls back his changes and updates his own changes to the database.
  • Non-repeatable read: B performs a read, but A modifies or deletes that data later. If B reads the same row again, he will get different data.
  • Phantoms: A does a query on a set of rows to perform an operation. B modifies the table such that a query of A would have given a different result. The table may be inconsistent.

1.TRANSACTION_READ_UNCOMMITTED : Dirty-read, Non-repeatable read and Phantoms can occur

2.TRANSACTION_READ_COMMITTED : Dirty-reads are prevented. Non-repeatable read and Phantoms can occur.

3.TRANSACTION_REPEATABLE_READ : Dirty-reads and Non-repeatable read are prevented and Phantoms can occur.

4.TRANSACTION_SERIALIZABLE : Dirty-reads,Non-repeatable read and Phantoms are prevented.

6.How do you handle your own transaction ?

Connection Object has a method called setAutocommit(Boolean istrue)
Default is true. Set the Parameter to false , and begin your transaction

Advertisements