Monday, June 29, 2009

1.What does a static variable mean?

A static variable is a special variable that is stored in the data segment unlike the default automatic variable
that is stored in stack. A static variable can be initialised by using keyword static before variable name.
For Example: static int a = 5;
A static variable behaves in a different manner depending upon whether it is a global variable or a local
variable. A static global variable is same as an ordinary global variable except that it cannot be accessed by
other files in the same program / project even with the use of keyword extern. A static local variable is
different from local variable. It is initialised only once no matter how many times that function in which it
resides is called. It may be used as a count variable.
Example:
void count(void) {
static int count1 = 0;
int count2 = 0;
count1++;
count2++;
printf("\nValue of count1 is %d Value of count2 is %d", count1, count2);
}
//In Main function:
main() {
count();
count();
count();
}
Output would be:
Value of count1 is 1 Value of count2 is 1
Value of count1 is 2 Value of count2 is 1
Value of count1 is 3 Value of count2 is

Sunday, June 28, 2009

sql

1)
General Questions of SQL SERVER
What is RDBMS?
Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage. (Read More Here)
What are the properties of the Relational tables?
Relational tables have six properties:

Values are atomic.

Column values are of the same kind.

Each row is unique.

The sequence of columns is insignificant.

The sequence of rows is insignificant.

Each column must have a unique name.
What is Normalization?
Database normalization is a data design and organization process applied to data structures based on rules that help building relational databases. In relational database design, the process of organizing data to minimize redundancy is called normalization. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.
What is De‐normalization?
De‐normalization is the process of attempting to optimize the performance of a database by adding redundant data. It is sometimes necessary because current DBMSs implement the relational model poorly. A true relational DBMS would allow for a fully normalized database at the logical level, while providing physical storage of data that is tuned for high performance. De‐normalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access.
3 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What are different normalization forms?
1NF: Eliminate Repeating Groups
Make a separate table for each set of related attributes, and give each table a primary key. Each field contains at most one value from its attribute domain.
2NF: Eliminate Redundant Data
If an attribute depends on only part of a multi‐valued key, remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key
If attributes do not contribute to a description of the key, remove them to a separate table. All attributes must be directly dependent on the primary key. (Read More Here)
BCNF: Boyce‐Codd Normal Form
If there are non‐trivial dependencies between candidate key attributes, separate them out into distinct tables.
4NF: Isolate Independent Multiple Relationships
No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF: Isolate Semantically Related Multiple Relationships
There may be practical constrains on information that justify separating logically related many‐to‐many relationships.
ONF: Optimal Normal Form
A model limited to only simple (elemental) facts, as expressed in Object Role Model notation.
DKNF: Domain‐Key Normal Form
A model free from all modification anomalies is said to be in DKNF.
Remember, these normalization guidelines are cumulative. For a database to be in 3NF, it must first fulfill all the criteria of a 2NF and 1NF database.
What is Stored Procedure?
A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.
4 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is Trigger?
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS. Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event‐drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger. (Read More Here)
What is View?
A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T‐SQL select command and can come from one to many different base tables or even other views.
What is Index?
An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance.
What is a Linked Server?
Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T‐SQL Statements. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data. Stored Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server. (Read More Here)
5 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is Cursor?
Cursor is a database object used by applications to manipulate data in a set on a row‐by‐row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.
In order to work with a cursor we need to perform some steps in the following order:

Declare cursor

Open cursor

Fetch row from the cursor

Process fetched row

Close cursor
• Deallocate cursor (Read More Here)
What is Collation?
Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case sensitivity, accent marks, kana character types and character width. (Read More Here)
What is Difference between Function and Stored Procedure?
UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables. Inline UDF's can be thought of as views that take parameters and can be used in JOINs and other Rowset operations.
What is sub‐query? Explain properties of sub‐query?
Sub‐queries are often referred to as sub‐selects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub‐query is executed by enclosing it in a set of parentheses. Sub‐queries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword.
A subquery is a SELECT statement that is nested within another T‐SQL statement. A subquery SELECT statement if executed independently of the T‐SQL statement, in which it is nested, will return a resultset. Meaning a subquery SELECT statement can standalone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values, and can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T‐SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery can be used anywhere an expression can be used. (Read More Here)
6 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What are different Types of Join?
Cross Join
A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. The common example is when company wants to combine each product with a pricing table to analyze each product at each price.
Inner Join
A join that displays only the rows that have a match in both joined tables is known as inner Join. This is the default type of join in the Query and View Designer.
Outer Join
A join that includes rows even if they do not have related rows in the joined table is an Outer Join. You can create three different outer join to specify the unmatched rows to be included:

Left Outer Join: In Left Outer Join all rows in the first‐named table i.e. "left" table, which appears leftmost in the JOIN clause are included. Unmatched rows in the right table do not appear.

Right Outer Join: In Right Outer Join all rows in the second‐named table i.e. "right" table, which appears rightmost in the JOIN clause are included. Unmatched rows in the left table are not included.

Full Outer Join: In Full Outer Join all rows in all joined tables are included, whether they are matched or not.
Self Join
This is a particular case when one table joins to itself, with one or two aliases to avoid confusion. A self join can be of any type, as long as the joined tables are the same. A self join is rather unique in that it involves a relationship with only one table. The common example is when company has a hierarchal reporting structure whereby one member of staff reports to another. Self Join can be Outer Join or Inner Join. (Read More Here)
What are primary keys and foreign keys?
Primary keys are the unique identifiers for each row. They must contain unique values and cannot be null. Due to their importance in relational databases, Primary keys are the most fundamental of all keys and constraints. A table can have only one Primary key.
Foreign keys are both a method of ensuring data integrity and a manifestation of the relationship between tables.
7 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is User Defined Functions? What kind of User‐Defined Functions can be created?
User‐Defined Functions allow defining its own T‐SQL functions that can accept 0 or more parameters and return a single scalar data value or a table data type.
Different Kinds of User‐Defined Functions created are:
Scalar User‐Defined Function
A Scalar user‐defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user‐defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value.
Inline Table‐Value User‐Defined Function
An Inline Table‐Value user‐defined function returns a table data type and is an exceptional alternative to a view as the user‐defined function can pass parameters into a T‐SQL select command and in essence provide us with a parameterized, non‐updateable view of the underlying tables.
Multi‐statement Table‐Value User‐Defined Function
A Multi‐Statement Table‐Value user‐defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T‐SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a TSQL select command or a group of them gives us the capability to in essence create a parameterized, non‐updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user‐defined function, It can be used in the FROM clause of a T‐SQL command unlike the behavior found when using a stored procedure which can also return record sets. (Read Here For Example)
What is Identity?
Identity (or AutoNumber) is a column that automatically generates numeric values. A start and increment value can be set, but most DBA leave these at 1. A GUID column also generates numbers; the value of this cannot be controlled. Identity/GUID columns do not need to be indexed.
What is DataWarehousing?

Subject‐oriented, meaning that the data in the database is organized so that all the data elements relating to the same real‐world event or object are linked together;

Time‐variant, meaning that the changes to the data in the database are tracked and recorded so that reports can be produced showing changes over time;

Non‐volatile, meaning that data in the database is never over‐written or deleted, once committed, the data is static, read‐only, but retained for future reporting.

Integrated, meaning that the database contains data from most or all of an organization's operational applications, and that this data is made consistent.
8 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
2
)Common Questions Asked
Which TCP/IP port does SQL Server run on? How can it be changed?
SQL Server runs on port 1433. It can be changed from the Network Utility TCP/IP properties –> Port number, both on client and the server.
What are the difference between clustered and a non‐clustered index? (Read More Here)
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
A non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf node of a non clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.
What are the different index configurations a table can have?
A table can have one of the following index configurations:
• N
o indexes

A clustered index

A clustered index and many nonclustered indexes

A nonclustered index

Many nonclustered indexes
What are different types of Collation Sensitivity?
Case sensitivity ‐ A and a, B and b, etc.
Accent sensitivity ‐ a and á, o and ó, etc.
Kana Sensitivity ‐ When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.
Width sensitivity ‐ A single‐byte character (half‐width) and the same character represented as a double‐byte character (full‐width) are treated differently than it is width sensitive. (Read More Here)
What is OLTP (Online Transaction Processing)?
In OLTP ‐ online transaction processing systems relational database design use the discipline of data modeling and generally follow the Codd rules of data normalization in order to ensure absolute data integrity. Using these rules complex information is broken down into its most simple structures (a table) where all of the individual atomic level elements relate to each other and satisfy the normalization rules.
9 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What's the difference between a primary key and a unique key?
Both primary key and unique key enforces 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. (Read More Here)
What is difference between DELETE & TRUNCATE commands?
Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.
TRUNCATE

TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.

TRUNCATE 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 removes all rows from a table, but the table structure, its columns, constraints, indexes and so on, remains. The counter used by an identity for new rows is reset to the seed for the column.

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

TRUNCATE cannot be rolled back.

TRUNCATE is DDL Command.

TRUNCATE Resets identity of the table
DELETE

DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.

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.

DELETE Can be used with or without a WHERE clause

DELETE Activates Triggers.

DELETE can be rolled back.

DELETE is DML Command.

DELETE does not reset identity of the table.
(Read More Here)
When is the use of UPDATE_STATISTICS command?
This command is basically used when a large processing of data has occurred. If a large amount of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.
10 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
They specify a search condition for a group or an aggregate. But the difference is that HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query whereas WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. (Read More Here)
What are the properties and different Types of Sub‐Queries?
Properties of Sub‐Query

A sub‐query must be enclosed in the parenthesis.

A sub‐query must be put in the right hand of the comparison operator, and

A sub‐query cannot contain an ORDER‐BY clause.

A query can contain more than one sub‐query.
Types of Sub‐query

Single‐row sub‐query, where the sub‐query returns only one row.

Multiple‐row sub‐query, where the sub‐query returns multiple rows,. and

Multiple column sub‐query, where the sub‐query returns multiple columns
What is SQL Profiler?
SQL Profiler is a graphical tool that allows system administrators to monitor events in an instance of Microsoft SQL Server. You can capture and save data about each event to a file or SQL Server table to analyze later. For example, you can monitor a production environment to see which stored procedures are hampering performances by executing too slowly.
Use SQL Profiler to monitor only the events in which you are interested. If traces are becoming too large, you can filter them based on the information you want, so that only a subset of the event data is collected. Monitoring too many events adds overhead to the server and the monitoring process and can cause the trace file or trace table to grow very large, especially when the monitoring process takes place over a long period of time.
What are the authentication modes in SQL Server? How can it be changed?
Windows mode and Mixed Mode ‐ SQL & Windows.
To change authentication mode in SQL Server click Start, Programs, Microsoft SQL Server and click SQL Enterprise Manager to run SQL Enterprise Manager from the Microsoft SQL Server program group. Select the server then from the Tools menu select SQL Server Configuration Properties, and choose the Security page.
11 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
Which command using Query Analyzer will give you the version of SQL server and operating system?
SELECT SERVERPROPERTY ('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition').
What is SQL Server Agent?
SQL Server agent plays an important role in the day‐to‐day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full‐function scheduling engine, which allows you to schedule your own jobs and scripts. (Read More Here)
Can a stored procedure call itself or recursive stored procedure? How much level SP nesting is possible?
Yes. Because Transact‐SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels.
What is Log Shipping?
Log shipping is the process of automating the backup of database and transaction log files on a production SQL server, and then restoring them onto a standby server. Enterprise Editions only supports log shipping. In log shipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and can be used this as the Disaster Recovery plan. The key feature of log shipping is that it will automatically backup transaction logs throughout the day and automatically restore them on the standby server at defined interval.
Name 3 ways to get an accurate count of the number of records in a table?
SELECT * FROM table1
SELECT COUNT(*) FROM table1
SELECT rows FROM sysindexes WHERE id = OBJECT_ID(table1) AND indid < 2
What does it mean to have QUOTED_IDENTIFIER ON? What are the implications of having it OFF?
When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks, and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact‐SQL rules for identifiers. (Read More Here)
12 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is the difference between a Local and a Global temporary table?
A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.
A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.
What is the STUFF function and how does it differ from the REPLACE function?
STUFF function is used to overwrite existing characters. Using this syntax, STUFF (string_expression, start, length, replacement_characters), string_expression is the string that will have characters substituted, start is the starting position, length is the number of characters in the string that are substituted, and replacement_characters are the new characters interjected into the string. REPLACE function to replace existing characters of all occurrences. Using the syntax REPLACE (string_expression, search_string, replacement_string), where every incidence of search_string found in the string_expression will be replaced with replacement_string.
What is PRIMARY KEY?
A PRIMARY KEY constraint is a unique identifier for a row within a database table. Every table should have a primary key constraint to uniquely identify each row and only one primary key constraint can be created for each table. The primary key constraints are used to enforce entity integrity.
What is UNIQUE KEY constraint?
A UNIQUE constraint enforces the uniqueness of the values in a set of columns, so no duplicate values are entered. The unique key constraints are used to enforce entity integrity as the primary key constraints.
What is FOREIGN KEY?
A FOREIGN KEY constraint prevents any actions that would destroy links between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.
What is CHECK Constraint?
A CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity. (Read More Here)
13 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is NOT NULL Constraint?
A NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.
(Read More Here)
How to get @@ERROR and @@ROWCOUNT at the same time?
If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset. And if @@Recordcount is checked before the error‐checking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR
What is a Scheduled Jobs or What is a Scheduled Tasks?
Scheduled tasks let user automate processes that run on regular or predictable cycles. User can schedule administrative tasks, such as cube processing, to run during times of slow business activity. User can also determine the order in which tasks run by creating job steps within a SQL Server Agent job. E.g. back up database, Update Stats of Tables. Job steps give user control over flow of execution. If one job fails, user can configure SQL Server Agent to continue to run the remaining tasks or to stop execution.
What are the advantages of using Stored Procedures?

Stored procedure can reduced network traffic and latency, boosting application performance.

Stored procedure execution plans can be reused, staying cached in SQL Server's memory, reducing server overhead.

Stored procedures help promote code reuse.

Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients.

Stored procedures provide better security to your data.
What is a table called, if it has neither Cluster nor Non‐cluster Index? What is it used for?
Unindexed table or Heap. Microsoft Press Books and Book on Line (BOL) refers it as Heap. A heap is a table that does not have a clustered index and, therefore, the pages are not linked by pointers. The IAM pages are the only structures that link the pages in a table together. Unindexed tables are good for fast storing of data. Many times it is better to drop all indexes from table and then do bulk of inserts and to restore those indexes after that.
Can SQL Servers linked to other servers like Oracle?
SQL Server can be linked to any server provided it has OLE‐DB provider from Microsoft to allow a link. E.g. Oracle has an OLE‐DB provider for oracle that Microsoft provides to add it as linked server to SQL Server group
14 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is BCP? When does it used?
BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the structures same as source to destination. BULK INSERT command helps to import a data file into a database table or view in a user‐specified format.
What command do we use to rename a db, a table and a column?
To rename db
sp_renamedb ‘oldname’ , ‘newname’
If someone is using db it will not accept sp_renmaedb. In that case first bring db to single user using sp_dboptions. Use sp_renamedb to rename database. Use sp_dboptions to bring database to multi user mode.
E.g.
USE master;
GO
EXEC sp_dboption AdventureWorks, 'Single User', True
GO
EXEC sp_renamedb 'AdventureWorks', 'AdventureWorks_New'
GO
EXEC sp_dboption AdventureWorks, 'Single User', False
GO
To rename Table
We can change the table name using sp_rename as follows,
sp_rename ‘oldTableName’ ‘newTableName’
E.g.
SP_RENAME ‘Table_First’, ‘Table_Last’ GO
To rename Column
The script for renaming any column :
sp_rename ‘TableName.[OldcolumnName]’, ‘NewColumnName’, ‘Column’
E.g.
sp_RENAME ‘Table_First.Name’, ‘NameChange’ , ‘COLUMN’ GO
15 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What are sp_configure commands and set commands?
Use sp_configure to display or change server‐level settings. To change database‐level settings, use ALTER DATABASE. To change settings that affect only the current user session, use the SET statement.
E.g.
sp_CONFIGURE ’show advanced’, 0 GO RECONFIGURE GO sp_CONFIGURE GO
You can run following command and check advance global configuration settings.
sp_CONFIGURE ’show advanced’, 1 GO RECONFIGURE GO sp_CONFIGURE GO
(Read More Here)
How to 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.
What is an execution plan? When would you use it? How would you view the execution plan?
An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL Server query optimizer for a stored procedure or ad‐hoc query and is a very useful tool for a developer to understand the performance characteristics of a query or stored procedure since the plan is the one that SQL Server will place in its cache and use to execute the stored procedure or query. From within Query Analyzer is an option called "Show Execution Plan" (located on the Query drop‐down menu). If this option is turned on it will display query execution plan in separate window when query is ran again.
16 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
3
)Questions of SQL SERVER 2008
What are the basic functions for master, msdb, model, tempdb and resource databases?
The master database holds information for all databases located on the SQL Server instance and is theglue that holds the engine together. Because SQL Server cannot start without a functioning masterdatabase, you must administer this database with care.
The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
The tempdb holds temporary objects such as global and local temporary tables and stored procedures.
The model is essentially a template database used in the creation of any new user database created in the instance.
The resoure Database is a read‐only database that contains all the system objects that are included with SQL Server. SQL Server system objects, such as sys.objects, are physically persisted in the Resource database, but they logically appear in the sys schema of every database. The Resource database does not contain user data or user metadata.
What is Service Broker?
Service Broker is a message‐queuing technology in SQL Server that allows developers to integrate SQL Server fully into distributed applications. Service Broker is feature which provides facility to SQL Server to send an asynchronous, transactional message. it allows a database to send a message to another database without waiting for the response, so the application will continue to function if the remote database is temporarily unavailable. (Read More Here)
Where SQL server user names and passwords are stored in SQL server?
They get stored in System Catalog Views sys.server_principals and sys.sql_logins.
What is Policy Management?
Policy Management in SQL SERVER 2008 allows you to define and enforce policies for configuring and managing SQL Server across the enterprise. Policy‐Based Management is configured in SQL Server Management Studio (SSMS). Navigate to the Object Explorer and expand the Management node and the Policy Management node; you will see the Policies, Conditions, and Facets nodes. (Read More Here)
17 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is Replication and Database Mirroring?
Database mirroring can be used with replication to provide availability for the publication database. Database mirroring involves two copies of a single database that typically reside on different computers. At any given time, only one copy of the database is currently available to clients which are known as the principal database. Updates made by clients to the principal database are applied on the other copy of the database, known as the mirror database. Mirroring involves applying the transaction log from every insertion, update, or deletion made on the principal database onto the mirror database.
What are Sparse Columns?
A sparse column is another tool used to reduce the amount of physical storage used in a database. They are the ordinary columns that have an optimized storage for null values. Sparse columns reduce the space requirements for null values at the cost of more overhead to retrieve nonnull values. (Read More Here)
What does TOP Operator Do?
The TOP operator is used to specify the number of rows to be returned by a query. The TOP operator has new addition in SQL SERVER 2008 that it accepts variables as well as literal values and can be used with INSERT, UPDATE, and DELETES statements.
What is CTE?
CTE is an abbreviation Common Table Expression. A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query. (Read More Here)
What is MERGE Statement? MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once. (Read More Here)
What is Filtered Index?
Filtered Index is used to index a portion of rows in a table that means it applies filter on INDEX which improves query performance, reduce index maintenance costs, and reduce index storage costs compared with full‐table indexes. When we see an Index created with some where clause then that is actually a FILTERED INDEX.
18 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
Which are new data types introduced in SQL SERVER 2008?
The GEOMETRY Type: The GEOMETRY data type is a system .NET common language runtime (CLR) data type in SQL Server. This type represents data in a two‐dimensional Euclidean coordinate system.
The GEOGRAPHY Type: The GEOGRAPHY datatype’s functions are the same as with GEOMETRY. The difference between the two is that when you specify GEOGRAPHY, you are usually specifying points in terms of latitude and longitude.
New Date and Time Datatypes: SQL Server 2008 introduces four new datatypes related to date and time: DATE, TIME, DATETIMEOFFSET, and DATETIME2.
• D
ATE: The new DATE type just stores the date itself. It is based on the Gregorian calendar and handles years from 1 to 9999.

TIME: The new TIME (n) type stores time with a range of 00:00:00.0000000 through 23:59:59.9999999. The precision is allowed with this type. TIME supports seconds down to 100 nanoseconds. The n in TIME (n) defines this level of fractional second precision, from 0 to 7 digits of precision.

The DATETIMEOFFSET Type: DATETIMEOFFSET (n) is the time‐zone‐aware version of a datetime datatype. The name will appear less odd when you consider what it really is: a date + a time + a time‐zone offset. The offset is based on how far behind or ahead you are from Coordinated Universal Time (UTC) time.

The DATETIME2 Type: It is an extension of the datetime type in earlier versions of SQL Server. This new datatype has a date range covering dates from January 1 of year 1 through December 31 of year 9999. This is a definite improvement over the 1753 lower boundary of the datetime datatype. DATETIME2 not only includes the larger date range, but also has a timestamp and the same fractional precision that TIME type provides
What are the Advantages of using CTE?

Using CTE improves the readability and makes maintenance of complex queries easy.

The query can be divided into separate, simple, logical building blocks which can be then used to build more complex CTEs until final result set is generated.

CTE can be defined in functions, stored procedures, triggers or even views.

After a CTE is defined, it can be used as a Table or a View and can SELECT, INSERT, UPDATE or DELETE Data.
19 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
How can we rewrite sub‐queries into simple select statements or with joins?
Yes we can write using Common Table Expression (CTE). A Common Table Expression (CTE) is an expression that can be thought of as a temporary result set which is defined within the execution of a single SQL statement. A CTE is similar to a derived table in that it is not stored as an object and lasts only for the duration of the query.
E.g.
USE AdventureWorks GO WITH EmployeeDepartment_CTE AS ( SELECT EmployeeID,DepartmentID,ShiftID FROM HumanResources.EmployeeDepartmentHistory ) SELECT ecte.EmployeeId,ed.DepartmentID, ed.Name,ecte.ShiftID FROM HumanResources.Department ed INNER JOIN EmployeeDepartment_CTE ecte ON ecte.DepartmentID = ed.DepartmentID GO
What is CLR?
In SQL Server 2008, SQL Server objects such as user‐defined functions can be created using such CLR languages. This CLR language support extends not only to user‐defined functions, but also to stored procedures and triggers. You can develop such CLR add‐ons to SQL Server using Visual Studio 2008. (Read More Here)
What are synonyms?
Synonyms give you the ability to provide alternate names for database objects. You can alias object names; for example, using the Employee table as Emp. You can also shorten names. This is especially useful when dealing with three and four part names; for example, shortening server.database.owner.object to object. (Read More Here)
What is LINQ?
Language Integrated Query (LINQ) adds the ability to query objects using .NET languages. The LINQ to SQL object/relational mapping (O/RM) framework provides the following basic features:

Tools to create classes (usually called entities) mapped to database tables

Compatibility with LINQ’s standard query operations

The DataContext class, with features such as entity record monitoring, automatic SQL statement generation, record concurrency detection, and much more
20 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is Isolation Levels?
Transactions specify an isolation level that defines the degree to which one transaction must be isolated from resource or data modifications made by other transactions. Isolation levels are described in terms of which concurrency side‐effects, such as dirty reads or phantom reads, are allowed.
Transaction isolation levels control:

Whether locks are taken when data is read, and what type of locks are reque• How long th

Whether a read operation referencing

Blocks until the exclusive lock on the row is freed.

Retrieves the committed version of the row that
s
tatement or transaction started. • Reads the uncommitted data mod
EXCEPT clause is similar to MINU
returns all rows in the first query that are not returned in the second query. Each SQL statement within the EXCEPT query and MINUS query must have the same number of fieldsin the result sets with similar data types. (Read More Here)
W
XPath uses a set
expression that you’ll use is the location path expression, which returns back a set ofcalled a node set. XPath can use both an unabbreviated and an abbreviated syntax. The following is the unabbreviated syntax for a location path:
Using the NOLOCK
improve concurrency on a busy system. When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is read. The result is a Dirty Read, which meansthat another process could be updating the data at the exact time you are reading it. Therare no guarantees that your query will retrieve the most recent data. The advantage to performance is that your reading of data will not block updates from taking place, and updates will not block your reading of data. SELECT statements take Shared (Read) lockThis means that multiple SELECT statements are allowed simultaneous access, but other processes are blocked from modifying the data. The updates will queue until all the readshave completed, and reads requested after the update will wait for the updates to complete. The result to your system is delay (blocking). (Read More Here)
21 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
H
SQL Server now supports the use of TRY...CATCH con
handling. TRY...CATCH lets us build error handling at the level we need, in the way wto, by setting a region where if any error occurs, it will break out of the region and head to an error handler. The basic structure is as follows: BEGIN TRY

END TRY
BEGIN CA

END CAT
f
error can be dealt.
RaiseError generates an
RAISERROR can either reference a user‐defined message stored in the sys.messages catalogview or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct. (Read More Here)
Master database is system databas
configuration. When SQL Server 2005 is installed it usually creates master, model, msdb,tempdb resource and distribution system database by default. Only Master database is thone which is absolutely must have database. Without Master database SQL Server cannot be started. This is the reason it is extremely important to backup Master database.
rebuild the system databases. This procedure is most often used to rebuild the master database for a corrupted installation of SQL Server.
W
The xml data type lets yo
An XML fragment is an XML instance that is missing a single top‐level element. You can create columns and variables of the xml type and store XML instances in them. The xml data type and associated methods help integrate XML into the relational framework of SServer.
22 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
What is Data Compression?
pression comes in two flavors:
• Row Compression
Row Compression
Row compression changes the format of physical storage of data. It minimize the metadata
In SQL SERVE 2008 Data Com

Page Compression
(column information, length, offsets etc) associated with each record. Numeric data types and fixed length strings are stored in variable‐length storage format, just like Varchar. (Read More Here)
uses the following techniques to compress data:

Prefix Compression.
T
hese prefixes are saved in compression information headers (CI) which resides after page header. A reference number is assigned to these prefixes and that reference number is replaced where ever those prefixes are being used.
in CI. The main difference between prefix and dictionary compression is that prefix is only restricted to one column while dictionary is applicable to the complete page.
The Transact‐SQL programming la
Console Commands for SQL Server. DBCC commands are used to perform following tasks.

Tasks that gather and display various types of inform

Validation operations on a database, table, index, catalog, fi
a
llocation of database pages. • Miscellaneous tasks such as en
m
emory. (Read Mor
23 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
H
Run following query in Query Editor.
USE ;
GO SELE ,name AS table_name FROM sys.tables WHERE OBJECTPROORDER BY schema_name, table_name; GO
y
There are multiple ways to do this.
1) “Detach Database” from one ser
2
) Manually script all the objects using SSMS and run the script on new server.
3
) Use Wizard of SSMS. (Read More Here)
There are multiple ways to do this.
1
Th
is method is used when
be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. ELECT INTO
This method
data from one table is to be inserted into newly created table from another table. New table is created with same data types as selected columns. (Read More Here)
Catalog views return info
Views are the most general interface to the catalog metadata and provide the most efficient way to obtain, transform, and present customized forms of this information. All user‐available catalog metadata is exposed through catalog views.
W
A Pivot Table can automatica
spreadsheet and create a second table displaying the summarized data. The PIVOT operator turns the values of a specified column into column names, effectively rotating a table.
U
24 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
W
Filestream allows yo
integrated within the database. It enables SQL Server based applications to store unstructured data such as documents, images, audios, videos etc. in the file system. FILESTREAMbasically integrates the SQL Srver Database Engine with New Technology File System (NTFS); it basically stores the data in varbinary (max) data type. Using this data type, the unstructured data is stored in the NTFS file system and the SQL Server Database Engine manages the link between the Filestream column and the actual file located in the NTFS. Using Transact SQL statements users can insert, update, delete and select the data stored in FILESTREAM enabled tables.
W
A dirty read occurs w
incorrect or unedited data. Suppose, A has changed a row, but has not committed the changes. B reads the uncommitted data but his view of the data may be wrong so that is Dirty Read.
W
sqlcmd is enhanced
other two options. In other words sqlcmd is better replacement of isql (which will be deprecated eventually) and osql (not included in SQL Server 2005 RTM). sqlcmd can work two modes ‐ i) BATCH and ii) interactive modes. (Read More)
W
Aggregate functions perform a
Aggregate functions ignore NULL values except COUNT function. HAVING clause is used, along with GROUP BY, for filtering query using aggregate values. Following functions are aggregate functions.
AVG, M CHECKSUM_AGG, SUM, COUNT, STDEV, COU
VAR, MAX, VARP (Read More Here )
TABLESAMPLE allows you to extract a sThe rows retrieved are random and they are not in any order. This sampling can be basedon a percentage of number of rows. You can use TABLESAMPLE when only a sampling of rows is necessary for the application instead of a full result set. (Read More Here)
ROW_NUMBER() returns athe result set. This is only a number used in the context of the result set, if the result changes, the ROW_NUMBER() will change.
25 © Copyright 2000-2008 Pinal Dave. All Rights Reserved. SQLAuthority.com
W
Ranking functions return a rank
functions are non‐deterministic. Different Ranking functions are:
Returns the sequential number of a row within a partition of a result setthe first row in each partition.
Returns the rank of each row within the partition of a result se
Returns the rank of rows within the partition of a result set, without a(Read More Here )
The UNIJOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
The UNION ALLall values.
rows, instead it just pulls all rows from all tables fitting your query specifics and combines them into a table. (Read More Here)
has following types of index pages or nodes:
on
ly one. • branch no
no
des which can be two or more. • leaf nodes A leaf node contains in
no
des which can be many.

sql own

1.What are the different types of joins?
Ans:- 1. Inner join 2. Outer join 3. Cross join
1. Inner join: inner join is the default type of join, it will producesses the result set, which contains matched rows only. Syntax: select * from table1table2
2. Outer join: outer join produces the results, which contains matched rows and unmatched rows. Here we have three types of joins,
1.left outer join 2.right outer join 3.full outer join left outer join:
left outer join producesses the results, which contains all the rows from left table and matched rows from right table. Syntax: select * from table1table2
2. right outer join: right outer join producesses the resultset, which contains all the rows from right table and matched rows from left table. Syntax:select * from table1table2 full outer join: full outer join producesses the resultset, which contains all the rows from left table and all the rows from right table. Syntax:select * from table1table2
3.cross join: a join without having any condition is known as cross join, in cross join every row in first table is joins with every row in second table. Syntax: select * from table1table2
self join: a join joins withitself is called self join working with self joins we use alias tables.
2.What is the difference between procedure and function?
Ans: 1. Function is mainly used in the case where it must return a value. Where as a procedure may or may not return a value or may return more than one value using the OUT parameter.
2. Function can be called from SQL statements where as procedure can not be called from the sql statements
3. Functions are normally used for computations where as procedures are normally used for executing business logic.
4. You can have DML (insert,update, delete) statements in a function. But, you cannot call such a function in a SQL query.
5. Function returns 1 value only. Procedure can return multiple values (max 1024).
6.Stored Procedure: supports deferred name resolution. Example while writing a stored procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime throws error Function wont support deferred name resolution.
7.Stored procedure returns always integer value by default zero. where as function return type could be scalar or table or table values
8. Stored procedure is precompiled execution plan where as functions are not.
9.A procedure may modify an object where a function can only return a value The RETURN statement immediately completes the execution of a subprogram and returns control to the caller.
3 What is group by function?
Ans: The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
4.What is the difference between a where clause and having clause?
Ans:1. Having clause is usually used with Group By clause although it can be used without it too.
2. 'Having' is just an additional filter to 'Where' clause.
3. 'Where' clause applies to the individual rows whereas 'Having' clause is used to test some condition on the group(usually aggregate methods) rather than on individual rows.
5.What are indexes. Advantages of indexes
Ans:Index in sql is created on existing tables to retrieve the rows quickly.
When there are thousands of records in a table, retrieving information will take a long time. Therefore indexes are created on columns which are accessed frequently, so that the information can be retrieved quickly. Indexes can be created on a single column or a group of columns. When a index is created, it first sorts the data and then it assigns a ROWID for each row.
Syntax to create Index:
CREATE INDEX index_name
ON table_name (column_name1,column_name2...);
Syntax to create SQL unique Index:
CREATE UNIQUE INDEX index_name
ON table_name (column_name1,column_name2...);
6.Triggers, how many triggers are available
Ans Trigger is fired when DML statement executed
Type- In database triggers
(Before, after)
(row level, statement level)
(insert,update,delete)
7.What does “i” represent in Oracle8i / 9i ans internet
8,Difference between primary key and foreign key
ans Primary key - Primary key means main key def:- A primary key is one which uniquely identifies a row of a table. this key does not allow null values and also does not allow duplicate values. for ex,
empno empname salary
1 firoz 35000
2 basha 34000
3 chintoo 40000
it will not the values as follows:
1 firoz 35000
1 basha 34000
chintoo 35000
Unique key - single and main key A unique is one which uniquely identifies a row of a table, but there is a difference like it will not allow duplicate values and it will any number of allow null values(In oracle).it allows only a single null value(In sql server 2000)Both will function in a similar way but a slight difference will be there. So, decalaring it as a primary key is the best one.
foreign key - a foreign key is one which will refer to a primary key of another table for ex,
emp_table dept_table
empno empname salary deptno deptno deptname
In the above relation, deptno is there in emp_table which is a primary key of dept_table. that means, deptno is refering the dept_table.
9.Can we have null in a primary key Ans no
10.Can we have null in a foreign key, if yes , how many in a table Ans no
11. What are cursors
Ans There are two types of cursors, Implicit Cursor and Explicit Cursor. PL/SQL uses Implicit Cursors for queries. User defined cursors are called Explicit Cursors. They can be declared and used.
12.Give example of how SQL tuning can be done
ans
13. What is normalization
ans
14.Difference between delete and truncate
ans
15.What are views, snapshots and synonyms?
Ans a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables. Synonyms- CREATE SYNONYM [ schema_name_1. ] synonym_name FOR < object > or table synonyms alternate name of table
16.What value one gets for “Select * from dual”
Ans dual is a table which is created by oracle along with the data dictionary. It consists of exactly one column whose name is dummy and one record. The value of that record is X.
select * from dual;
D
-
X
17.Have you used Decode function? Give an example
Ans the decode function to compare two dates (ie: date1 and date2), where if date1 > date2, the decode function should return date2. Otherwise, the decode function should return date1.
Answer: To accomplish this, use the decode function as follows: decode((date1 - date2) - abs(date1 - date2), 0, date2, date1)
The formula below would equal 0, if date1 is greater than date2:(date1 - date2) - abs(date1 - date2)
18.Datatypes supported by Oracle
Ans char varchar integer
19.Can you explain how do index retrieve records from database
Ans SELECT ProductID, ProductName, UnitPrice FROM Products WHERE (UnitPrice > 12.5) AND (UnitPrice < 14)


20. What is commit and rollback
Ans commit permanent save but rollback u can undo it.
21. What is the difference between these 2 queries
o Select count(*) from table
o Select count(1) from table
Ans count1 means count(columnfirst)count2- secand column)
22. Difference between NODATAFOUND and %NOFOUND
23.Difference between IN and EXISTS? Which is faster in execution?
Ans SQL> select count(*) from emp_master where emp_nbr not in ( select mgr_nbr from emp_master );
COUNT(*)
———-
0
This means that everyone is a manager…hmmm, I wonder whether anything ever gets done in that case
NOT EXISTS
SQL> select count(*) from emp_master T1 where not exists ( select 1 from emp_master T2 where t2.mgr_nbr = t1.emp_nbr );
COUNT(*)
———-
9
Now there are 9 people who are not managers. So, you can clearly see the difference that NULL values make and since NULL != NULL in SQL, the NOT IN clause does not return any records back. (in MS SQL Server, depending upon the ANSI NULLS setting, the behavior can be altered but this post only talks about the behavior that is same in Oracle, DB2 LUW and MS SQL Server).
Performance implications:
When using “NOT IN”, the query performs nested full table scans, whereas for “NOT EXISTS”, query can use an index within the sub-query.
24. What is referential integrity
Ans Referential Integrity is the process of automatically maintaining the correctness of your data when modifications are made to fields which are related to other fields in other tables. Having the rules of referential integrity enforced on your database will keep related records from becoming orphaned by its parent records, and can also help to enforce your systems business rules. There are two basic rules of Referential Integrity. The first is the Delete Cascade. This will delete all child records when a parent record is deleted. The second rule is the Update Cascade. This rule updates all child records to reflect the update made to the parent.
25.What are constraints
Ans Data integrity allows to define certain data quality requirements that the data in the database needs to meet. If a user tries to insert data that doesn't meet these requirements, Oracle will not allow so.
There are five integrity constraints in Oracle.
Not Null:-A column in a table can be specified not null. It's not possible to insert a null in such a column. The default is null.
Unique Key-The unique constraint doesn't allow duplicate values in a column. If the unique constraint encompasses two or more columns, no two equal combinations are allowed.
Primary Key-On a technical level, a primary key combines a unique and a not null constraint. Additionally, a table can have at most one primary key. After creating a primary key, it can be referenced by a foreign key.
Foreign Key-A foreign key constraint (also called referential integrity constraint) on a column ensures that the value in that column is found in the primary key of another table.
If a table has a foreign key that references a table, that referenced table can be dropped with a drop table .. cascade constraints.
It is not possible to establish a foreign key on a global temporary table. If tried, Oracle issues a ORA-14455: attempt to create referential integrity constraint on temporary table.
Check-A check constraint allows to state a minimum requirement for the value in a column. If more complicated requirements are desired, an insert trigger must be used.
The following table allows only numbers that are between 0 and 100 in the column a;
26. What are transaction isolation levels?
Ans-
27.What is DDL, DML ? How are they different?
28, What are different types of joins in SQL?
29.How do you select unique rows using SQL?
Ans SELECT DISTINCT class FROM student
30. What is the difference between DELETE and TRUNCATE ?
TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is released back to the server. DELETE is a DML command and can be rolled back. Both commands accomplish identical tasks (removing all data from a table) but TRUNCATE is much faster.
31.What is the difference between a "where" clause and a "having" clause?
Ans HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.
HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, AVING behaves like a WHERE clause.
32.What is the difference between "procedure" and "function"?
33.What is the difference between "translate" and "replace" ?
34. How to remove duplicate records from a table?
35.What is a "trigger"?
36.What is the difference between "translate" and "replace"?
37.What is a VIEW?
38.What is the difference among "dropping a table", "truncating a table"
and "deleting all records" from a table
39.Explain new feature of 9i Database ? Explain new feature of 10g Database ?
40.How to use DECODE function?
41.What is “Group by” clause?
42.What are cursors and what are the situations you will use them?
43.What default packages are provided by Oracle?
44.How do you debug a oracle procedure /function?
45.How many triggers are available?
46.How are procedures executed?
47How do you convert a date to a string?
48What is an aggregate function?
49What is the dual table?
50What are cursors? Distinguish between implicit and explict cursors?
51Explain how cursors are used by Oracle?
52What is PL/SQL? Describe the block structure of PL/SQL?
53What is a nested subquery?
54What are the various types of queries ?
55Which of the following is not a schema object : Index, table, public synonym, trigger and package ?
56What is dynamic sql in oracle?
57What is the difference between a package, procedure and function
58What is the difference between delete, drop and truncating a table
59How many triggers are supported in Oracle
60Are you aware of FLASHBACK concept ? What is it?
61Describe oracle’s logical and physical structure?
62What is data dictionary
63What is the use of control files
64How would store XML data in table ? What data type would be used for the columns?
65Difference between post and commit?
66Difference between commit and rollback?
67What are savepoints?
68Difference between a View and Synonym
69How would you fetch system date from oracle
70What is the difference between primary key, unique key, foreign key?
71What is the difference between NO DATA FOUND and %NOTFOUND
72What is cursor for loop
73What are cursor attributes
74What will you use in Query : IN or EXISTS? Why
75Explain the difference between a data block, an extent and a segment.
76What's the difference between logical and physical I/O?
78What is an anonymous block?
79What is a PL/SQL collection?
80How can you tell if an UPDATE updated no rows
81How can you tell if a SELECT returned no rows

DB concepts:
Physical Database Structure

1. Datafiles
2. Redo log files
3. Control files.

Logical Structures

1. TableSpaces
2. DB Schema Objects.

Segments,Extents and Data Blocks

Oracle background processes

1. PMON
2.SMON
3.DBWR
4.LGWR
5.ARCH
6.RECO

A synonym is an alias for a table, view, sequence, create public synonyms that make the base schema object available for general, system-wide use by any database user.

Indexes are created to increase the performance of data retrieval


--------------------------------------------------------------------------------------------------------dbms--------------------------------------------------------------------------------------------------------------------
C/C++ Programming interview questions and answers
What is encapsulation?
Containing and hiding information about an object, such as internal data structures and code. Encapsulation isolates the internal complexity of an object's operation from the rest of the application. For example, a client component asking for net revenue from a business object need not know the data's origin.
What is inheritance?
Inheritance allows one class to reuse the state and behavior of another class. The derived class inherits the properties and method implementations of the base class and extends it by overriding methods and adding additional properties and methods.
What is Polymorphism??
Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
You can use implementation inheritance to achieve polymorphism in languages such as C++ and Java.
Base class object's pointer can invoke methods in derived class objects.
You can also achieve polymorphism in C++ by function overloading and operator overloading.
What is constructor or ctor?
Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is different from other methods in a class.
What is destructor?
Destructor usually deletes any extra resources allocated by the object.
What is default constructor?
Constructor with no arguments or all the arguments has default values.
What is copy constructor?
Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you.
for example:
Boo Obj1(10); // calling Boo constructor
Boo Obj2(Obj1); // calling boo copy constructor
Boo Obj2 = Obj1;// calling boo copy constructor
When are copy constructors called?
Copy constructors are called in following cases:
a) when a function returns an object of that class by value
b) when the object of that class is passed by value as an argument to a function
c) when you construct an object based on another object of the same class
d) When compiler generates a temporary object
What is assignment operator?
Default assignment operator handles assigning one object to another of the same class. Member to member copy (shallow copy)
What are all the implicit member functions of the class? Or what are all the functions which compiler implements for us if we don't define one.??
default ctor
copy ctor
assignment operator
default destructor
address operator
What is conversion constructor?
constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion.
for example:
class Boo
{
public:
Boo( int i );
};
Boo BooObject = 10 ; // assigning int 10 Boo object
What is conversion operator??
class can have a public method for specific data type conversions.
for example:
class Boo
{
double value;
public:
Boo(int i )
operator double()
{
return value;
}
};
Boo BooObject;
double i = BooObject; // assigning object to variable i of type double. now conversion operator gets called to assign the value.
What is diff between malloc()/free() and new/delete?
malloc allocates memory for object in heap but doesn't invoke object's constructor to initiallize the object.
new allocates memory and also invokes constructor to initialize the object.
malloc() and free() do not support object semantics
Does not construct and destruct objects
string * ptr = (string *)(malloc (sizeof(string)))
Are not safe
Does not calculate the size of the objects that it construct
Returns a pointer to void
int *p = (int *) (malloc(sizeof(int)));
int *p = new int;
Are not extensible
new and delete can be overloaded in a class
"delete" first calls the object's termination routine (i.e. its destructor) and then releases the space the object occupied on the heap memory. If an array of objects was created using new, then delete must be told that it is dealing with an array by preceding the name with an empty []:-
Int_t *my_ints = new Int_t[10];
...
delete []my_ints;
what is the diff between "new" and "operator new" ?

"operator new" works like malloc.
What is difference between template and macro??
There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking.
If macro parameter has a postincremented variable ( like c++ ), the increment is performed two times.
Because macros are expanded by the preprocessor, compiler error messages will refer to the expanded macro, rather than the macro definition itself. Also, the macro will show up in expanded form during debugging.
for example:
Macro:
#define min(i, j) (i < j ? i : j)
template:
template
T min (T i, T j)
{
return i < j ? i : j;
}


What are C++ storage classes?
auto
register
static
extern
auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definition. They are not visible outside that block
register: a type of auto variable. a suggestion to the compiler to use a CPU register for performance
static: a variable that is known only in the function that contains its definition but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution
extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code file. It can be visible outside the file where it is defined.
What are storage qualifiers in C++ ?
They are..
const
volatile
mutable
Const keyword indicates that memory once initialized, should not be altered by a program.
volatile keyword indicates that the value in the memory location can be altered even though nothing in the program
code modifies the contents. for example if you have a pointer to hardware location that contains the time, where hardware changes the value of this pointer variable and not the program. The intent of this keyword to improve the optimization ability of the compiler.
mutable keyword indicates that particular member of a structure or class can be altered even if a particular structure variable, class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { "Satish Shetty", 1000 }; //initlized by complier
strcpy ( MyStruct.name, "Shilpa Shetty"); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed
What is reference ??
reference is a name that acts as an alias, or alternative name, for a previously defined variable or an object.
prepending variable with "&" symbol makes it as reference.
for example:
int a;
int &b = a;

What is passing by reference?
Method of passing arguments to a function which takes parameter of type reference.
for example:
void swap( int & x, int & y )
{
int temp = x;
x = y;
y = temp;
}
int a=2, b=3;
swap( a, b );
Basically, inside the function there won't be any copy of the arguments "x" and "y" instead they refer to original variables a and b. so no extra memory needed to pass arguments and it is more efficient.
When do use "const" reference arguments in function?
a) Using const protects you against programming errors that inadvertently alter data.
b) Using const allows function to process both const and non-const actual arguments, while a function without const in the prototype can only accept non constant arguments.
c) Using a const reference allows the function to generate and use a temporary variable appropriately.

When are temporary variables created by C++ compiler?
Provided that function parameter is a "const reference", compiler generates temporary variable in following 2 ways.
a) The actual argument is the correct type, but it isn't Lvalue
double Cube(const double & num)
{
num = num * num * num;
return num;
}
double temp = 2.0;
double value = cube(3.0 + temp); // argument is a expression and not a Lvalue;
b) The actual argument is of the wrong type, but of a type that can be converted to the correct type
long temp = 3L;
double value = cuberoot ( temp); // long to double conversion

What is virtual function?
When derived class overrides the base class method by redefining the same function, then if client wants to access redefined the method from derived class through a pointer from base class object, then you must define this function in base class as virtual function.
class parent
{
void Show()
{
cout << "i'm parent" << endl;
}
};
class child: public parent
{
void Show()
{
cout << "i'm child" << endl;
}
};
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls parent->show() i
now we goto virtual world...
class parent
{
virtual void Show()
{
cout << "i'm parent" << endl;
}
};
class child: public parent
{
void Show()
{
cout << "i'm child" << endl;
}
};
parent * parent_object_ptr = new child;
parent_object_ptr->show() // calls child->show()

What is pure virtual function? or what is abstract class?
When you define only function prototype in a base class without implementation and do the complete implementation in derived class. This base class is called abstract class and client won't able to instantiate an object using this base class.
You can make a pure virtual function or abstract class this way..
class Boo
{
void foo() = 0;
}
Boo MyBoo; // compilation error

What is Memory alignment??
The term alignment primarily means the tendency of an address pointer value to be a multiple of some power of two. So a pointer with two byte alignment has a zero in the least significant bit. And a pointer with four byte alignment has a zero in both the two least significant bits. And so on. More alignment means a longer sequence of zero bits in the lowest bits of a pointer.
What problem does the namespace feature solve?
Multiple providers of libraries might use common global identifiers causing a name collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions.
namespace [identifier] { namespace-body }
A namespace declaration identifies and assigns a name to a declarative region.
The identifier in a namespace declaration must be unique in the declarative region in which it is used. The identifier is the name of the namespace and is used to reference its members.
What is the use of 'using' declaration?
A using declaration makes it possible to use a name from a namespace without the scope operator.
What is an Iterator class?
A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators: input iterators, output iterators, forward iterators, bidirectional iterators, random access. An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class. Something like a pointer.
What is a dangling pointer?
A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.
What do you mean by Stack unwinding?
It is a process during exception handling when the destructor is called for all local objects in the stack between the place where the exception was thrown and where it is caught.
Name the operators that cannot be overloaded??
sizeof, ., .*, .->, ::, ?:
What is a container class? What are the types of container classes?
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.
What is inline function??
The __inline keyword tells the compiler to substitute the code within the function definition for every instance of a function call. However, substitution occurs only at the compiler's discretion. For example, the compiler does not inline a function if its address is taken or if it is too large to inline.

What is overloading??
With the C++ language, you can overload functions and operators. Overloading is the practice of supplying more than one definition for a given function name in the same scope.
- Any two functions in a set of overloaded functions must have different argument lists.
- Overloading functions with argument lists of the same types, based on return type alone, is an error.
What is Overriding?
To override a method, a subclass of the class that originally declared the method must declare a method with the same name, return type (or a subclass of that return type), and same parameter list.
The definition of the method overriding is:
• Must have same method name.
• Must have same data type.
• Must have same argument list.
Overriding a method means that replacing a method functionality in child class. To imply overriding functionality we need parent and child classes. In the child class you define the same method signature as one defined in the parent class.
What is "this" pointer?
The this pointer is a pointer accessible only within the member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.
When a nonstatic member function is called for an object, the address of the object is passed as a hidden argument to the function. For example, the following function call
myDate.setMonth( 3 );
can be interpreted this way:
setMonth( &myDate, 3 );
The object's address is available from within the member function as the this pointer. It is legal, though unnecessary, to use the this pointer when referring to members of the class.
What happens when you make call "delete this;" ??
The code has two built-in pitfalls. First, if it executes in a member function for an extern, static, or automatic object, the program will probably crash as soon as the delete statement executes. There is no portable way for an object to tell that it was instantiated on the heap, so the class cannot assert that its object is properly instantiated. Second, when an object commits suicide this way, the using program might not know about its demise. As far as the instantiating program is concerned, the object remains in scope and continues to exist even though the object did itself in. Subsequent dereferencing of the pointer can and usually does lead to disaster.
You should never do this. Since compiler does not know whether the object was allocated on the stack or on the heap, "delete this" could cause a disaster.
How virtual functions are implemented C++?
Virtual functions are implemented using a table of function pointers, called the vtable. There is one entry in the table per virtual function in the class. This table is created by the constructor of the class. When a derived class is constructed, its base class is constructed first which creates the vtable. If the derived class overrides any of the base classes virtual functions, those entries in the vtable are overwritten by the derived class constructor. This is why you should never call virtual functions from a constructor: because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions
What is name mangling in C++??
The process of encoding the parameter types with the function/method name into a unique name is called name mangling. The inverse process is called demangling.
For example Foo::bar(int, long) const is mangled as `bar__C3Fooil'.
For a constructor, the method name is left out. That is Foo::Foo(int, long) const is mangled as `__C3Fooil'.
What is the difference between a pointer and a reference?
A reference must always refer to some object and, therefore, must always be initialized; pointers do not have such restrictions. A pointer can be reassigned to point to different objects while a reference always refers to an object with which it was initialized.
How are prefix and postfix versions of operator++() differentiated?
The postfix version of operator++() has a dummy parameter of type int. The prefix version does not have dummy parameter.
What is the difference between const char *myPointer and char *const myPointer?
Const char *myPointer is a non constant pointer to constant data; while char *const myPointer is a constant pointer to non constant data.
How can I handle a constructor that fails?
throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.
How can I handle a destructor that fails?
Write a message to a log-file. But do not throw an exception.
The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception. For example, if someone says throw Foo(), the stack will be unwound so all the stack frames between the throw Foo() and the } catch (Foo e) { will get popped. This is called stack unwinding.
During stack unwinding, all the local objects in all those stack frames are destructed. If one of those destructors throws an exception (say it throws a Bar object), the C++ runtime system is in a no-win situation: should it ignore the Bar and end up in the } catch (Foo e) { where it was originally headed? Should it ignore the Foo and look for a } catch (Bar e) { handler? There is no good answer -- either choice loses information.
So the C++ language guarantees that it will call terminate() at this point, and terminate() kills the process. Bang you're dead.
What is Virtual Destructor?
Using virtual destructors, you can destroy objects without knowing their type - the correct destructor for the object is invoked using the virtual function mechanism. Note that destructors can also be declared as pure virtual functions for abstract classes.
if someone will derive from your class, and if someone will say "new Derived", where "Derived" is derived from your class, and if someone will say delete p, where the actual object's type is "Derived" but the pointer p's type is your class.

Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?
C++ allows for dynamic initialization of global variables before main() is invoked. It is possible that initialization of global will invoke some function. If this function crashes the crash will occur before main() is entered.
Name two cases where you MUST use initialization list as opposed to assignment in constructors.
Both non-static const data members and reference data members cannot be assigned values; instead, you should use initialization list to initialize them.
Can you overload a function based only on whether a parameter is a value or a reference?
No. Passing by value and by reference looks identical to the caller.
What are the differences between a C++ struct and C++ class?
The default member and base class access specifiers are different.
The C++ struct has all the features of the class. The only differences are that a struct defaults to public member access and public base class inheritance, and a class defaults to the private access specifier and private base class inheritance.
What does extern "C" int func(int *, Foo) accomplish?
It will turn off "name mangling" for func so that one can link to code compiled by a C compiler.
How do you access the static member of a class?
::
What is multiple inheritance(virtual inheritance)? What are its advantages and disadvantages?
Multiple Inheritance is the process whereby a child can be derived from more than one parent class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of more than one base class thus allowing for modeling of complex relationships. The disadvantage of multiple inheritance is that it can lead to a lot of confusion(ambiguity) when two base classes implement a method with the same name.
What are the access privileges in C++? What is the default access level?
The access privileges in C++ are private, public and protected. The default access level assigned to members of a class is private. Private members of a class are accessible only within the class and by friends of the class. Protected members are accessible by the class itself and it's sub-classes. Public members of a class can be accessed by anyone.
What is a nested class? Why can it be useful?
A nested class is a class enclosed within the scope of another class. For example:
// Example 1: Nested class
//
class OuterClass
{
class NestedClass
{
// ...
};
// ...
};
Nested classes are useful for organizing code and controlling access and dependencies. Nested classes obey access rules just like other parts of a class do; so, in Example 1, if NestedClass is public then any code can name it as OuterClass::NestedClass. Often nested classes contain private implementation details, and are therefore made private; in Example 1, if NestedClass is private, then only OuterClass's members and friends can use NestedClass.
When you instantiate as outer class, it won't instantiate inside class.
What is a local class? Why can it be useful?
local class is a class defined within the scope of a function -- any function, whether a member function or a free function. For example:
// Example 2: Local class
//
int f()
{
class LocalClass
{
// ...
};
// ...
};
Like nested classes, local classes can be a useful tool for managing code dependencies.

Can a copy constructor accept an object of the same class as parameter, instead of reference of the object?

No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference.

Baba write hypothetical stories

"The Baba Is out of one outstanding apex in the battel filed of story writing.Whose stories never end untill the earth end"

Enjoy Baba Hypothetical true stories......................

satisfied or not

Followers

 

Copyright © 2009 by Frequntly ask question