Java database interview questions

Category: JAVA Questions    |    6 views    |    Add a Comment
  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. Is the JDBC-ODBC Bridge multi-threaded? - No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading.
  3. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? - No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
  4. What is cold backup, hot backup, warm backup recovery? - Cold backup (All these files must be backed up at the same time, before the databaseis restarted). Hot backup (official name is ‘online backup’) is a backup taken of each tablespace while the database is running and is being accessed by the users.
  5. When we will Denormalize data? - Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.
  6. What is the advantage of using PreparedStatement? - If we are using PreparedStatement the execution time will be less. The PreparedStatement object contains not just an SQL statement, but the SQL statement that has been precompiled. This means that when the PreparedStatement is executed,the RDBMS can just run the PreparedStatement’s Sql statement without having to compile it first.
  7. 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.
  8. 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
  9. 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.

    TRANSACTION_READ_UNCOMMITTED : DIRTY READS, NON-REPEATABLE

    READ AND PHANTOMS CAN OCCUR.

    TRANSACTION_READ_COMMITTED : DIRTY READS ARE PREVENTED, NON-

    REPEATABLE READ AND PHANTOMS CAN OCCUR.

    TRANSACTION_REPEATABLE_READ : DIRTY READS ,
    NON-REPEATABLE READ ARE PREVENTED AND PHANTOMS CAN OCCUR.

    TRANSACTION_SERIALIZABLE : DIRTY READS, NON-REPEATABLE READ

    AND PHANTOMS ARE PREVENTED.

  10. What is 2 phase commit? - A 2-phase commit is an algorithm used to ensure the integrity of a committing transaction. In Phase 1, the transaction coordinator contacts potential participants in the transaction. The participants all agree to make the results of the transaction permanent but do not do so immediately. The participants log information to disk to ensure they can complete In phase 2 f all the participants agree to commit, the coordinator logs that agreement and the outcome is decided. The recording of this agreement in the log ends in Phase 2, the coordinator informs each participant of the decision, and they permanently update their resources.
  11. 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
  12. What is the normal procedure followed by a java client to access the db.? - The database connection is created in 3 steps:
    1. Find a proper database URL
    2. Load the database driver
    3. Ask the Java DriverManager class to open a connection to your database

    In java code, the steps are realized in code as follows:

    1. Create a properly formatted JDBR URL for your database. (See FAQ on JDBC URL for more information). A JDBC URL has the form
      jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
    2. Class.forName(”my.database.driver”);
    3. Connection conn = DriverManager.getConnection(”a.JDBC.URL”,

      “databaseLogin”,”databasePassword”);

  13. What is a data source? - A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.
  14. What are collection pools? What are the advantages? - A connection pool is a cache of database connections that is maintained in memory, so that the connections may be reused
  15. How do you get Column names only for a table (SQL Server)? Write the Query. -
    	select name from syscolumns
     		where id=(select id from sysobjects where
    name='user_hdr')
    order by colid --user_hdr is the table name

Share/Save/Bookmark

 

Database management interview questions

Category: Database Questions    |    4 views    |    Add a Comment

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

2. What is an advantage to using a stored procedure as opposed to passing an SQL query from an application.

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

3. What is the difference of a LEFT JOIN and an INNER JOIN statement?

Expected answer:
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

4. When a query is sent to the database and an index is not being used, what type of execution is taking place?

Expected answer:
A table scan.

5. What are the pros and cons of using triggers?

Expected answer:
A trigger is one or more statements of SQL that are being executed in event of data modification in a table to which the trigger belongs.

Triggers enhance the security, efficiency, and standardization of databases.
Triggers can be beneficial when used:
– to check or modify values before they are actually updated or inserted in the database. This is useful if you need to transform data from the way the user sees it to some internal database format.
– to run other non-database operations coded in user-defined functions
– to update data in other tables. This is useful for maintaining relationships between data or in keeping audit trail information.
– to check against other data in the table or in other tables. This is useful to ensure data integrity when referential integrity constraints aren’t appropriate, or when table check constraints limit checking to the current table only.

6. What are the pros and cons of using stored procedures. When would you use them?

7. What are the pros and cons of using cursors? When would you use them?

Share/Save/Bookmark

 

PL/SQL interview qiuestions

Category: Database Questions    |    3 views    |    Add a Comment
  1. Which of the following statements is true about implicit cursors?
    1. Implicit cursors are used for SQL statements that are not named.
    2. Developers should use implicit cursors with great care.
    3. Implicit cursors are used in cursor for loops to handle data processing.
    4. Implicit cursors are no longer a feature in Oracle.

  2. Which of the following is not a feature of a cursor FOR loop?
    1. Record type declaration.
    2. Opening and parsing of SQL statements.
    3. Fetches records from cursor.
    4. Requires exit condition to be defined.
  3. A developer would like to use referential datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. How would the developer define this variable using referential datatypes?
    1. Use employee.lname%type.
    2. Use employee.lname%rowtype.
    3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
    4. Declare it to be type LONG.
  4. Which three of the following are implicit cursor attributes?
    1. %found
    2. %too_many_rows
    3. %notfound
    4. %rowcount
    5. %rowtype
  5. If left out, which of the following would cause an infinite loop to occur in a simple loop?
    1. LOOP
    2. END LOOP
    3. IF-THEN
    4. EXIT
  6. Which line in the following statement will produce an error?
    1. cursor action_cursor is
    2. select name, rate, action
    3. into action_record
    4. from action_table;
    5. There are no errors in this statement.
  7. The command used to open a CURSOR FOR loop is
    1. open
    2. fetch
    3. parse
    4. None, cursor for loops handle cursor opening implicitly.
  8. What happens when rows are found using a FETCH statement
    1. It causes the cursor to close
    2. It causes the cursor to open
    3. It loads the current row values into variables
    4. It creates the variables to hold the current row values
  9. Read the following code:
    CREATE OR REPLACE PROCEDURE find_cpt
    (v_movie_id {Argument Mode} NUMBER,
     v_cost_per_ticket {argument mode}
    NUMBER) IS BEGIN   IF v_cost_per_ticket
     > 8.5 THEN SELECT  cost_per_ticket INTO
             v_cost_per_ticket FROM
      gross_receipt WHERE   movie_id = v_movie_id;
      END IF; END;

    Which mode should be used for V_COST_PER_TICKET?

    1. IN
    2. OUT
    3. RETURN
    4. IN OUT
  10. Read the following code:
    CREATE OR REPLACE TRIGGER update_show_gross
          {trigger information}      BEGIN
     {additional code}      END;

    The trigger code should only execute when the column, COST_PER_TICKET, is
    greater than $3. Which trigger information will you add?

    1. WHEN (new.cost_per_ticket > 3.75)
    2. WHEN (:new.cost_per_ticket > 3.75
    3. WHERE (new.cost_per_ticket > 3.75)
    4. WHERE (:new.cost_per_ticket > 3.75)
  11. What is the maximum number of handlers processed before the PL/SQL block is exited when an exception occurs?
    1. Only one
    2. All that apply
    3. All referenced
    4. None
  12. For which trigger timing can you reference the NEW and OLD qualifiers?
    1. Statement and Row
    2. Statement only
    3. Row only
    4. Oracle Forms trigger
  13. Read the following code:
    CREATE OR REPLACE FUNCTION
    get_budget(v_studio_id IN NUMBER)
     RETURN number IS  v_yearly_budget NUMBER;
     BEGIN
      SELECT  yearly_budget
          INTO
         v_yearly_budget        FROM
           studio        WHERE   id = v_studio_id;
           RETURN v_yearly_budget; END;

    Which set of statements will successfully invoke this function within SQL*Plus?

    1. VARIABLE g_yearly_budget NUMBER
      EXECUTE g_yearly_budget := GET_BUDGET(11);
    2. VARIABLE g_yearly_budget NUMBER
      EXECUTE :g_yearly_budget := GET_BUDGET(11);
    3. VARIABLE :g_yearly_budget NUMBER
      EXECUTE :g_yearly_budget := GET_BUDGET(11);
    4. VARIABLE g_yearly_budget NUMBER
      :g_yearly_budget := GET_BUDGET(11);
  14. CREATE OR REPLACE PROCEDURE update_theater
    (v_name IN VARCHAR v_theater_id IN NUMBER) IS BEGIN
            UPDATE  theater        SET
                 name = v_name
            WHERE   id = v_theater_id; END update_theater;

    When invoking this procedure, you encounter the error:

    ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.

    How should you modify the function to handle this error?

    1. An user defined exception must be declared and associated with the error code and handled in the EXCEPTION section.
    2. Handle the error in EXCEPTION section by referencing the error code directly.
    3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.
    4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.
  15. Read the following code:
    CREATE OR REPLACE PROCEDURE calculate_budget IS v_budget
          studio.yearly_budget%TYPE; BEGIN
      v_budget := get_budget(11);        IF v_budget < 30000
    		THEN
         set_budget(11,30000000);
      END IF; END;

    You are about to add an argument to CALCULATE_BUDGET. What effect will this have?

    1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.
    2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution.
    3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
    4. All three procedures are marked invalid and must be recompiled.
  16. Which procedure can be used to create a customized error message?
    1. RAISE_ERROR
    2. SQLERRM
    3. RAISE_APPLICATION_ERROR
    4. RAISE_SERVER_ERROR
  17. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can you issue to enable this trigger?
    1. ALTER TRIGGER check_theater ENABLE;
    2. ENABLE TRIGGER check_theater;
    3. ALTER TABLE check_theater ENABLE check_theater;
    4. ENABLE check_theater;
  18. Examine this database trigger
    CREATE OR REPLACE TRIGGER prevent_gross_modification
     {additional trigger information} BEGIN
      IF TO_CHAR(sysdate, DY) = MON 	THEN
    RAISE_APPLICATION_ERROR(-20000,Gross receipts
    cannot be deleted on Monday);        END IF; END;

    This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the entire DELETE statement. What additional information must you add?

    1. BEFORE DELETE ON gross_receipt
    2. AFTER DELETE ON gross_receipt
    3. BEFORE (gross_receipt DELETE)
    4. FOR EACH ROW DELETED FROM gross_receipt
  19. Examine this function:
    CREATE OR REPLACE FUNCTION set_budget
    (v_studio_id IN NUMBER, v_new_budget
     IN NUMBER) IS BEGIN        UPDATE  studio
          SET             yearly_budget = v_new_budget
          WHERE   id = v_studio_id;         IF SQL%FOUND THEN
                 RETURN TRUEl;        ELSE
  20.   RETURN FALSE;        END IF;
      COMMIT; END;

    Which code must be added to successfully compile this function?

    1. Add RETURN right before the IS keyword.
    2. Add RETURN number right before the IS keyword.
    3. Add RETURN boolean right after the IS keyword.
    4. Add RETURN boolean right before the IS keyword.
  21. Under which circumstance must you recompile the package body after recompiling the package specification?
    1. Altering the argument list of one of the package constructs
    2. Any change made to one of the package constructs
    3. Any SQL statement change made to one of the package constructs
    4. Removing a local variable from the DECLARE section of one of the package constructs
  22. Procedure and Functions are explicitly executed. This is different from a database trigger. When is a database trigger executed?
    1. When the transaction is committed
    2. During the data manipulation statement
    3. When an Oracle supplied package references the trigger
    4. During a data manipulation statement and when the transaction is committed
  23. Which Oracle supplied package can you use to output values and messages from database triggers, stored procedures and functions within SQL*Plus?
    1. DBMS_DISPLAY
    2. DBMS_OUTPUT
    3. DBMS_LIST
    4. DBMS_DESCRIBE
  24. What occurs if a procedure or function terminates with failure without being handled?
    1. Any DML statements issued by the construct are still pending and can be committed or rolled back.
    2. Any DML statements issued by the construct are committed
    3. Unless a GOTO statement is used to continue processing within the BEGIN section, the construct terminates.
    4. The construct rolls back any DML statements issued and returns the unhandled exception to the calling environment.
  25. Examine this code
    BEGIN        theater_pck.v_total_seats_sold_overall :=
    theater_pck.get_total_for_year; END;

    For this code to be successful, what must be true?

    1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist only in the body of the THEATER_PCK package.
    2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package.
    3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the THEATER_PCK package.
    4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist in the specification of the THEATER_PCK package.
  26. A stored function must return a value based on conditions that are determined at runtime. Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when the function is executed. Which Oracle supplied package will enable this feature?
    1. DBMS_DDL
    2. DBMS_DML
    3. DBMS_SYN
    4. DBMS_SQL

Share/Save/Bookmark

 

Microsoft MSN interview questions

Category: Database Questions    |    5 views    |    Add a Comment

Aaron Boodman took up a job with Microsoft (MSN division) and told the story of his interview in his Weblog. Below is an excerpt of questions potential candidates might find interesting.

  1. Compare and contrast SQL Server with MySQL.
  2. Compare and contrast stored procedures and dynamic SQL.
  3. Describe a standard 3-tier architecture and the interfaces between each tier.
  4. Compare and contrast a rich client and browser-based web application
  5. Compare and contrast WS and remoting protocols.
  6. Design the data structures for the game battleship.
  7. Consider the Dead Sea Scrolls. Imagine that you have these torn up old shreds of paper with ancient words on them. You want to develop an application that will display one sheet at a time on the screen. When the user left-clicks a word, the page containing the previous occurence of that word is displayed and the word is highlighted. When the user right-clicks a word, the page containing the next occurence is displayed and the word is highlighted. When the user double-clicks a word, the definition is displayed. How would you design the application?
  8. Given an array of the counties in NY represented as arrays of line segments, find the collection of line segments which represent the outline of the state.
  9. Consider an SOA rich-client application used by several international vendors, where one vendor sees bandwidth usage
    far exceeding what would be expected based on their usage. What steps would you follow to debug the problem?
  10. Imagine a trainyard. The purpose of a trainyard is to reorder trains so that they are most efficiently grouped for outbound travel. The basic unit of a trainyard is a piece of track which looks like the figure below. The train operator can perform three operations: move a car from the source to the spur, from the source to the destination, or from the spur to the destination. So, for example, he could reverse a train by moving each car onto the spur and then moving each car onto the destination. Write a function which, given an array of integers representing the order of cars on the source, and another representing the order of cars desired on the destination, prints instructions telling the trainyard operator which operations to perform to reorder the train correctly.
  11. Implement a function which, given the integer value of the hours and minutes hands of a clock, returns the measure of the degrees between them.
  12. Find the lowest valued node in a Binary Search Tree (BST) greater than or equal to a a certain value.
  13. Verify that a given BST is valid.
  14. Given the following database table, which represents the history of user account statuses, give the query that returns the users which had a certain status on a certain day.
  15. Implement the datastructures for a Tree and a function to populate it based off a page of text.

Share/Save/Bookmark