Can one use dynamic SQL statements from PL/SQL?
Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL and PL/SQL statements (statements created at runtime). Look at these examples. Note that the statements within quotes are NOT semicolon terminated: EXECUTE IMMEDIATE 'CREATE TABLE x (a NUMBER)'; Using bind variables... sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)'; EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location; Returning a cursor... sql_stmt := 'SELECT * FROM emp WHERE empno = :id'; EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id; One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements. Look at these examples: CREATE OR REPLACE PROCEDURE DYNSQL AS cur integer; rc integer; BEGIN cur := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE); rc := DBMS_SQL.EXECUTE(cur); DBMS_SQL.CLOSE_CURSOR(cur); END; / More complex DBMS_SQL example using bind variables: CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO %TYPE) AS v_cursor integer; v_dname char(20); v_rows integer; BEGIN v_cursor := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x', DBMS_SQL.V7); DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no); DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20); v_rows := DBMS_SQL.EXECUTE(v_cursor); loop if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then exit; end if; DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname); end loop; DBMS_SQL.CLOSE_CURSOR(v_cursor); EXCEPTION when others then DBMS_SQL.CLOSE_CURSOR(v_cursor); raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '|| sqlerrm); END; / What is the difference between %TYPE and %ROWTYPE? Both %TYPE and %ROWTYPE are used to define variables in PL/SQL as it is defined within the database. If the datatype or precision of a column changes, the program automically picks up the new definition from the database without having to make any code changes. The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs, and allows programs to adapt as the database changes to meet new business needs. %TYPE %TYPE is used to declare a field with the same type as that of a specified table's column. Example: DECLARE v_EmpName emp.ename%TYPE; BEGIN SELECT ename INTO v_EmpName FROM emp WHERE ROWNUM = 1; DBMS_OUTPUT.PUT_LINE('Name = ' || v_EmpName); END; / %ROWTYPE %ROWTYPE is used to declare a record with the same types as found in the specified database table, view or cursor. Examples: DECLARE v_emp emp%ROWTYPE; BEGIN v_emp.empno := 10; v_emp.ename := 'XXXXXXX'; END; / What is the result of comparing NULL with NULL?
PUT_LINE('Name = ' || v_EmpRecord. end.[/code] Workarounds: Use IS NULL or IS NOT NULL: declare a number := NULL. end. b number := NULL. else dbms_output.ename).put_line('Both values are NULL. NULL = NULL'). begin if a=b then dbms_output.put_line('Both values are NULL.'). b number := NULL. Any comparison to NULL is evaluated to NULL. 99999) = nvl(b. b number := NULL. end if. DECLARE v_EmpRecord emp%ROWTYPE. 99999) then dbms_output. nor it is not equal to NULL. NULL <> NULL'). end if. elsif a<>b then dbms_output. DBMS_OUTPUT. begin if nvl(a.put_line('True.put_line('Undefined NULL is neither = nor <> to NULL'). end. BEGIN SELECT * INTO v_EmpRecord FROM emp WHERE ROWNUM = 1. end if.'). Example: declare a number := NULL.put_line('False. Use the NVL() or NVL2() function.NULL is neither equal to NULL. Look at this code example to convince yourself: declare a number := NULL. The output would be: SQL> / Undefined NULL is neither = nor <> to NULL PL/SQL procedure successfully completed.
. begin if a IS NULL and b IS NULL then dbms_output.
END. A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the result of a CASCADE delete. the workaround is to enforce the referential integrity through triggers as well.NEXTVAL into :i from dual. Functions MUST return a value.PUT_LINE('Salary = ' || v_EmpRecord.update. (Of course.sal). you cannot call that function from a SQL query. However. Another way this error can occur is if the trigger has statements to change the primary. Etc. You can have DML (insert. procedures doesn't need to. NEW and OLD still can be accessed by the trigger). Oracle (for some silly reason) prohibits this: i := sq_sequence.
. There are several restrictions in Oracle regarding triggers: A row-level trigger cannot query or modify a mutating table. or insert statement. / How does one get the value of a sequence into a PL/SQL variable? As you might know. But. What is a mutating and constraining table? "Mutating" means "changing". it is considered "mutating" and raises an error since Oracle should not return data that has not yet reached its final state. delete. A mutating table is a table that is currently being modified by an update. if you have a function that is updating a table. you cannot call such a function in a SQL query. one cannot use sequences directly from PL/SQL. one can use embedded SQL statements to obtain sequence values: select sq_sequence.DBMS_OUTPUT. If you must have triggers on tables that have referential constraints. What is the difference between stored procedures and functions? Functions are normally used for computations where as procedures are normally used for executing business logic. When a trigger tries to reference a table that is in state of flux (being changed). foreign or unique key columns of the table off which it fires.NEXTVAL. For example. delete) statements in a function.
Difference between user defined function and stored procedure Advantages of User Defined Functions Before SQL 2000. Another disadvantage is that SQL functions that return non-deterministic values are not allowed to be called from inside User Defined Functions. Therefore.select myFunction(field) from sometable. Example while writing a stored procedure that uses table named tabl1 and tabl2 etc. Every time the function is called. Procedure can return multiple values (max 1024). One of the advantages of User Defined Functions over Stored Procedures. Stored procedure returns always integer value by default zero. A procedure may modify an object where a function can only return a value. They also can be used to create joins. Disadvantages of User Defined Functions User Defined Functions cannot be used to modify base table information. User Defined Functions are simpler to invoke than Stored Procedures from inside another SQL statement. GETDATE cannot be called from inside a UDF you create.but actually not exists in database is allowed only in during creation but runtime throws error Function wont support deferred name resolution. At that stage procedures executed faster than triggers as triggers had to be re-compiled every time before executed (unless cached). and DELETE cannot be used on base tables. a different value is returned. Where. were not available. will throw error. In more recent releases both triggers and procedures are compiled when created (stored p-code) and one can add as much code as one likes in either procedures or triggers. is the fact that a UDF can be used in a Select. where as function return type could be scalar or table or table values(SQL Server). GETDATE is an example of a non-deterministic function. UPDATE. Stored Procedure: supports deferred name resolution. When advantages or disadvantages of User Defined Functions are discussed.
.. or Case statement. User Defined Functions (UDFs). In addition. Stored procedure is precompiled execution plan where as functions are not. the comparison is usually to Stored Procedures. The DML statements INSERT. PS: In earlier releases of Oracle it was better to put as much code as possible in procedures rather than triggers. Function returns 1 value only. Stored Procedures were often used in their place.
. and @@PACK_SENT. NEWID.101) RETURN @MyOutput END To call our function. execute: SELECT dbo.Types of User Defined Functions There are three different types of User Defined Functions. The statement begins by supplying a function name and input parameter list. The next line defines the type of data the UDF will return. In this case.@InDateTime. DBO in this case. and return only the date portion. enter:
CREATE FUNCTION dbo. @@CONNCECTIONS. a date time value will be passed in. Scalar UDFs Our first User Defined Function will accept a date time. This function returns a table variable whose structure was created by hand. GETDATE can be used as the input parameter. In Line Table functions return a single table variable that was created by a select statement.@InDateTime.DateOnly(GETDATE()) Notice the User Defined Function must be prefaced with the owner name. From inside Query Analyzer. This function should be shortened to:
CREATE FUNCTION testDateOnly(@InDateTime datetime) RETURNS varchar(10) AS BEGIN RETURN CONVERT(varchar(10). Scalar functions return a single value. @@TIMETICKS. Each type refers to the data being returned by the function. In addition. Scalar functions return a value. The final UDF is a Multi-statement Table Function. It is useful when complex data manipulation inside the function is required.DateOnly(@InDateTime datetime) RETURNS varchar(10) AS BEGIN DECLARE @MyOutput varchar(10) SET @MyOutput = CONVERT(varchar(10). Between the BEGIN and END block is the statement code. similar to a Create Table statement. Other built in SQL functions that cannot be used inside a User Defined Function include: RAND. Declaring the output variable was for clarity only. but could not be used inside the function itself. Any built in function that is non-deterministic.
This next function looks all the employees in the pubs database that start with a letter that is passed in as a parameter. Like other programming languages. not to be confused with a temporary table.LookByFName(’A') All the rows having a first name starting with A were returned. but having the benefit of accepting input parameters. But rather than return a table from a simple select. enter: SELECT * FROM dbo. the purpose of a User Defined Function is to create a stand-alone code module to be reused over and over by the global application. and data in it will be manipulated prior to the return:
. Multi Statement UDFs Multi Statement User Defined Functions are very similar to Stored Procedures. In Query Analyzer. that UDFs cannot use non-deterministic built in functions. Remember also.Inline Table UDFs These User Defined Functions return a table variable that was created by a single select statement. There is no way to return multiple result sets. They are a special data type whose scope is limited to the process that declared it. There are a number of restrictions unique to functions though. 1) = @FirstLetter To use the new function. They both allow complex logic to take place inside the function. So GETDATE and RAND cannot be used. For a Multi Statement test. This new function will accept the same input parameter. enter and run:
USE pubs GO CREATE FUNCTION dbo. The return is a Table Variable. a User Defined Function cannot call a Stored Procedure from inside itself. RAISERROR and @@ERROR are invalid from inside User Defined Functions. Table variables are new in SQL 2000. Table variables are stated to have performance benefits over temporary tables. Error handling is restricted. None of my personal testing has found this result though.LookByFName(@FirstLetter char(1)) RETURNS TABLE AS RETURN SELECT * FROM employee WHERE LEFT(fname. The Multi Statement UDF will always return a table variable–and only one table variable. we will create a modified version of the LookByFName function. Almost like a simply constructed non-updatable view. a specific table will be created. In addition. They also cannot execute dynamic SQL.
UDFs will provide you with a programming plus.lname.multi_test(’A') f ON e. SELECT fname FROM dbo. The main requirement is that the function be self-contained. For example. we can manipulate data like a Stored Procedure.fname Conclusion User Defined Functions offer an excellent way to work with code snippets. 1) = @FirstLetter UPDATE @Result SET on_probation = ‘N’ UPDATE @Result SET on_probation = ‘Y’ WHERE hire_date < ‘01/01/1991′ END RETURN
To use the new function. hire_date) SELECT fname.multi_test(’A') With the new Multi Statement Function. only specific columns can be returned. but use it in statement areas like a View.multi_test(@FirstLetter char(1)) RETURNS @Result TABLE ( fname varchar(20). hire_date FROM employee WHERE LEFT(fname. hire_date datetime. execute: SELECT * FROM dbo.CREATE FUNCTION dbo. on_probation char(1) ) AS BEGIN INSERT INTO @Result (fname. but if it can be worked around.fname FROM employee e INNER JOIN dbo.
. f. Not being able to use non-deterministic built in functions is a problem.fname = f.multi_test(’A') The function can also be joined like a view: SELECT e.
37.What is normalization? Ans: Well a relational database is basically composed of tables that contain related data. Views also reduce the effort that is required for writing queries to access specific columns every time. So the Process of organizing this data into tables is actually referred to as normalization. 36. 41. sp_renamedb are a set of system defined stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. sp_who2.What are cursors?
.What is the basic difference between clustered and a non-clustered index? Ans: The difference is that. Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. 39. 40. an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.What is a view? Ans: If we have several tables in a db and we want to view only specific columns from specific tables we can go for views.What is a Stored Procedure? Ans: Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. 38.What are the types of indexes available with SQL Server? Ans: There are basically two types of indexes that we use with the SQL Server. We can also have user defined stored procedures which can be called in similar way What is a trigger? Ans: Triggers are basically used to implement business rules.Can you give an example of Stored Procedure? Ans: sp_helpdb . you actually run a set of statements.What is an Index? Ans: When queries are run against a db. 35. Its basically like a Macro so when you invoke the Stored procedure.SQL SERVER:34. Clustered and the Non-Clustered. Triggers is also similar to stored procedures.
SQL Server runs on which TCP/IP port? Ans: SQL Server runs on port 1433 but we can also change it for better security.Well sometimes sp_reanmedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases?
. DBCC CHECKFILEGROUP .Can we use Truncate command on a table which is referenced by FOREIGN KEY? Ans: No.To check that all pages in a db are correctly allocated. We use these commands to check the consistency of the databases. UPDATE_STATISTICS updates the indexes on these tables accordingly. DBCC SQLPERF .and DBCC CHECKALLOC .It gives report on current usage of transaction log in percentage. 48.both on client and the server. 45. validation task and status checks..e. 49.Checks all tables file group for any damage. 'newname' 50. i. If we do a large amount of deletions any modification or Bulk Copy into the tables. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values. 43. 44. We cannot use Truncate command on a table with Foreign Key because of referential integrity. maintenance.Ensures that tables in the db and the indexes are correctly linked.What is the use of DBCC commands? Ans: DBCC stands for database consistency checker. 42.Can you tell me the difference between DELETE & TRUNCATE commands? Ans: Delete command removes the rows from a table based on the condition that we provide with a WHERE clause.What command do we use to rename a db? Ans: sp_renamedb 'oldname' . Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.From where can you change the default port? Ans: From the Network Utility TCP/IP properties --> Port number. 46.Can you give me some DBCC command options?(Database consistency check) Ans: DBCC CHECKDB .Ans: Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table.When do we use the UPDATE_STATISTICS command? Ans: This command is basically used when we do a large processing of data. we need to basically update the indexes to take these changes into account. 47.
Is for linking and connecting to other SQL Servers 61. 51. Cross Join 55. DB Maintanance. 54. Backups DTC . Outer Join. 53. Ans: We can link any server provided we have the OLE-DB provider from Microsoft to allow a link..What are the OS services that the SQL Server installation adds? Ans: MS SQL SERVER SERVICE.Can you explain the types of Joins that we can have with Sql Server? Ans: There are three types of joins: Inner Join.case insensitive and Binary. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group. DTC (Distribution transac co-ordinator) 60. 52. 56. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. sp_addlinkedsrvlogin 59.What is a Linked Server? Ans: Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. 57. SQL AGENT SERVICE.What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? Ans: Having Clause is basically used only with the GROUP BY function in a query.Ans: In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode.is for running the databases SQL AGENT .When do you use SQL Profiler? Ans: SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running. Dictonary .What is a Join in SQL Server? Ans: Join actually puts data from two or more tables into a single result set.Which stored procedure will you be running to add a linked server? Ans: sp_addlinkedserver. 58.What do you mean by COLLATION? Ans: Collation is basically the sort order. failed jobs etc.. There are three types of sort order Dictionary case sensitive.Can you explain the role of each service? Ans: SQL SERVER .Can you link only other SQL Servers or any database servers such as Oracle etc.is for automation such as Jobs.How do you troubleshoot SQL Server if its running very slow?
64. Makepipe is run on Server and readpipe on client to check for any connection issues.What are the authentication modes in SQL Server? Ans: Windows mode and mixed mode (SQL & Windows).What is log shipping? Can we do logshipping with SQL Server 7.Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow? Ans: For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER –m which will basically bring it into the maintenance mode after which we can restore the master db. 67. We should have two SQL Server . use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Secondly. Third would be to run UPDATE_STATISTICS command to update the indexes 62. eg SELECT field1 from table1 X WHERE field2>(select avg(field2) from table1 Y where
.Enterprise Editions.0 Ans: Logshipping is a new feature of SQL Server 2000. In logshipping the transactional log file from one server is automatically updated into the backup database on the other server. How do you troubleshoot? Ans: First I will look to ensure that port settings are proper on server and client Network utility for connections. 66.Lets say due to N/W or Security issues client is not able to connect to server or vice versa. 63. ODBC is properly configured at client end for connection ------Makepipe & readpipe are utilities to check for connection. Now you have to rebuild the db so what kind of action do you take? Ans: (I am not sure. 65. the other server will have the same db and we can use this as the DR (disaster recovery) plan.
What is a CO-RELATED SUBQUERY A CO-RELATED SUBQUERY is one that has a correlation name as table or view designator in the FROM clause of the outer query and the same correlation name as a qualifier of a search condition in the WHERE clause of the subquery. From Enterprise Manager we can configure the logshipping.Let us say master db itself has no backup.but I think we have a command to do it).Ans: First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor. If one server fails.Where do you think the users names and passwords will be stored in sql server? Ans: They get stored in master db in the sysxlogins table.
What is a view A view is stored procedure based on one or more tables. The columns that compose PK are automatically define NOT NULL. Outer Join–Its a join condition used where One can query all the rows of one of the tables in the join condition even though they don’t satisfy the join condition.field1=X.) What are various joins used while writing SUBQUERIES Self join-Its a join foreign key of a table references the same table. Equi-join–Its a join condition that retrieves rows from one or more tables in which one or more columns in one table are equal to one or more columns in the second table.field1). whereas a column that compose a UNIQUE is not automatically defined to be
. What are various constraints used in SQL NULL NOT NULL CHECK DEFAULT What are different Oracle database objects TABLES VIEWS INDEXES SYNONYMS SEQUENCES TABLESPACES etc What is difference between Rename and Alias Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column which do not exist once the SQL statement is executed. What are various privileges that a user can grant to another user SELECT CONNECT RESOURCE What is difference between UNIQUE and PRIMARY KEY constraints A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys. its a virtual table. (The subquery in a correlated subquery is revaluated for every row of the table or view named in the outer query.
DCL. SQL*PLUS commands are used to format query result. How will you delete duplicating rows from a base table DELETE FROM table_name A WHERE rowid>(SELECT min(rowid) from table_name B where B. . by restricting access to a predetermined set of rows and columns of a table. . DROP old_table RENAME new_table TO old_table DELETE FROM table_name A WHERE rowid NOT IN (SELECT MAX(ROWID) FROM table_name GROUP BY column_name) What is difference between SUBSTR and INSTR SUBSTR returns a specified portion of a string eg SUBSTR(’BCDEF’. Can a primary key contain more than one columns Yes How you will avoid duplicating records in a query By using DISTINCT What is difference between SQL and SQL*PLUS SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool.Present the data in a different perspective from that of the base table.DDL). Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database.table_no). CREATE TABLE new_table AS SELECT DISTINCT * FROM old_table.Store complex queries. Edit SQL commands and PL/SQL.Simplify commands for the user. SQL is a language used to query the relational database(DML.Provide an additional level of table security.4) output BCDE INSTR provides character position in which a pattern is found in a string. Set options.Hide data complexity. What are the advantages of views? .table_no=A.'-’. . eg INSTR(’ABC-DC-F’. . Which datatype is used for storing graphics and images LONG RAW data type is used for storing BLOB’s (binary large objects).mandatory must also specify the column is NOT NULL.
.2) output 7 (2nd occurence of ‘-’ ) *******************************************************************
Can a view based on another view? Yes.
How are the index updates? Indexes are automatically maintained and used by Oracle. What is a synonym? A synonym is an alias for a table. A database users and allocated free database space in ORACLE data blocks. What are the Characteristics of Data Files ? A data file can be associated with only one database. What is a public synonym? Any database user can access a public synonym. What are synonyms used for? .ORA file and can’t be changed latter. . which can be created to increase the performance of data retrieval. Once created a data file can't change size. What are the types of synonyms? There are two types of synonyms private and public. Changes to table data are automatically incorporated into all relevant indexes. One or more data files form a logical unit of database storage called a tablespace.What is an Oracle sequence? A sequence generates a serial list of unique numbers for numerical columns of a database's tables.Simplify the SQL statements for database users. . Index can be created on one or more columns of a table. views or program units of a remote database. What is a private synonym? Only its owner can access a private synonym.Provide public access to an object . What is an Oracle index? An index is an optional structure associated with a table to have direct access to rows. What is a Tablespace? A database is divided into Logical Storage Unit called tablespace.Provide location transparency for tables. view. A tablespace is used to grouped related logical structures together What is Rollback Segment ? A Database contains one or more Rollback Segments to temporarily store "undo" information. sequence or program unit.Mask the real name and owner of an object.
. Block size is specified in INIT. How to define Data Block size ? A data block size is specified for each ORACLE database when the database is created.
CREATE DATABASE. parameter of the ALTER SESSION Command ? The Optimizer chooses Cost_based approach and optimizes with the goal of best throughput if statistics for atleast one of the tables accessed by the SQL statement exist in the data dictionary. Database Name Names and locations of a database's files and redolog files. or be multiples of your operating system block size. is falling out of fashion. What is difference between UNIQUE constraint and PRIMARY KEY constraint ? A column defined as UNIQUE can contain Nulls while a column defined as PRIMARY KEY can't contain Nulls. How does one create a new database? (for DBA) One can create and modify Oracle databases using the Oracle "dbca" (Database Configuration Assistant) utility. The Oracle Universal Installer (oui) normally starts it after installing the database server software. however. Time stamp of database creation. Otherwise the OPTIMIZER chooses RULE_based approach. It contains the following information. Your choice should depend on the type of application you are
. ALTER SYSTEM SET DB_CREATE_ONLINE_LOG_DEST_1='/u02/oradata/'. One can use smaller block sizes.What does a Control file Contain ? A Control file records the physical structure of the database. What is the effect of setting the value "ALL_ROWS" for OPTIMIZER_GOAL parameter of the ALTER SESSION command ? What are the factors that affect OPTIMIZER in choosing an Optimization approach ? Answer The OPTIMIZER_MODE initialization parameter Statistics in the Data Dictionary the OPTIMIZER_GOAL parameter of the ALTER SESSION command hints in the statement. What database block size should I use? (for DBA) Oracle recommends that your database block size match. but the performance cost is significant. The dbca utility is located in the $ORACLE_HOME/bin directory. What is Index Cluster ? A Cluster with an index on the Cluster Key When does a Transaction end ? When it is committed or Rollbacked. ALTER SYSTEM SET DB_CREATE_ONLINE_LOG_DEST_2='/u03/oradata/'. What is the effect of setting the value "CHOOSE" for OPTIMIZER_GOAL. as it is quite involved and error prone. This option. One can also create databases manually using scripts. Look at this example for creating and Oracle 9i database: CONNECT SYS AS SYSDBA ALTER SYSTEM SET DB_CREATE_FILE_DEST='/u01/oradata/'.
Bizarre values for PCTINCREASE will contribute to fragmentation. What does ROLLBACK do ? ROLLBACK retracts any of the changes resulting from the SQL statements in the transaction.TS$.3 one can manually coalesce a tablespace using the ALTER TABLESPACE . unless they run into thousands and thousands where additional I/O may be required to fetch the additional blocks where extent maps of the segment are stored. Such extents of bizarre size are rarely re-used in their entirety. COALESCE. consider your "operating system block size" to be 8K. If you have many small transactions as with OLTP.. only for a short period of time..
. Note that the number of extents per segment does not cause any performance issue anymore. NAME FROM SYS. Locally Managed tablespaces (available from 8i onwards) with uniform extent sizes virtually eliminates any tablespace fragmentation. as with a DSS application. With fewer but larger transactions. use a larger block size. 101K. 102K. until then use: SQL> alter session set events 'immediate trace name coalesce level n'. SMON will not coalesce free space if a tablespace's default storage parameter "pctincrease" is set to 0. Where can one find the high water mark for a table? (for DBA) There is no single system table. A table's HWM can be calculated using the results from the following SQL statements: SELECT BLOCKS FROM DBA_SEGMENTS WHERE OWNER=UPPER(owner) AND SEGMENT_NAME = UPPER(table). contiguous extents every 2 hours and even then. Use the same extent size for all the segments in a given tablespace.g. 100K.DBA_FREE_SPACE_COALESCED dictionary view. E. How does one prevent tablespace fragmentation? (for DBA) Always set PCTINCREASE to 0 or 100. command. 100K. 400K.table ESTIMATE STATISTICS. use a smaller block size. etc.running. 200K. PCTINCREASE of 0 or 100 gives you nice round extent sizes that can easily be reused. 100K. ANALYZE TABLE owner. This is because volume manager products use 8K blocks (and this is not configurable).. etc. which contains the high water mark (HWM) for a table. Where 'n' is the tablespace number you get from SELECT TS#. How does one coalesce free space ? (for DBA) SMON coalesces free space (extents) into larger. You can get status information about this process by selecting from the SYS. With Oracle 7. For example if you set PCTINCREASE to 1 you will see that your extents are going to have weird and wacky sizes: 100K. SELECT EMPTY_BLOCKS FROM DBA_TABLES WHERE OWNER=UPPER(owner) AND SEGMENT_NAME = UPPER(table). If you are using a volume manager. What are the different approaches used by Optimizer in choosing an execution plan ? Rule-based and Cost-based.
Thus. Clearly Oracle doesn't always round extents to a multiple of 5 blocks. Oracle will round it up to 10 blocks. the tables' HWM = (query result 1) . Oracle doesn't round it up to the multiple of 5 when a tablespace is locally managed. ename from emp where rowid in (select rowid from emp where rownum <=&upto minus select rowid from emp where rownum< &Start). this is listed as Enhancement Request 158508. Space allocation also depends upon the size of contiguous free space available. If one asks for 8 blocks. Oracle would also give it to you. If one requests 16K or 2 blocks (assuming a 8K block size). If one asks for 8 blocks and Oracle finds a contiguous free space that is exactly 8 blocks. then Oracle allocates 64K or 8 blocks assuming 8K-block size. empno. If it were 9 blocks. Enter value for upto: 10 Enter value for Start: 7 ROWNUM EMPNO ENAME ——— ——— ———1 7782 CLARK 2 7788 SCOTT
. How are extents allocated to a segment? (for DBA) Oracle8 and above rounds off extents to a multiple of 5 blocks when more than 5 blocks are requested.(query result 2) . The exception to this rule is locally managed tablespaces. The changes made by the SQL statements of a transaction become visible to other user sessions transactions that start only after transaction is committed.1. What does COMMIT do ? COMMIT makes permanent the changes resulting from all SQL statements in the transaction. Oracle doesn't round it up to 5 blocks. What is COST-based approach to optimization ? Considering available access paths and determining the most efficient execution plan based on statistics in the data dictionary for the tables accessed by the statement and their associated clusters and indexes. If a tablespace is created with local extent management and the extent size is 64K. it would give it you. but it allocates 2 blocks or 16K as requested. Workaround: Do a user-level export of user A create new user B Import system/manager fromuser=A touser=B Drop user A *********************************************************
Display the records between two range select rownum. Can one rename a database user (schema)? (for DBA) No.1 NOTE: You can also use the DBMS_SPACE package and calculate the HWM = TOTAL_BLOCKS .UNUSED_BLOCKS .
sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b. cursor_name%NOTFOUND. For SQL queries returning a single row. Here SQL%ISOPEN is false. if commission is null then the text “Not Applicable” want to display.sal<=b. instead of blank space. because oracle automatically closed the implicit cursor after executing SQL statements.’NA’) from emp.3 7839 KING 4 7844 TURNER I know the nvl function only allows the same data type(ie. cursor_name%ROWCOUNT. All are Boolean attributes. number or char or date Nvl(comm.sal)) FROM EMP B WHERE a.sal). SQL%ROWCOUNT. SQL%ISOPEN Tips : 1. How do I write the query? SQL> select nvl(to_char(comm. Output : NVL(TO_CHAR(COMM). cursor_name%ISOPEN Implicit Cursor attributes Same as explicit cursor but prefixed by the word SQL SQL%Found. For queries that returning more than one row. PL/SQL declares all implicit cursors.’NA’) ———————– NA 300 500 NA 1400 NA NA Oracle cursor : Implicit & Explicit cursors Oracle uses work areas called private SQL areas to create SQL statements. Explicit Cursor attributes There are four cursor attributes used in Oracle cursor_name%Found. Find out nth highest salary from emp table SELECT DISTINCT (a. is called as Cursor. SQL%NOTFOUND.). 0)). PL/SQL construct to identify each and every work are used. : 2. Enter value for n: 2 SAL
. the cursor needs to be explicitly declared.
What is the use of ANALYZing the tables? 17. 31. When do you get contraint violtaion? What are the types of constraints? 21. What is a "transaction"? Why are they necessary? 19.? 37. Difference . What cursor type do you use to retrieve multiple recordsets? 4. What is the diference between "NULL in C" and "NULL in Oracle?" 11. 20. How will you copy the structure of a table without copying the data? 7. What are the Large object types suported by Oracle? 29.
.Primary Key and Aggregate Key 23. Tadeoffs with having indexes 9. Diffrence between a "where" clause and a "having" clause 5. What is the difference among "dropping a table". How to convert RAW datatype into TEXT? 22. What is Pro*C? What is OCI? 12. What is the difference between "procedure" and "function"? 6. seelct 2 from the emp. 33. Explain Normalizationa dn Denormalization with examples.? 36. What is a "trigger"? 25. Select even number in the the emp table. What is DYNAMIC SQL method 4? 15. What is a VIEW? How to get script for a view? 28. How to create a database link ? 34. What are the different types of joins? 2. Why can a "group by" or "order by" clause be expensive to process? 26. "truncating a table" and "deleting all records" from a table. What was the o/p for the following query 38. Difference between "ORACLE" and "MICROSOFT ACCESS" databases. What are "HINTS"? What is "index covering" of a query? 27. 13. What is SQL*Loader? 30. Select the row between Third & 10th row. What is the difference between "translate" and "replace"? 14. How functional dependency is related to database table design? 24. Explain normalization with examples. 32. How to remove duplicate records from a table? 16.*********************************************************************** *
1. Give some examples of Analytical functions. 3. Select the second row in the table 35. Difference between "VARCHAR" and "VARCHAR2" datatypes. How to find out the database name from SQL*PLUS command prompt? 8. How to run SQL script from a Unix Shell? 18. Talk about "Exception Handling" in PL/SQL? 10.
Difference .PL/SQL interview questions.What are the different types of replication? How are they used? 87.What is one of the first things you would do to increase performance of a query? Example “ a query ran yesterday took 30 seconds. How do we find row chaining? 5.What is referential integrity? What are the advantages of it? 77. Why EXISTS is preferable to distinct 18.
70. NVL. Order by clause 12. What is TEMP table space in Oracle.. Pattern matching operators 6.What is an execution plan? When would you use it? How would you view the execution plan? 84.What is the difference between HAVING clause and the WHERE clause? 76.. Convert Zulu time zone to US Eastern time zone 10.Decode.What is a NOLOCK? 74. Difference . today it takes 6 minutes” 83. NVL2 14.What is a sub-query? When would you use one? 73.union and union all 11. Features in oracle 9i and 10g 7.What are the different types of joins and what dies each do? 71. Give 2 examples of avoiding unnecessary parsing. what is rollback segment 4.What is database normalization? 78.What is the difference between a local and a global variable? 88.What is the purpose of using COLLATE in a query? 81.What is a trigger? 82.Using query analyzer.Equijoin and union 3.What are three SQL keywords used to change or set someone’s permissions? 75. What are the restrictions on calling PL/SQL from SQL 17.What is the difference between a Local temporary table and a Global temporary table? How is each one used?
. Why truncating table is faster than delete 8. Tradeoffs of using partitioned tables 15.What does it mean to have quoted_identifier on? What are the implications of having it off? 86. name 3 ways you can get an accurate count of the number of records in a table? 80. copy commit syntax 9. Difference . Difference . Normalize many to many relationships 2. 1.What is the STUFF function and how does it differ from the REPLACE function? 85. How can we call stored procedure in SQL query 16.Which command using Query Analyzer will give you the version of SQL server and operating system? 79. Which Ranking functions are available? 13.What are the four main query statements? 72.Group by.
How do we upgrade from SQL Server 6.Explain the basic concepts of SQL server architecture? 115. how it looks?
.What is SQL server agent? 96.What is normalization and what are the different forms of normalizations? 99.Difference between server.What is a stored procedure? 105.What are primary keys and foreign keys? 127.How do you load large data to the SQL server database? 93.What is the purpose of UPDATE STATISTICS? 91.)? 116.Explain sp_configure commands. If yes what level and can it be controlled? 108.0 and 7.Difference between Function and Procedure-in general? 106.Explain fundamentals of Data ware housing & OLAP? 117. msdb.89.Explain couple pf features of SQL server 2000(Scalability.Can a stored procedure call another stored procedure. etc.execute method? 100. Availability.What is a table called.How do SQL server 2000 and XML linked? Can XML be used to access data? 95.What is better.Explain some DBCC commands? 121.What is indexing? 98. If yes what level and can it be controlled.How do you check the performance of a query and how do you optimize it? 94.If a stored procedure is taking a table data type.5 to 7.What is referential integrity and how is it achieved? 97.Can a stored procedure call itself(recursive).How would you Update the rows which are divisible by 10.Difference between Cluster and Non-cluster index? 111. RDBMS? 113.How do you use DBCC statements to monitor various aspects of a SQL server installation? 92.What is data integrity? Explain constraints? 120.Explain the new features of SQL server 2000? 118.Explain DBMS.0 to 2000? 119.Explain basic SQL queries with SELECT from where Order By.Can we rewrite subqueries into simple select statements or with joins? Example? 103. Group ByHaving? 114.What is a function? Give some example? 104.What id de-normalization and when do you do it? 101.Difference between Function and Stored Procedure? 107. given a set of numbers in column? 128.What is the basic functions for master. tempdb databases? 124.What are tasks? 126.transfer and server.Explain what are db_options used for? 123.? 109.How do you find the number of rows in a table? 110. set commands? 122. Integration with internet.2nd Normal form or 3rd normal form? Why? 102.What are cursors? Name four types of cursors and when each one would be applied? 90. if it does not have neither Cluster nor Non-cluster Index? 112.What is a job? 125.
7.Questions on identity? 140.How can you get @@error and @@rowcount at the same time? 134.How do you find the error. what will be the state? ****************************************************************
1.What are the type of joins? When do we use Outer and Self joins? 136.If there is failure during updation of certain rows. 4. does that mean a temporary table is created on disk? 10. Is it possible to do a FULL OUTER JOIN in MySQL?
.Which virtual table does a trigger use? 137. 9.How do you know which index a table is using? 131. 8. Using filesort” in the Extra column of EXPLAIN output.Questions regarding Raiseerror? 139. 6. how can you know the number of rows effected by last SQL statement? 133. will performance increase? If I see Using temporary. 2.How will oyu test the stored procedure taking two parameters namely first name and last name returning full name? 132.129. 3.What are sub-queries? Give example? In which case sub-queries are not feasible? 135.How do you measure the performance of a stored procedure? 138.one with OR or one with IN? Where does MyISAM cache table records? Which will be faster out of queries with explicit INNER JOIN and implicit one? Is InnoDB faster/better than MyISAM? Is CHAR faster than VARCHAR? Is VARCHAR(80) faster than VARCHAR(255)? Are there performance issues when joining tables from different storage engines? If I change a derived table to a view.
Which will be faster out of these two queries .How m-m relationships are implemented? 130. 5.