Top Banner

of 22

Sybase Interview Questions

Apr 10, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/8/2019 Sybase Interview Questions

    1/22

    http://dba.fyicenter.com/Interview-Questions/SYBASE/

    Sybase Interview Questions and Answers:Theoritical1what is stored procedure?what is the maximum parameter can pass through it?It is a db objects that exists independly of the table ,Which contain a set of query.maximum paraperters pass through it is 255

    2what is Advantage of stored procedure?faster execution,reduce network traffic,Modular programming,reduced operator eror,enforced consistency3what is Trigger?how many trigger can a table have and what are?It is internal part of a statement that fired when insert,update,delete operation taken place.Three trigger,Triggers are special kind of stored procedures thatget executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.4What is magic table?

    The table that exists within a trigger named as Inserted and deleted are Magic table5what is view?how many table can join for creating view?It is logical way of looking at physical data located in a table,166how will you add a column and drop a column?Alter table table name [add][drop][modify] column name7explain about @@sqlstatus?It returns the status of the pervious fetch statement in a cursor8compare WHERE clause and HAVING clause?

    Where clause cannot have Aggeregate function ,and it select the row before the group by function .having select the row after the group by9What is dead lock?A deadlock occurs when there is a cyclic dependency between two or more transactions for the same set of resources.10What is sp_dboption?It is used to enable or disable db option for your databasesp_dboption,'select into', true

    11

    What is CURSOR?It is a pointer , use for row by row operation12Why we should go for Deallocating the cursors?When we Deallocate the cursor so that server will clear the memory space occupied by the cursor we can use that space for some other action13How many index can have for a table?25014What is Clustered and Nonclustered index?When you craete a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered

    index per table. Non-clustered indexes have their own storage separate from thetable data storage. Non-clustered indexes are stored as B-tree structures (so doclustered indexes), with the leaf level nodes having the index key and it's row

  • 8/8/2019 Sybase Interview Questions

    2/22

    locater15How do I get the Duplicate rows from a table?select * from table group by column having count(*)>116While creating index I forgot to tell what type what will happen?nonclustered index

    17Compare Primary key and 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.18What is bcp.How do you invoke bcp commandIt is used for import and export the values from table to os file and vice-ver.Fast bcp and Slow bcpInvoking the bcp command is as follows:-bcp -S -U -P inout -e -F -L -b -t -r bcp -v displays version no of bcp.

    19Compare left and Right Outer Join?For left join all row was selected in outer table and for inner table row whichare not meet the join condition are filled with NULL. In Right join inner tableall row was selected and for outer table the rows which not meet the join conditins will filled with NULL20While bcp in default,rules,constraints can be applied?Only default can apply

    21What is Hotspot?Whan a multipe processes attempt to modify a same page in table22How do I force the lock?Using Holdlock.

    All select/readtext statements acquire shared locks to retrieve their information. After the information is retrieved, the shared lock(s) is/are released.

    The holdlock option is used within transactions so that after the select/readtext statement the locks are held until the end of the transaction:* commit transaction* rollback transaction

    If the holdlock is not used within a transaction, the shared locks are released.

    23What is Isolation levels and explain them?

    The categories of locking behavior within transaction that are defined by ANSI,Level are 0,1,2,3

  • 8/8/2019 Sybase Interview Questions

    3/22

    Each isolation level specifies the kinds of actions that are not permitted whileconcurrent transactions are executing. Higher levels include the restrictionsimposed by the lower levels:

    Level 0 - allow reading uncommitted data[allow dirty reads]Level 1 - Doesnt allow dirty reads.default isolation level for ASE.Level 2 - prevents non-repeatable reads.

    Such reads occur whenone transaction reads a row and a second transaction modifies that row. Ifthe second transaction commits its change, subsequent reads by the firsttransaction yield different results than the original read

    Level 3 - prevents phantom rows.

    Phantom rows occur when onetransaction reads a set of rows that satisfy a search condition, and then asecond transaction modifies the data (through an insert, delete, update, andso on). If the first transaction repeats the read with the same searchconditions, it obtains a different set of rows.

    24how to get Yesterdays date?dataadd(dd,-1,getdate())

    25What is I option in Sybase tools?It is the name of the interface file to use when trying to find a server to connect to27What are defaults? Is there a column to which a default can't be bound?When you are inserting suppose forgot to enter the value for particular column t

    han you will provide some constant value for that .identity ,timestamps column are default cannot bound.

    A default is a value that Adaptive Server inserts into a column if a userdoes not explicitly enter a value for that column. In database management,a rule specifies what you are or are not allowed to enter in a particularcolumn or in any column with a given user-defined datatype. You can usedefaults and rules to help maintain the integrity of data across thedatabase.

    create default as "UNKNOWN"sp_bindefault ,

    28If I want current database name?select db_name()

    29If i want creation text of a particular object (such as SP,Trigger,view,rule,default)what shall i dosp_helptext,defncopy,syscomments

    30Compare Join and SubQuery in performance?Generally Join queries consume more memory than sub query. Sub query in turn inv

  • 8/8/2019 Sybase Interview Questions

    4/22

    olve intermediate table creation so affects performance, because of high I/Os fetches need for processing. If the RAM memory is more, then the Joins can be usedinstead of sub queries. Under memory constraints we can go for sub queries.Sometimes sub queries are flattened to join to improve the performance. Also making the outer query to compare inner query with equality option can materializethe subquery.

    31What are the different types of lock in Sybase?There are three types of locks:

    * page and row locks* table locks* demand locks

    Page Locks----------There are three types of page locks:

    * shared* exclusive* update

    Shared locks

    Adaptive Server applies shared locks for read operations. If a shared lockhas been applied to a data page or data row or to an index page, other transactions can also acquire a shared lock, even when the first transaction is active.However, no transaction can acquire an exclusive lock on the page or row until all shared locks on the page or row are released. This means that many transactions can simultaneously read the page or row, but no transaction can change data o

    n the page or row while a shared lock exists. Transactions that need an exclusive lock wait or block for the release of the shared locks before continuing.

    By default, Adaptive Server releases shared locks after it finishes scanning the page or row. It does not hold shared locks until the statement is completed or until the end of the transaction unless requested to do so by the user. For more details on how shared locks are applied, see Locking for select queries atisolation Level 1.

    *

    Exclusive locks

    Adaptive Server applies an exclusive lock for a data modification operation. When a transaction gets an exclusive lock, other transactions cannot acquirea lock of any kind on the page or row until the exclusive lock is released at the end of its transaction. The other transactions wait or block until the exclusivelock is released.

    *

    Update locks

    Adaptive Server applies an update lock during the initial phase of an update, delete, or fetch (for cursors declared for update) operation while the pageor row is being read. The update lock allows shared locks on the page or row, but does not allow other update or exclusive locks. Update locks help avoid deadlo

    cks and lock contention. If the page or row needs to be changed, the update lockis promoted to an exclusive lock as soon as no other shared locks exist on thepage or row.

  • 8/8/2019 Sybase Interview Questions

    5/22

    In general, read operations acquire shared locks, and write operations acquire exclusive locks. For operations that delete or update data, Adaptive Server applies page-level or row-level exclusive and update locks only if the column used inthe search argument is part of an index. If no index exists on any of the search arguments, Adaptive Server must acquire a table-level lock.

    Table Locks-----------There are three types of table locks:

    * intent* shared* exclusive

    intentAn intent lock is held as long as page or row locks are in effect for the transaction.Shared lock

    This lock is similar to a shared page or lock, except that it affects the entiretable. For example, Adaptive Server applies a shared table lock for a select command with a holdlock clause if the command does not use an index. A create nonclustered index command also acquires a shared table lock.

    Exclusive lock

    This lock is similar to an exclusive page or row lock, except it affects the entire table. For example, Adaptive Server applies an exclusive table lock during acreate clustered index command. update and delete statements require exclusivetable locks if their search arguments do not reference indexed columns of the object.

    Demand Locks------------A demand lock prevents further shared locks from being set. The SQL Server setsa demand lock to indicate that a transaction is next in queue to lock a table ora page.

    32List out all System procedure in your server?select name from sysobjects where type='P'33There's a performance issue What will be your very first step towards the solution?First you need to identify which query is creating the problem and than to identify where the problem lies in that query. Query that is taking maximum time is the first you want to consider for the optimization. To check which query is taking maximum time to execute place getdate() both before and after the query. Identity the type of the query whether it is a data look-up query, or data modification query.34What is @@rowcount?returns the no of rows affected by the preceding query

    35How do you check whether the rollback was correct?By checking the @@trancount value before rollback statement execute.

  • 8/8/2019 Sybase Interview Questions

    6/22

    36What is Index Covering?Index covering is a mechanism for using the leaf level of nonclustered index theway the data page of a clustered index would work. Index covering occurs when all columns referenced in a query are contained in the index itself.Index covering can produce dramatic performance improvements as data is read from index and not from the table.

    37How do you select unique rows using Sybase?using Distinct keyword39How many database Sybase 11 have ,list out with explanations?four.Master,Model,sybsystemprocs,sybsystemdb,tempdb

    Master - controls the user databases and the operation of Adaptive Server as a whole.Model- used as a template for creating user database.sybsystemprocs - contains system proceduressybsystemdb - contains info about distributed transactions.

    tempdb- contains info about temporary tables and those created with tempdb..

    40What is Roll Forward and Roll Back?

    Roll forward:Committed transaction not written to data area are rolled forward into the data.Sybase has provided the log roll forward capability with the snapshot feature tosupport rolling the database forward from the restoredsnapshot to the last committed transaction.

    Roll back :Uncommited transactions are rolled back.All data modification done

    with in transaction are reversed.

    41If I want to round the value 999.99 as 1000 ?round(999.99,0)42What is Phantom reads?when one transaction reads a set of rows that satisfy a searchcondition, and then a second transaction modifies the data (through aninsert, delete, update, and so on). If the first transaction repeatsthe read with the same search conditions, it obtains a different setof rows.43How will you Restart and Exit on while loop?continue,break44Compare Delete and Truncate?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.

    45

    How many columns can table have?25046

  • 8/8/2019 Sybase Interview Questions

    7/22

    How will you find second maximum value in a table?select max(column1) from table where column1

  • 8/8/2019 Sybase Interview Questions

    8/22

    7. What is the command for quitting from Sybase isql session? quit or exit.

    10. What is a bind cache?sp_bindchache , --> Binding a db object to a cache.

    15. How to find the 2 minimum salaries in a table?

    select min(sal) from salaries where sal>(select min(sal) from salaries)

    20. A column name is given to you. You have to find out which table has that column. Database has 230 tables. For example: empid (column name) For this how do you find out which table has the column (empid) ?

    select name from sysobjects where type = 'U' and id = ( select id from syscolumns where name = 'empid')

    22. What is the difference between sybase 12.5 and 15?

    1.Login triggers: Were introduced in ASE 15.0A login trigger is basically a regular ASE stored procedure, which is automatically executed in the background when a user successfully logs in to ASE.

    2.Fast bcp: In 15.0.2, fast BCP is also allowed for indexed tables. Rest all things about bcp remain same, like select into/bulkcopy/pllsort' is enabled; logging only the page allocations in log etc.

    3.sp_displaylogin displays when and why a login was locked & also when you lastlogged in.

    4.Semantic partitions/smart partitioning: ASE 15 makes large databases easy to manage. And more efficient by allowing you to divide tables into smaller partitions which can be individually managed. You can run maintenance tasks on selectedpartitions to avoid slowing overall performance, and queries run faster becauseASE 15's smart query optimizer bypasses partitions that don't contain relevant data.

    5.Scrollable cursors: With large data sets, filing through a mountain of resultsdata can be difficult. ASE 15?s bi-directional scrollable cursors make it convenient to work with large result sets because your application can easily move backward and forward through a result set, one row at a time. This especially helps with Web applications that need to process large result sets but present the user with subsets of those results

    6.Computed columns: Often applications repeat the same calculation over and overfor the same report or query. ASE 15 supports both virtual and materialized columns based on server calculations. Columns can be the computed result of other data in the table, saving that result for future repeated queries

    7.Functional indexes: When applications need to search tables based on the result of a function, performance can suffer. Functional indexes allow the server tobuild indexes on a table based on the result of a function. When repeated searches use that function, the results do not need to be computed from scratch8.Plan viewer in the form of a GUI: Plans for solving complicated queries can become very complex and make troubleshooting performance issues difficult. To make

    debugging queries simpler, ASE 15 provides a graphical query plan viewer that lets you visualize the query solution selected by ASE's optimizer.

  • 8/8/2019 Sybase Interview Questions

    9/22

    9.In ASE 15.0, Update statistics is not necessary after index rebuild. Also sp_recompile is not necessary after index rebuild.

    10.ASE 15 allows you to assign two billion logical devices to a single server, with each device up to 4 Tb in size. ASE 15 supports over 32,767 databases, and the maximum size limit for an individual database is 32 terabytes, extending the

    maximum storage per ASE server to over 1 million terabytes!11.As of release 12.5.1, all changes to data cache are dynamic12.ASE 15.0 and later versions no longer use vdevno. i.e. the disk init syntax doesn?t need to mention the vdevno parameter.13.Disk init syntax in 12.5 expects size parameter in K, M, and G only. From 15.0 and onwards, T (Terabyte) can be specified.Also, pre 15.0; the maximum size of a device was 32GB14.The configuration parameter ?default database size? was static in ASE 12. InASE 12.5, it was made dynamic.For ASE 15.0, the below table is specified by Sybase.Logical Page Size 2K 4K 8K 16KInitial default database size 3MB 4 MB 8 MB 16 MB

    All system tables, initially 1.2 MB 2.4 MB 4.7 MB 9.4 MB15.In 12.5.0, auto database extension was not present. It was introduced in 12.5.1 and later versions.16.The Dump/Load Database and Dump/Load Tran syntax differ from version 12.5.0.3and 12.5.2(and hence later versions) (See sybooks for more information. The compression levels 1-9were introduced.)17.ASE 12.5.0.3 and earlier versions used to allow only one tempdb in the server. But all the later versions allow creation of multiple temporary databases.18.Before 15.0, after changing a database option we need to use that database and do checkpoint on it. But ASE15.0 doesn?t need this.19.Restricting proxy authorization is available in 12.5.2 and later releases only.

    20.From version 12.5.2 and onwards, cache creation is made dynamic (sp_cacheconfig [cachename [,"cache_size [PKMG]?] It was static earlier.21.Till 12.5.2, backing up a database with password was not possible. ASE 12.5.2and later allow dump database with passwd.22.Cross platform dumps and loads were introduced in ASE 12.5.323.MDA tables (Monitoring and Diagnostic Tables) are available in 12.5.3 and later releases.24. Row Level Locking: In ASE 15.0 all the system tables were converted into datarows format.

    23. What is Sybase Adaptive Server Enterprise?Adaptive Server Enterprise (ASE) is Sybase Corporation's flagship enterprise-class relational model database server

    25. What are table partitions? how is it different with ASE 15.0 version?Partition is a old technology helps to access data faster (not actually faster)in almost all the databases. Sybase ASE 15.0 opens up a new possiblity of this.Sybase ASE contains semantic Partioning which is not available in Oracle latestversion called "Semantic Partioning" Because of this at the time of table definition itself you can mention a certain set of data (for example Countrycode 'US') can sit on a separate partionin. More over it has range based partition and algorithm based partition.

    26. When you change a database option when will it take effect?In pre sybase 15 all database options will take effect after a use database and

    checkpoint command is run.

    For Sybase 15 the option take effect immediately since all sp_dboption commands

  • 8/8/2019 Sybase Interview Questions

    10/22

    have an automatic checkpoint.

    28. What are the steps for Switching to a different Sybase database?select * from ..use

    29. What are the similarity between Oracle and sybase?

    http://www.rocket99.com/sybase/syb_vs_ora.html

    30. What are the mandatory options required for BCP command utility?bcp inout -S server_name -U user_name -P password -t -r

    31. how to check the long running transaction ?In addition to syslogshold one can look at master.sysprocess and the physical_io. If this is large (several hundred thousand) you are probably looking at a query doing a table scan. syslogshold tends to only store theh*longest* running transaction.

    32. What is the default table size in Sybase?1 extent whixh is 8 pages.

    33. how to clear the logsegment when the Secondary truncation point is on ?When the database log is full, Adaptive Server cannot continue to process updates. To solve this problem you must truncate the log. However, you should not truncate transactions from the log before the RepAgent has passed them successfullyto the Replication Server.

    Adaptive Server uses truncation points to ensure that only transactions processed by the RepAgent are truncated. A secondary truncation point marks the place inthe primary database log up to which the RepAgent has processed transactions. The RepAgent periodically updates the secondary truncation point to reflect trans

    actions successfully passed to the Replication Server. Adaptive Server will nottruncate the log past the secondary truncation point.

    To truncate the database log at the secondary truncation point:Verify that the secondary truncation point is set for the database.Execute dbcc gettrunc.A 1 in the ltm_trunc_state column indicates the secondary truncation point is turned on.

    Turn off the secondary truncation point in the database.dbcc settrunc(ltm, ignore)

    Dump the database log.

    Finally, you should dump the transaction log.This may result in the loss of updates to the replicate database.

    Set the secondary truncation point.Before you restart a RepAgent, you need to reestablish the secondary truncationpoint using dbcc settrunc(ltm,valid)After resetting the locater for the database in the rs_locater table, resume theReplication Server to restart the RepAgent.The RepAgent begins scanning the log from the page returned in the ltm_truncpagecolumn by the dbcc gettrunc command.

    34. Why can a user create 249 non clustered indexes over a given table as agains

    t only one clustered index over a table?There can only be one way in which a table can be ordered as per the clustered index.

  • 8/8/2019 Sybase Interview Questions

    11/22

    Since there are 249 other columns and assuming a non-clustered index for each column,249 indexes can be created.

    35. what is a deferred update in sybase?A deferred update is a two-step procedurein which the row is deleted from the original partition and then inserted in thenew partition.

    36. What is the use of sp_helprotect in Sybase?sp_helprotect reports permissions on a stored procedure

    37. What is the role of Replication Server in Sybase?moves data from one place to another.

    38. What is the method for deleting a table in Sybase?drop table

    39. what is forcing an index concept in sybaseAll the columns of the key used in the query..leads to performace improvement.

    41. What are the data types supported by Sybase?http://www.sfu.ca/sasdoc/sashtml/accdb/z0439559.htm

    43. How to list the objects in Sybase?sp_helpselect * from sysobjects

    44. What is the difference between 'dump tran database to physical name' 'dump tran database with truncate_only' and dump tran database with no_log'and In realtime when we go to truncate the log?

    To truncate the log without making a backup copy:- dump tran[saction] database_name with truncate_onlyTo truncate a log that is filled to capacity. Use only as a last resort:-dump tran[saction] database_name with no_logDumps the transaction log to a tape:- dump tran database to physical name

    45. What are the types of Sybase index?clustered and non-clusted

    48. What is defncopy and it's usage.Copies source text to os file.

    50 How many defaults can be placed on one column of a able.If this col had an existing default, what will happen if one more is added?If a default already exists on a column, you must remove it before binding a newdefault.

    51. Difference between natural join and equi join?Equijoins compare the valuesin the columns being joined for equality and then include all the columns in thetables being joined in the results.select *

    from authors, publisherswhere authors.city = publishers.city

  • 8/8/2019 Sybase Interview Questions

    12/22

    In the results of this statement, the city column appears twice. By definition,theresults of an equijoin contain two identical columns. Because there is usuallyno point in repeating the same information, one of these columns can beeliminated by restating the query. The result is called a natural join.

    The query that results in the natural join of publishers and authors on the city

    column is:select publishers.pub_id, publishers.pub_name,publishers.state, authors.*from publishers, authorswhere publishers.city = authors.city

    =====================================

    52. Which one is faster count(*) or count(1) ?

    49. What is the major differences between oracle & sybase

    http://www.rocket99.com/sybase/syb_vs_ora.html

    describe architecture of sybase ?A Sybase server consists of:A) two processes, data server and backup server ;B) devices which house the databases; one database (master) contains system andconfiguration data ;C) a configuration file which contains the server attributes.

    Memory ModelThe Sybase memory model consists of:A) the program area, which is where the dataserver executable is stored;B) the data cache, stores recently fetched pages from the database device

    C) the stored procedure cache, which contains optimized sql callsThe Sybase dataserver runs as a single process within the operating system; whenmultiple users are connected to the database, only one process is managed by the OS. Each Sybase database connection requires 40-60k of memory.The "total memory" configuration parameter determines the amount of memory allocated to the server. This memory is taken immediately upon startup, and does notincrease.

    What's a natural key in Sybasenatural key is a key for a given table that uniquely identifies the row. For example, assume that social security numbers are unique (I believe it is strived tobe unique but it's not always the case), then if you had the following employeetable:

    employee:

    ssn char(09)f_name char(20)l_name char(20)title char(03)

    Then a natural key would be ssn. If the combination of f_name and l_name were unique at this company, then another natural key would be f_name, l_name. As a matter of fact, you can have many natural keys in a given table but in practice what one does is build a surrogate (or artificial) key. he surrogate key is guarant

    eed to be unique because (wait, get back, here it goes again) it's typically a monotonically increasing value.The reason one uses a surrogate key is because your joins will be faster.

  • 8/8/2019 Sybase Interview Questions

    13/22

  • 8/8/2019 Sybase Interview Questions

    14/22

  • 8/8/2019 Sybase Interview Questions

    15/22

    ADD FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);

    Oracle:ALTER TABLE ORDERSADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES CUSTOMER(SID);

    How do you troubleshoot if your tempdb gets filled

    When the transaction log is filled, use dump tran with no_log or dump tran withtruncate_only.If this does not work, u need to do the following:-

    Use the following query to find the spid of the oldest open transaction in a transaction log that has reached its last-chance threshold:

    use mastergoselect dbid, spid from syslogshold

    where dbid = db_id("name_of_database")

    For example, to find the oldest running transaction on the pubs2 database:

    select dbid, spid from syslogsholdwhere dbid = db_id ("pubs2")dbid spid------ ------

    7 1

    Then execute lct_admin.

    The syntax for lct_admin abort is:

    lct_admin("abort", {process_id [, database_id]})

    Before you can abort a transaction, you must first determine its ID. See Gettingthe process ID for the oldest open transaction, below for information about determining the transactions process ID.

    To terminate the oldest transaction, enter the process ID (spid) of the processthat initiated the transaction. This also terminates any other suspended transactions in the log that belong to the specified process.

    For example, if process 83 holds the oldest open transaction in a suspended log,and you want to terminate the transaction, enter:

    select lct_admin("abort", 83)

    This also terminates any other open transactions belonging to process 83 in thesame transaction log.

    To terminate all open transactions in the log, enter:

    select lct_admin("abort", 0, 12)

    a good concept ofmultiple temp dbs can be implemented and we can create temp

    dbs and assign newly created temp db to sa, so that sacould get the info of the processes that is blocking tempdb, ab=nd by using lct_admin or some other commands we can

  • 8/8/2019 Sybase Interview Questions

    16/22

    abort that blocking transaction.

    What is charindex function?charindex(expr1,expr2) --> Searches expr2 for expr1 and returns the starting position.For example,the expression charindex(".",convert(varchar,qty)) searches for a dot in the qty column.

    What is stuff function?stuff(char_expr1, start, length, char_expr2)Delete length characters from char_expr1 at start, and then insert char_expr2 into char_expr1 at start. To delete characters without inserting other characters,char_expr2 should be NULL, not " ", which indicates a single space.

    In order to replace qty = 11.36 with 11,36 use a combination of stuff and charindex as below:-

    charindex(".",convert(varchar,qty)) - returns position of decimal point

    Replace with stuff function as given below:

    stuff(convert(varchar,qty),charindex(".",convert(varchar,qty)),1,",")

    Query to find nth highest salary.---------------------------------SELECT *FROM Employee E1WHERE (N-1) = (SELECT COUNT(DISTINCT(E2.Salary))FROM Employee E2WHERE E2.Salary > E1.Salary)

    In the above example, the inner query uses a value of the outer query in its filter condition meaning; the inner query cannot be evaluated before evaluating theouter query. So each row in the outer query is evaluated first and the inner query is run for that row.

    What is 'forcing an index'?

    Causing the optimizer to use an index forcefully.

    Update trade_p2kset trade_ref = 'new'from transaction_wil (index index_a_new)where record_no_wil = 11.

    Performance and Tuning ..some of the concepts:-

    set showplan on - Use the "set showplan on" command to see the plan chosen as "most efficient" by optimizer.set statistics io on - Use the "set statistics io on" command to see the numberof logical and physical i/o's for a query. Scrutinize those queries with high logical i/o's.Use the "set statistics time on" command to see the amount of time (elapsed, execution, parse and compile) a query takes to run.If the optimizer refuses to select the proper index for a table, you can force i

    t by adding the index id in parentheses after the table name in the FROM clause.If the optimizer turns out to be a "pessimizer", use the "set forceplan on" command to change join order to be the order of the tables in the FROM clause.

  • 8/8/2019 Sybase Interview Questions

    17/22

    How do I find the oldest open transaction in Sybase?

    select h.spid, u.name, p.cmd, h.name, h.starttime,p.hostname, p.hostprocess, p.program_name

    from master..syslogshold h,master..sysprocesses p,master..sysusers uwhere h.spid = p.spidand p.suid = u.suidand h.spid != 0 /* not replication truncation point */

    When are stored procedures compiled in Sybase ?A stored procedures is compiled:1. with the first EXECute, when the parse tree is read into cache2. with every EXECute, if CREATE PROCEDURE included WITH RECOMPILE3. with each EXECute specifying WITH RECOMPILE

    4. if the plans in cache for the procedure are all in use by other processes5. after EXECute sp_recompile on a referenced table, which increments sysobjects.schema and thus forces re-compilation

    How do I remove duplicate rows from a table in Sybase?

    There are a number of different ways to achieve this, depending on what you aretrying to achieve.Usually, you are trying to remove duplication of a certain key due to changes inbusiness rules or recognition of a business rule that was not applied when thedatabase was originally built.

    Probably the quickest method is to build a copy of the original table:

    select *into temp_tablefrom base_tablewhere 1=2

    Create a unique index on the columns that covers the duplicating rows with the ignore_dup_key attribute. This may be more columns that the key for the table.

    create unique index temp_idxon temp_table(col1, col2, ..., colN)with ignore_dup_key

    Now, insert base_table into temp_table.

    insert temp_tableselect * from base_table

    You probably want to ensure you have a very good backup of the base_table at this point, coz your going to clear it out!You will also want to check to ensure that the temp_table includes the rows youneed.

    You also need to ensure that there are no triggers on the base table (rememberto keep a copy!) or RI constraints.You probably do not want any of these to fire, or if they do, you are aware of

  • 8/8/2019 Sybase Interview Questions

    18/22

    the implications.

    Now you have a couple of choices. You can simply drop the original table and rename the temp table to the same name as the base table. Alternatively, truncate the table and insert from the temp_table into the original table. You would needto do this last if you did need the RI to fire on the table etc. I suspect thatin most cases dropping and renaming will be the best option.

    If you want to simply see the duplicates in a table, the following query will help:

    select key1, key2, ...from base_tablegroup by key1, key2, key3, key4, ...having count(*) > 1

    How do you identify the triggers associated with a table in a sybase database?sp_depends

    How can I execute dynamic SQL with ASE in Sybase?

    declare @sqlstring varchar(255)select @sqlstring = "select count(*) from master..sysobjects"exec (@sqlstring)go

    How can I tell when my server started?

    select crdate from master..sysdatabases where name = 'tempdb'

    What will happen if we create more indexes on a sybase table?

    As far as i know the retrieval is fast.as per the standard definitions the insertion will be slow.To achieve more performance when you are loading large dataplease drop indexes on the table and load the data.Once yourload has completed recreate indexes.It will help your performance.

    What is the maximum nesting level of Stored Procedure and Triggers in Sybase?Triggers can nest to a depth of 16 levels. The currentnesting level is stored in the @@nestlevel global variable.Nesting is enabled at installation. A System Administratorcan turn trigger nesting on and off with the allow nestedtriggers configuration parameter.the same is applied for Sp with nesting level with a rangeor depth from 0 to 16.if more than 16 then we get an error as :Maximum storedprocedure nesting level exceeded (limit 16).

    What is a temp table? how to denote temp table?Any table with name starting with '#' is automatically putinto tempdb database.Temp tables allow developers to create and scan tableswithin a stored procedure - andhave the tables totally isolated from all other database

    connections. This is veryvaluable when results need to be processed several timeswithin a loop, or when

  • 8/8/2019 Sybase Interview Questions

    19/22

    a complex result set is expected (like a crosstab). Notethat temp table transactionsare logged within tempdb (exception: select into createstatements).

    # 1

    When you install Adaptive Server, it contains these systemdatabases:

    The master database controls the user databases and theoperation of Adaptive Server as a whole. It storesinformation about all user databases and their associateddatabase devices.

    The model database is used by Adaptive Server as a templatefor creating new user databases.

    A new database cannot be smaller than the modeldatabase.

    ? The sybsystemprocs database contains the system storedprocedures.

    The sybsystemdb database contains information aboutdistributed transactions.

    ? The temporary database, tempdb, stores temporary objects,including temporary tables created with the nameprefix ?tempdb..?.

    ? The sybsecurity database, contains the audit system forAdaptive Server. It consists of:

    The system tables, sysaudits_01, sysaudits_02, ...sysaudits_08, which contain the audit trail

    what is the architechure of sybase ASE?

    The Sybase ServerA Sybase server consists of:

    a) Two processes, data server and backup server.b) Devices which house the databases; one database

    (master) contains system and configuration data.c) A configuration file which contains the server

    attributes.Memory ModelThe Sybase memory model consists of:

    a) The program area, which is where the dataserverexecutable is stored.

    b) The data cache, stores recently fetched pagesfrom the database device.

    c) The stored procedure cache, which containsoptimized sql calls.A database device stores the objects that make up

    databases.The term device does not necessarily refer to a

    distinct physical device: it can refer to any piece of a

  • 8/8/2019 Sybase Interview Questions

    20/22

    disk (such as a disk partition) or a file in the filesystem that is used to store databases and their objects.

    Each database device or file must be prepared and madeknown to Adaptive Server before it can be used for databasestorage. This process is called initialization.A segment is a label that points to one or more database

    devices. When you first create a database, Adaptive Servercreates three segments in the database,

    System: Stores the database?s system tables.Logsegment: Stores the database?s transaction log.Default: Stores all other database objects?unless youcreate additional segments and store tables or indexes onthe new segments by using create table...on segment_name orcreate index...on segment_name

    what are the properties of relational tables?Values are atomic

    /prod/gbo/bin/process_mail.pl calls Deshaw::GBO::Mail::MailProcessor::process_mailFrom process_mail, call to Deshaw::GBO::Mail::MIMEMessage::get_action_cmdline_for_mail takes placeFrom within this,we set the options for the mime-message,like getFromField,getSubject(),getMailRecipientList(),do database connection and then get the archivalpath and then we use save_mime_msg_to

    -----------

    perl -w --> causes the interpreter to spit out warnings when the variables used

    are not declared.

    Why do you want to use strict?To help you catch typos so you can quickly get on to finding more significant problems (and so we don't have to catch the typos for you either), among other reasons.Its difficult to spot '$recieve_date' when on the previous page you've been calling it '$receive_date'. Also, to give your variables as small a scope as possible so that you don't have to worry about what they're doing to other parts of your program (although that's the function of my, it forces you to use my which when properly used helps achieve this goal).

    -----------save transaction :Used as a savepoint.If I specify a rollbackstatement, the transaction will be rolled back upto the savepoint only.

    @@transtate global variable contains the current status of a transaction.@@trancount contains the current nesting level of a transaction.Until it becomes0, transaction would not be committed.

    Two transaction modes in ASE:chained and unchained..Chained :Every data selection and modification command initiates an implicitBEGIN transaction.Unchained:Transaction should be explicitly begun.This is the default mode for sybase ASE.

    @@tranchained global variable contains the current transaction mode. it returns1 or 0 to specify whether the transaction is at chained or unchained mode.

  • 8/8/2019 Sybase Interview Questions

    21/22

    Default transaction isolation level is set at 1.

    The global variable @@isolation contains the current isolation level of your Transact-SQL session.

    To enforce transaction isolation level 2 from a query, use:

    select title_id, price, advancefrom titlesat isolation 2

    ---------------------------------CLUSTERED INDEX --> http://msdn.microsoft.com/en-us/library/aa933131%28v=SQL.80%29.aspx================A clustered index determines the physical order of data in a table. A clusteredindex is analogous to a telephone directory, which arranges data by last name. B

    ecause the clustered index dictates the physical storage order of the data in the table, a table can contain only one clustered index. However, the index can comprise multiple columns (a composite index), like the way a telephone directoryis organized by last name and first name.

    A clustered index is particularly efficient on columns that are often searched for ranges of values. After the row with the first value is found using the clustered index, rows with subsequent indexed values are guaranteed to be physicallyadjacent. For example, if an application frequently executes a query to retrieverecords between a range of dates, a clustered index can quickly locate the rowcontaining the beginning date, and then retrieve all adjacent rows in the tableuntil the last date is reached. This can help increase the performance of this type of query. Also, if there is a column(s) that is used frequently to sort the

    data retrieved from a table, it can be advantageous to cluster (physically sort)the table on that column(s) to save the cost of a sort each time the column(s)is queried.

    Clustered indexes are also efficient for finding a specific row when the indexedvalue is unique. For example, the fastest way to find a particular employee using the unique employee ID column emp_id is to create a clustered index or PRIMARY KEY constraint on the emp_id column.

    Before creating clustered indexes, understand how your data will be accessed. Consider using a clustered index for:

    * Columns that contain a large number of distinct values.

    * Queries that return a range of values using operators such as BETWEEN, >,>=,

  • 8/8/2019 Sybase Interview Questions

    22/22

    cally by means of the primary key. Create a clustered index on the primary key.

    Clustered indexes are not a good choice for:

    * Columns that undergo frequent changes

    This results in the entire row moving (because SQL Server must keep the data values of a row in physical order). This is an important consideration in high-volume transaction processing systems where data tends to be volatile.

    NON CLUSTERED INDEX-===================

    Before you create nonclustered indexes, understand how your data will be accessed. Consider using nonclustered indexes for:

    * Columns that contain a large number of distinct values, such as a combinat

    ion of last name and first name (if a clustered index is used for other columns). If there are very few distinct values, such as only 1 and 0, most queries willnot use the index because a table scan is usually more efficient.

    * Queries that do not return large result sets.

    * Columns frequently involved in search conditions of a query (WHERE clause)that return exact matches.

    * Decision-support-system applications for which joins and grouping are frequently required. Create multiple nonclustered indexes on columns involved in join and grouping operations, and a clustered index on any foreign key columns.

    * Covering all columns from one table in a given query. This eliminates accessing the table or clustered index altogether.