Thursday, September 11, 2008

Interview questions for Linux admin

Advantages/disadvantages of script vs compiled program.
Name a replacement for PHP/Perl/MySQL/Linux/Apache and show main differences. .Why have you choosen such a combination of products?
Differences between two last MySQL versions. Which one would you choose and when/why?
Main differences between Apache 1.x and 2.x. Why is 2.x not so popular? Which one would you choose and when/why?
Which Linux distros do you have experience with?
Which distro you prefer? Why?
Which tool would you use to update Debian / Slackware / RedHat / Mandrake / SuSE ?
You’re asked to write an Apache module. What would you do?
Which tool do you prefer for Apache log reports?
Your portfolio. (even a PHP guest book may work well)
What does ‘route’ command do?
Differences between ipchains and iptables.
What’s eth0, ppp0, wlan0, ttyS0, etc.
What are different directories in / for?
Partitioning scheme for new webserver. Why?

Unix sysadmin interview questions

1. How would you make the following SQL statement run faster? SELECT * FROM TABLEA WHERE COL1=’A’ AND COL2=’B'; A: Make sure that COL1 and COL2 have indexes.Find out which condition will return less values and use that as the first conditonal.
2. What is Data Mining A: Data Minig is the process of sifting through extremeley large amounts of Data to find trends or relevent information.
3. Name the Seven layers in the OSI Model. A: Appication, Presentation, Session, Transport, Network, Data Link, Phyiscal
4. What is one way to view a unix network share on a Windows computer, within explorer A: NFS, The Unix computer can be running a NFS Server Daemon.
5. How would you find all the processes running on your computer. A: Unix, is ps -ef or ps -aux depending on version.
6. What is DHCP A: DHCP is a way to dynamically assign IP address to computers. Dyanmic Host Configuration Protocol
7. What is HTTP Tunneling A: HTTP Tunneling is a security method that encryptes packets traveling throught the internet. Only the intended reciepent should be able to decrypt the packets. Can be used to Create Virtual Private Networks. (VPN)
8. Scenario: You have 9 identical looking balls, however one ball is heavier than the others. You have two chances to use a balance. How do you find out which ball is the heaviest? A: Split into groups of three, randomly choose two groups and use balance on them. If one group is heavier, then discard the other 6 balls. If the two groups are the same weight. The heavier ball must be in the group that was not on the scale. Now randomly choose two balls and test on balance. If they are the same weight, the heaviest ball is on one that was not tested. Else the heaviest ball is already known from the balance

Unix/Linux programming interview questions

1. What is the major advantage of a hash table? (Asked by Silicon Magic Corp. people) Answer: The major advantage of a hash table is its speed. Because the hash function is to take a range of key values and transform them into index values in such a way that the key values are distributed randomly across all the indices of a hash table.
2. What are the techniques that you use to handle the collisions in hash tables?(Asked by Silicon Magic Corp. people)
Answer: We can use two major techniques to handle the collisions. They are open addressing and separate chaining. In open addressing, data items that hash to a full array cell are placed in another cell in the array. In separate chaining, each array element consist of a linked list. All data items hashing to a given array index are inserted in that list.
3. In Unix OS, what is the file server? (Asked by Silicon Magic Corp. people)
Answer: The file server is a machine that shares its disk storage and files with other machines on the network.
4. What is NFS? What is its job?(Asked by Silicon Magic Corp. people)
Answer: NFS stands for Network File System. NFS enables filesystems physically residing on one computer system to be used by other computers in the network, appearing to users on the remote host as just another local disk.
5. What is CVS? List some useful CVS commands.(Asked by Silicon Magic Corp.people)
Anser: CVS is Concurrent Version System. It is the front end to the RCS revision control system which extends the notion of revision control from a collection of files in a single directory to a hierarchical collection of directories consisting of revision controlled files. These directories and files can be combined together to form a software release. There are some useful commands that are being used very often. They are
cvs checkout cvs update cvs add cvs remove cvs commit

Unix/Linux administration interview questions

1.What is LILO?
LILO stands for Linux boot loader. It will load the MBR, master boot record, into the memory, and tell the system which partition and hard drive to boot from.
2.What is the main advantage of creating links to a file instead of copies of the file?
A: The main advantage is not really that it saves disk space (though it does that too) but, rather, that a change of permissions on the file is applied to all the link access points. The link will show permissions of lrwxrwxrwx but that is for the link itself and not the access to the file to which the link points. Thus if you want to change the permissions for a command, such as su, you only have to do it on the original. With copies you have to find all of the copies and change permission on each of the copies.
3.Write a command to find all of the files which have been accessed within the last 30 days.
find / -type f -atime -30 > December.files
This command will find all the files under root, which is ‘/’, with file type is file. ‘-atime -30′ will give all the files accessed less than 30 days ago. And the output will put into a file call December.files.
4.What is the most graceful way to get to run level single user mode?
A: The most graceful way is to use the command init s.If you want to shut everything down before going to single user mode then do init 0 first and from the ok prompt do a boot -s.
5.What does the following command line produce? Explain each aspect of this line.
$ (date ; ps -ef awk ‘{print $1}’ sort uniq wc -l ) >> Activity.log
A: First let’s dissect the line: The date gives the date and time as the first command of the line, this is followed by the a list of all running processes in long form with UIDs listed first, this is the ps -ef. These are fed into the awk which filters out all but the UIDs; these UIDs are piped into sort for no discernible reason and then onto uniq (now we see the reason for the sort - uniq only works on sorted data - if the list is A, B, A, then A, B, A will be the output of uniq, but if it’s A, A, B then A, B is the output) which produces only one copy of each UID.
These UIDs are fed into wc -l which counts the lines - in this case the number of distinct UIDs running processes on the system. Finally the results of these two commands, the date and the wc -l, are appended to the file "Activity.log". Now to answer the question as to what this command line produces. This writes the date and time into the file Activity.log together with the number of distinct users who have processes running on the system at that time. If the file already exists, then these items are appended to the file, otherwise the file is created.

SQL Server interview questions

How do you read transaction logs?
How do you reset or reseed the IDENTITY column?
How do you persist objects, permissions in tempdb?
How do you simulate a deadlock for testing purposes?
How do you rename an SQL Server computer?
How do you run jobs from T-SQL?
How do you restore single tables from backup in SQL Server 7.0/2000? In SQL Server 6.5?
Where to get the latest MDAC from?
I forgot/lost the sa password. What do I do?
I have only the .mdf file backup and no SQL Server database backups. Can I get my database back into SQL Server?
How do you add a new column at a specific position (say at the beginning of the table or after the second column) using ALTER TABLE command?
How do you change or alter a user defined data type?
How do you rename an SQL Server 2000 instance?
How do you capture/redirect detailed deadlock information into the error logs?
How do you remotely administer SQL Server?
What are the effects of switching SQL Server from ‘Mixed mode’ to ‘Windows only’ authentication mode? What are the steps required, to not break existing applications?
Is there a command to list all the tables and their associated filegroups?
How do you ship the stored procedures, user defined functions (UDFs), triggers, views of my application, in an encrypted form to my clients/customers? How do you protect intellectual property?
How do you archive data from my tables? Is there a built-in command or tool for this?
How do you troubleshoot ODBC timeout expired errors experienced by applications accessing SQL Server databases?
How do you restart SQL Server service automatically at regular intervals?
What is the T-SQL equivalent of IIF (immediate if/ternary operator) function of other programming languages?
How do you programmatically find out when the SQL Server service started?
How do you get rid of the time part from the date returned by GETDATE function?
How do you upload images or binary files into SQL Server tables?
How do you run an SQL script file that is located on the disk, using T-SQL?
How do you get the complete error message from T-SQL while error handling?
How do you get the first day of the week, last day of the week and last day of the month using T-SQL date functions?
How do you pass a table name, column name etc. to the stored procedure so that I can dynamically select from a table?
Error inside a stored procedure is not being raised to my front-end applications using ADO. But I get the error when I run the procedure from Query Analyzer.
How do you suppress error messages in stored procedures/triggers etc. using T-SQL?
How do you save the output of a query/stored procedure to a text file?
How do you join tables from different databases?
How do you join tables from different servers?
How do you convert timestamp data to date data (datetime datatype)?
Can I invoke/instantiate COM objects from within stored procedures or triggers using T-SQL?
Oracle has a rownum to access rows of a table using row number or row id. Is there any equivalent for that in SQL Server? Or How do you generate output with row number in SQL Server?
How do you specify a network library like TCP/IP using ADO connect string?
How do you generate scripts for repetitive tasks like truncating all the tables in a database, changing owner of all the database objects, disabling constraints on all tables etc?
Is there a way to find out when a stored procedure was last updated?
How do you find out all the IDENTITY columns of all the tables in a given database?
How do you search the code of stored procedures?
How do you retrieve the generated GUID value of a newly inserted row? Is there an @@GUID, just like @@IDENTITY?

SQL Server, DBA interview questions

Questions are categorized under the following sections, for your convenience:

Database design (8 questions)

SQL Server architecture (12 questions)

Database administration (13 questions)

Database programming (10 questions)

Database design

What is normalization? Explain different levels of normalization?

Check out the article Q100139 from Microsoft knowledge base and of course, there’s much more information available in the net. It’ll be a good idea to get a hold of any RDBMS fundamentals text book, especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process of normalization. It’s the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. It will be a good idea to read up a database designing fundamentals text book.

What’s the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

What are user defined datatypes and when you should go for them?

User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables. See sp_addtype, sp_droptype in books online.

What is bit datatype and what’s the information that can be stored inside a bit column?

Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

Define candidate key, alternate key, composite key.

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default can’t be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can’t have defaults bound to them. See CREATE DEFAULT in books online.

What is a transaction and what are ACID properties?

A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book. Explain different isolation levels An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level. Read Committed - A transaction operating at the Read Committed level cannot see changes made by other transactions until those transactions are committed. At this level of isolation, dirty reads are not possible but nonrepeatable reads and phantoms are possible. Read Uncommitted - A transaction operating at the Read Uncommitted level can see uncommitted changes made by other transactions. At this level of isolation, dirty reads, nonrepeatable reads, and phantoms are all possible. Repeatable Read - A transaction operating at the Repeatable Read level is guaranteed not to see any changes made by other transactions in values it has already read. At this level of isolation, dirty reads and nonrepeatable reads are not possible but phantoms are possible. Serializable - A transaction operating at the Serializable level guarantees that all concurrent transactions interact only in ways that produce the same effect as if each transaction were entirely executed one after the other. At this isolation level, dirty reads, nonrepeatable reads, and phantoms are not possible.

CREATE INDEX myIndex ON myTable(myColumn)What type of Index will get created after executing the above statement?

Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

What’s the maximum size of a row?

8060 bytes. Don’t be surprised with questions like ‘what is the maximum number of columns per table’. 1024 columns per table. Check out SQL Server books online for the page titled: "Maximum Capacity Specifications". Explain Active/Active and Active/Passive cluster configurations Hopefully you have experience setting up cluster servers. But if you don’t, at least be familiar with the way clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server books online has enough information on this topic and there is a good white paper available on Microsoft site. Explain the architecture of SQL Server This is a very important question and you better be able to answer it if consider yourself a DBA. SQL Server books online is the best place to read about SQL Server architecture. Read up the chapter dedicated to SQL Server Architecture.

What is lock escalation?

Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it’s dynamically managed by SQL Server.

What’s the difference between DELETE TABLE and TRUNCATE TABLE commands?

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won’t log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log. TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. TRUNCATE TABLE may not be used on tables participating in an indexed view

Explain the storage models of OLAP

Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more infomation.

What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time of your interview)? What changed between the previous version of SQL Server and the current version?

This question is generally asked to see how current is your knowledge. Generally there is a section in the beginning of the books online titled "What’s New", which has all such information. Of course, reading just that is not enough, you should have tried those things to better answer the questions. Also check out the section titled "Backward Compatibility" in books online which talks about the changes that have taken place in the new version.

What are constraints? Explain different types of constraints.

Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults. Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY. For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE TABLE", "ALTER TABLE"

What is an index? What are the types of indexes? How many clustered indexes can be created on a table? I create a separate index on each column of a table. What are the advantages and disadvantages of this approach?

Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker. Indexes are of two types. Clustered indexes and non-clustered indexes. When you create 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 the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and it’s row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table. If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.

What is RAID and what are different types of RAID configurations?

RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has some information about RAID levels and for detailed information, check out the RAID advisory board’s homepage

What are the steps you will take to improve performance of a poor performing query?

This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables. Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query Analyzer. Download the white paper on performance tuning SQL Server from Microsoft web site. Don’t forget to check out sql-server-performance.com

What are the steps you will take, if you are tasked with securing an SQL Server?

Again this is another open ended question. Here are some things you could talk about: Preferring NT authentication, using server, databse and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc. Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server security best practices

What is a deadlock and what is a live lock? How will you go about resolving deadlocks?

Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other’s piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user’s process. A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely. Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also check out the article Q169960 from Microsoft knowledge base.

What is blocking and how would you troubleshoot it?

Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first. Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions. Explain CREATE DATABASE syntax Many of us are used to creating databases from the Enterprise Manager or by just issuing the command: CREATE DATABAE MyDB.

But what if you have to create a database with two filegroups, one on drive C and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%?

That’s why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out SQL Server books online for more information.

How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?

SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal configuration mode. Check out SQL Server books online for more parameters and their explanations.

As a part of your job, what are the DBCC commands that you commonly use for database maintenance?

DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information.

What are statistics, under what circumstances they go out of date, how do you update them?

Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query. Some situations under which you should update statistics: 1) If there is significant change in the key values in the index 2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3) Database is upgraded from a previous version. Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats

What are the different ways of moving data/databases between servers and databases in SQL Server?

There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT…SELECT, SELECT…INTO, creating INSERT scripts to generate data.

Explain different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would you go about choosing a backup plan?

Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup.

What is database replication? What are the different types of replication you can set up in SQL Server?

Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios: � Snapshot replication � Transactional replication (with immediate updating subscribers, with queued updating subscribers) � Merge replication See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc.

How to determine the service pack currently installed on SQL Server?

The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. To know more about this process visit SQL Server service packs and versions.

What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row processing of the resultsets. Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information. Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one roundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Further, there are restrictions on the SELECT statements that can be used with some types of cursors. Most of the times, set based operations can be used instead of cursors. Here is an example: If you have to give a flat hike to your employees using the following criteria: Salary between 30000 and 40000 — 5000 hike Salary between 40000 and 55000 — 7000 hike Salary between 55000 and 65000 — 9000 hike. In this situation many developers tend to use a cursor, determine each employee’s salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000 END

Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You don’t have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the ‘My code library’ section of my site or search for WHILE. Write down the general syntax for a SELECT statements covering all the options. Here’s the basic syntax: (Also checkout SELECT in books online for advanced syntax).

SELECT select_list [INTO new_table_] FROM table_source [WHERE search_condition] [GROUP BY group_by_expression] [HAVING search_condition] [ORDER BY order_expression [ASC DESC] ]

What is a join and explain different types of joins.

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS. For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?

An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server. Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see ‘My code library’ section of this site.

What is the system function to get the current user’s user id?

USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME().

What are triggers? How many triggers you can have on a table? How to invoke a trigger on demand?

Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table. In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there’s no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder. Triggers can’t be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined. Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster. Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers. Also check out books online for ‘inserted table’, ‘deleted table’ and COLUMNS_UPDATED()

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?

Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.

What is a self join? Explain it with an example.

Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp ( empid int, mgrid int, empname char(10) )

INSERT emp SELECT 1,2,’Vyas’ INSERT emp SELECT 2,3,’Mohan’ INSERT emp SELECT 3,NULL,’Shobha’ INSERT emp SELECT 4,2,’Shridhar’ INSERT emp SELECT 5,2,’Sourabh’

SELECT t1.empname [Employee], t2.empname [Manager] FROM emp t1, emp t2 WHERE t1.mgrid = t2.empid Here’s an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, ‘No manager’) [Manager] FROM emp t1 LEFT OUTER JOIN emp t2 ON t1.mgrid = t2.empid

Database management interview questions

1. What is a Cartesian product? What causes it?

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.

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?

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?

A table scan.

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

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?

Wednesday, September 10, 2008

C Programs

1. Write a program in C to display the message " welcome to c program in C me writing" ?
2. Write a program in C to find the area of circle ?
3. write a program in C to find the area of triangle ?
4. Write a program in C to find the area of sphere ?
5. Write a program in C to find the circumference of circle ?
6. Write a program in C to find the area of circle using input value ?
7. Write a program in C to find the area of triangle using input value ?
8. Write a program in C to find the area of sphere using input value ?
9. Write a program in C to find the circumference of circle using input value ?
10. Write a program in C to read and print an given character ?
11. Write a program in C to print the ascii value of given character ?
12. Write a program in C to read and print the given integer ?
13. Write a program in C to read and print the given float ?
14. Write a program in C to read and print the given float with two decimal places ?
15. Write a program in C to read and print the given double ?
16. Write a program in C to read and print the given double with two decimal places ?
17. Write a program in C to Arithmatic operations of two integer numbers ?
18. Write a program in C to Arithmatic operations of two integer numbers .Print these results in separate lines ?
19. Write a program in C to Arithmatic operations of two long numbers .Print these results in separate lines ?
20. Write a program in C to Arithmatic operations of two float numbers .Print these results in separate lines ?
21. Write a program in C to Arithmatic operations of two double numbers .Print these results in separate lines ?
22. Write a program in C to print the upper case letters to lower case ?
23. Write a program in C to print the lower case letters to upper case ?
24. Write a program in C to read float value and print integer equivalent ?
25. Write a program in C to read int value and print float equivalent ?

C Quesitions

1. The C language terminator is

(a) semicolon
(b) colon
(c) period
(d) exclamation mark


2. What is false about the following -- A compound statement is

(a) A set of simple statments
(b) Demarcated on either side by curly brackets
(c) Can be used in place of simple statement
(d) A C function is not a compound statement.


3. What is true about the following C Functions

(a) Need not return any value
(b) Should always return an integer
(c) Should always return a float
(d) Should always return more than one value


4. Main must be written as

(a) The first function in the program
(b) Second function in the program
(c) Last function in the program
(d) Any where in the program


5. Which of the following about automatic variables within a function is correct ?

(a) Its type must be declared before using the variable
(b) Tthey are local
(c) They are not initialised to zero
(d) They are global


6. Write one statement equivalent to the following two statements

x=sqr(a);
return(x);

Choose from one of the alternatives

(a) return(sqr(a));
(b) printf("sqr(a)");
(c) return(a*a*a);
(d) printf("%d",sqr(a));


7. Which of the following about the C comments is incorrect ?

(a) Ccommentscan go over multiple lines
(b) Comments can start any where in the line
(c) A line can contain comments with out any language statements
(d) Comments can occur within comments


8. What is the value of y in the following code?
x=7;
y=0;
if(x=6) y=7;
else y=1;

(a) 7
(b) 0
(c) 1
(d) 6


9. Read the function conv() given below
conv(int t){
int u;
u=5/9 * (t-32);
return(u);
}
What is returned

(a) 15
(b) 0
(c) 16.1
(d) 29


10. Which of the following represents true statement either x is in the range of 10 and 50 or y is zero

(a) x >= 10 && x <= 50 || y = = 0
(b) x<50
(c) y!=10 && x>=50
(d) None of these


11. Which of the following is not an infinite loop ?

(a) while(1)\{ ....}

(b) for(;;)
{
...
}

(c) x=0;
do{
/*x unaltered within the loop*/
.....}
while(x = = 0);

(d) # define TRUE 0
...
while(TRUE){
....}



12. What does the following function print?
func(int i)
{ if(i%2)return 0;
else return 1;}
main()
{
int =3;
i=func(i);
i=func(i);
printf("%d",i);
}

(a) 3
(b) 1
(c) 0
(d) 2


13. How does the C compiler interpret the following two statements
p=p+x;
q=q+y;


(a) p=p+x;
q=q+y
(b)p=p+xq=q+y
(c)p=p+xq;
q=q+y
(d)p=p+x/q=q+y



For questions 14,15,16,17 use the following alternatives

a.int
b.char
c.string
d.float

14. '9'

15. "1 e 02"

16. 10e05

17. 15



18. Read the folllowing code

# define MAX 100
# define MIN 100
....
....
if(x>MAX)
x=1;
else if(xx=-1;
x=50;
if the initial value of x=200,what is the value after executing this code?

(a) 200
(b) 1
(c) -1
(d) 50


19. A memory of 20 bytes is allocated to a string declared as char *s
then the following two statements are executed:
s="Entrance"
l=strlen(s);
what is the value of l ?

(a)20
(b)8
(c)9
(d)21


20. Given the piece of code

int a[50];
int *pa;
pa=a;

To access the 6th element of the array which of the following is incorrect?

(a) *(a+5)
(b) a[5]
(c) pa[5]
(d) *(*pa + 5}


21. Consider the following structure:

struct num nam{
int no;
char name[25];
}

struct num nam n1[]={{12,"Fred"},{15,"Martin"},{8,"Peter"},{11,Nicholas"}};
.....
.....
printf("%d%d",n1[2],no,(*(n1 + 2),no) + 1);

What does the above statement print?

(a) 8,9
(b) 9,9
(c) 8,8
(d) 8,unpredictable value


22. Identify the in correct expression

(a) a=b=3=4;
(b) a=b=c=d=0;
(c)float a=int b=3.5;
(d)int a; float b; a=b=3.5;


23. Regarding the scope of the varibles;identify the incorrect statement:

(a)automatic variables are automatically initialised to 0
(b)static variables are are automatically initialised to 0
(c)the address of a register variable is not accessiable
(d)static variables cannot be initialised with any expression


24. cond 1?cond 2?cond 3?:exp 1:exp 2:exp 3:exp 4;
is equivalent to which of the following?

(a)if cond 1
exp 1;
else if cond 2
exp 2;
else if cond 3
exp 3;
else exp 4;

(b) if cond 1
if cond 2
if cond 3
exp 1;
else exp 2;
else exp 3;
else exp 4;

(c) if cond 1 && cond 2 && cond 3
exp 1 |exp 2|exp 3|exp 4;

(d) if cond 3
exp 1;
else if cond 2 exp 2;
else if cond 3 exp 3;
else exp 4;



25. The operator for exponencation is

(a) **
(b) ^
(c) %
(d) not available


26. Which of the following is invalid

(a) a+=b
(b) a*=b
(c) a»=b
(d) a**=b


27. What is y value of the code if input x=10

y=5;
if (x==10)
else if(x==9)
else y=8;

(a)9
(b)8
(c)6
(d)7


28. What does the following code do?

fn(int n,int p,int r){
static int a=p;
switch(n){
case 4:a+=a*r;
case 3:a+=a*r;
case 2:a+=a*r;
case 1:a+=a*r;}}

(a)computes simple interest for one year
(b)computes amount on compound interest for 1 to 4 years
(c)computes simple interest for four year
(d)computes compound interst for 1 year


29. a=0;
while(a<5)
printf("%d\\n",a++);
How many times does the loop occurs?

(a)infinite
(b)5
(c)4
(d)6


30. How many times does the loop iterated ?

for (i=0;i=10;i+=2)
printf("Hi\\n");

(a)10
(b) 2
(c) 5
(d) None of these


31. What is incorrect among the following
A recursive function

(a) calls itself
(b) is equivalent to a loop
(c) has a termination condition
(d) does not have a return value at all



32. Which of the following go out of the loop if expn 2 becoming false

(a) while(expn 1)\{...if(expn 2)continue;}
(b) while(!expn 1)\{if(expn 2)continue;...}
(c) do{..if(expn 1)continue;..}while(expn 2);
(d) while(!expn 2)\{if(expn 1)continue;..\}


33. Consider the following program

main()
{unsigned int i=10;
while(i>=0){
printf("%u",i)
i--;}
}

How many times the loop will get executed

(a)10
(b)9
(c)11
(d)infinite


34.Pick out the add one out

(a) malloc()
(b) calloc()
(c) free()
(d) realloc()


35.Consider the following program

main(){
int a[5]={1,3,6,7,0};
int *b;
b=&a[2];
}
The value of b[-1] is

(a) 1
(b) 3
(c) -6
(d) none


36. # define prod(a,b)=a*b
main(){
int x=2;
int y=3;
printf("%d",prod(x+2,y-10)); }

the output of the program is

(a) 8
(b) 6
(c) 7
(d) None


37.Consider the following program segment

int n,sum=1;
switch(n){
case 2:sum=sum+2;
case 3:sum*=2;
break;
default:sum=0;}

If n=2, what is the value of sum

(a) 0
(b) 6
(c) 3
(d) None of these


38. Identify the incorrect one

1.if(c=1)
2.if(c!=3)
3.if(a4.if(c==1)

(a) 1 only
(b) 1&3
(c) 3 only
(d) All of the above


39. The format specified for hexa decimal is

(a) %d
(b) %o
(c) %x
(d) %u


40. Find the output of the following program

main(){
int x=5, *p;
p=&x
printf("%d",++*p);
}

(a) 5
(b) 6
(c) 0
(d) none of these


41.Consider the following C code

main(){
int i=3,x;
while(i>0){
x=func(i);
i--; }

int func(int n){
static sum=0;
sum=sum+n;
return(sum);}

The final value of x is

(a) 6
(b) 8
(c) 1
(d) 3


43. Int *a[5] refers to

(a) array of pointers
(b) pointer to an array
(c) pointerto a pointer
(d) none of these


44.Which of the following statements is incorrect

(a) typedef struct new{
int n1;
char n2;
} DATA;

(b) typedef struct {
int n3;
char *n4;}ICE;

(c) typedef union{ int n5;
float n6;} UDT;

(d) #typedef union {
int n7;
float n8;} TUDAT;