sql interview questions

7
SQL What is the difference between inner and outer join? Explain with example. Inner Join Inner join is the most common type of Join which is used to combine the rows from two tables and create a result set containing only such records that are present in both the tables based on the joining condition (predicate). Inner join returns rows when there is at least one match in both tables.If none of the record matches between two tables, then INNER JOIN will return a NULL set. Below is an example of INNER JOIN and the resulting set. SELECT dept.name DEPARTMENT, emp.name EMPLOYEE FROM DEPT dept, EMPLOYEE emp WHERE emp.dept_id = dept.id Outer Join - Outer Join can be full outer or single outer Outer Join, on the other hand, will return matching rows from both tables as well as any unmatched rows from one or both the tables (based on whether it is single outer or full outer join respectively). Notice in our record set that there is no employee in the department 5 (Logistics). Because of this if we perform inner join, then Department 5 does not appear in the above result. However in the below query we perform an outer join (dept left outer join emp), and we can see this department. SELECT dept.name DEPARTMENT, emp.name EMPLOYEE FROM DEPT dept, EMPLOYEE emp WHERE dept.id = emp.dept_id (+) What is the difference between JOIN and UNION? SQL JOIN allows us to “lookup” records on other table based on the given conditions between two tables. For example, if we have the department ID of each employee, then we can use this department ID of the employee table to join with the department ID of department table to lookup department names. UNION operation allows us to add 2 similar data sets to create resulting data set that contains all the data from the source data sets. Union does not require any condition for joining. For example, if you have 2 employee tables with same structure, you can UNION them to create one result set that will contain all the employees from both of the tables. SELECT * FROM EMP1 UNION SELECT * FROM EMP2; What is the difference between UNION and UNION ALL? UNION and UNION ALL both unify for add two structurally similar data sets, but UNION operation returns only the unique records from the resulting data set whereas UNION ALL will return all the rows, even if one or more rows are duplicated to each other. In the following example, I am choosing exactly the same employee from the emp table and performing UNION and UNION ALL. Check the difference in the result. ELECT * FROM EMPLOYEE WHERE ID = 5 UNION ALL SELECT * FROM EMPLOYEE WHERE ID = 5 SELECT * FROM EMPLOYEE WHERE ID = 5 UNION SELECT * FROM EMPLOYEE WHERE ID = 5

Upload: mriyasam

Post on 04-Sep-2015

2 views

Category:

Documents


0 download

DESCRIPTION

This has some SQL Interview Questions

TRANSCRIPT

SQL

What is the difference between inner and outer join? Explain with example.

Inner Join

Inner join is the most common type of Join which is used to combine the rows from two tables and create a result set containing only such records that are present in both the tables based on the joining condition (predicate).

Inner join returns rows when there is at least one match in both tables.If none of the record matches between two tables, then INNER JOIN will return a NULL set. Below is an example of INNER JOIN and the resulting set.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE

FROM DEPT dept, EMPLOYEE emp

WHERE emp.dept_id = dept.id

Outer Join - Outer Join can be full outer or single outer

Outer Join, on the other hand, will return matching rows from both tables as well as any unmatched rows from one or both the tables (based on whether it is single outer or full outer join respectively).

Notice in our record set that there is no employee in the department 5 (Logistics). Because of this if we perform inner join, then Department 5 does not appear in the above result. However in the below query we perform an outer join (dept left outer join emp), and we can see this department.

SELECT dept.name DEPARTMENT, emp.name EMPLOYEE

FROM DEPT dept, EMPLOYEE emp

WHERE dept.id = emp.dept_id (+)

What is the difference between JOIN and UNION?

SQL JOIN allows us to lookup records on other table based on the given conditions between two tables. For example, if we have the department ID of each employee, then we can use this department ID of the employee table to join with the department ID of department table to lookup department names.

UNION operation allows us to add 2 similar data sets to create resulting data set that contains all the data from the source data sets. Union does not require any condition for joining. For example, if you have 2 employee tables with same structure, you can UNION them to create one result set that will contain all the employees from both of the tables.

SELECT * FROM EMP1

UNION

SELECT * FROM EMP2;

What is the difference between UNION and UNION ALL?

UNION and UNION ALL both unify for add two structurally similar data sets, but UNION operation returns only the unique records from the resulting data set whereas UNION ALL will return all the rows, even if one or more rows are duplicated to each other.

In the following example, I am choosing exactly the same employee from the emp table and performing UNION and UNION ALL. Check the difference in the result.

ELECT * FROM EMPLOYEE WHERE ID = 5

UNION ALL

SELECT * FROM EMPLOYEE WHERE ID = 5

SELECT * FROM EMPLOYEE WHERE ID = 5

UNION

SELECT * FROM EMPLOYEE WHERE ID = 5

What is the difference between WHERE clause and HAVING clause?

WHERE and HAVING both filters out records based on one or more conditions. The difference is, WHERE clause can only be applied on a static non-aggregated column whereas we will need to use HAVING for aggregated columns.

To understand this, consider this example. Suppose we want to see only those departments where department ID is greater than 3. There is no aggregation operation and the condition needs to be applied on a static field. We will use WHERE clause here:

SELECT * FROM DEPT WHERE ID > 3

Next, suppose we want to see only those Departments where Average salary is greater than 80. Here the condition is associated with a non-static aggregated information which is average of salary. We will need to use HAVING clause here:

SELECT dept.name DEPARTMENT, avg(emp.sal) AVG_SAL

FROM DEPT dept, EMPLOYEE emp

WHERE dept.id = emp.dept_id (+)

GROUP BY dept.name

HAVING AVG(emp.sal) > 80

What is the difference among UNION, MINUS and INTERSECT?

UNION combines the results from 2 tables and eliminates duplicate records from the result set.

MINUS operator when used between 2 tables, gives us all the rows from the first table except the rows which are present in the second table.

INTERSECT operator returns us only the matching or common rows between 2 result sets.

To understand these operators, lets see some examples. We will use two different queries to extract data from our emp table and then we will perform UNION, MINUS and INTERSECT operations on these two sets of data.

UNION

SELECT * FROM EMPLOYEE WHERE ID = 5

UNION

SELECT * FROM EMPLOYEE WHERE ID = 6

MINUS

SELECT * FROM EMPLOYEE

MINUS

SELECT * FROM EMPLOYEE WHERE ID > 2

INTERSECT

SELECT * FROM EMPLOYEE WHERE ID IN (2, 3, 5)

INTERSECT

SELECT * FROM EMPLOYEE WHERE ID IN (1, 2, 4, 5)

What is Self Join and why is it required?

Self Join is the act of joining one table with itself.Self Join is often very useful to convert a hierarchical structure into a flat structure. In our employee table example above, we have kept the manager ID of each employee in the same row as that of the employee. This is an example of how a hierarchy (in this case employee-manager hierarchy) is stored in the RDBMS table. Now, suppose if we need to print out the names of the manager of each employee right beside the employee, we can use self join. See the example below:

SELECT e.name EMPLOYEE, m.name MANAGER

FROM EMPLOYEE e, EMPLOYEE m

WHERE e.mgr_id = m.id (+)

The only reason we have performed a left outer join here (instead of INNER JOIN) is we have one employee in this table without a manager (employee ID = 1). If we perform inner join, this employee will not show-up.

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.

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.

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 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 are the advantages of using Stored Procedures?

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

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

3. Stored procedures help promote code reuse.

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

5. Stored procedures provide better security to your data.

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 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.

Explain the difference between DELETE , TRUNCATE and DROP commands?

Once delete operation is performed Commit and Rollback can be performed to retrieve data. But after truncate statement, Commit and Rollback rollback statement cant be performed. Where condition can be used along with delete statement but it cant be used with truncate statement. Drop command is used to drop the table or keys like primary,foreign from a table.

Write a SQL Query to find year from date.

SELECT YEAR(GETDATE()) as "Year";

How do you find orphans?

An Orphan is a foreign key value in "child table" which doesnt exist in primary key column in parent table. To get it you can use left outer join (important: child table on left side) with join condition on primary/foreign key columns and with where clause where primary key is null. Adding distinct or count to select is common precise. In SQL Server you can also you except which will show all unique values from first query that don't exist in second query.

How to return XML in SQL Server?

We can use FOR XML statement at the end of the query to return xml data from the SQL Server.

select * from mytable for xml auto

What is the use of COALESCE in SQL Server?

Coalesce returns the first non-null expression among its arguments. Lets say we have to return a non-null from more than one column, then we can use COALESCE function.

SELECT COALESCE(hourly_wage, salary, commission) AS 'Total Salary' FROM wages

In this case,

If hourly_wage is not null and other two columns are null then hourly_wage will be returned.

If hourly_wage, commission are null and salary is not null then salary will be returned.

If commission is non-null and other two columns are null then commission will be returned.

What command do we use to rename a db? sp_renamedb oldname , newname

Can we create a Foreign Key with out Primary Key?

Yes. If the table has Unique Key then it is posible to create a Foreign key constraint

JAVA SCRIPT

How do we add JavaScript onto a web page? There are several way for adding JavaScript on a web page, but there are two ways which are commonly used by developersIf your script code is very short and only for single page, then following ways are the best:a) You can place tag inside the element.

Is JavaScript case sensitive? Ans:Yes!A function getElementById is not the same as getElementbyID.

How to access the value of a textbox using JavaScript?

var name = document.getElementById('txtFullName').value;

OR

var name = document.forms[0].FirstName.value; (old way)

How do you change the style/class on any element using JavaScript?

document.getElementById(myText).style.fontSize = 10";

OR

document.getElementById(myText).className = anyclass;

Does JavaScript Support automatic type conversion, If yes give example.

Yes

Difference between window.onload and onDocumentReady?

The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means theres a huge delay before any code is executed.That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.

What is the difference between == and === ?

The == checks for value equality, but === checks for both type and value.

What is the difference between undefined and null?

The value of a variable with no value is undefined (i.e., it has not been initialized). Variables can be emptied by setting their value to null. You can test for each using the === (three equal signs) or == (two equal signs) for comparison checking. The big difference is the latter uses coercion, which can have some odd results -- it returns true for a null or undefined comparison if they are either.JQUERY

What does dollar sign ($) means in jQuery?

Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code.

$(document).ready(function(){});

Over here $ sign can be replaced with "jQuery" keyword.

jQuery(document).ready(function(){});

Can we use our own specific character in the place of $ sign in jQuery?

Yes. It is possible using jQuery.noConflict().

How JavaScript and jQuery are different?

JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

What is the difference between .js and .min.js?

jQuery library comes in 2 different versions Production and Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.

How do you select element by ID in jQuery?

To select element use ID selector. We need to prefix the id with "#" (hash symbol). For example, to select element with ID "txtName", then syntax would be,

$('#txtName')

What does $("div") will select?

This will select all the div elements on page.

What are the fastest selectors in jQuery?

ID and element selectors are the fastest selectors in jQuery.

What are the slow selectors in jQuery?

class selectors are the slow compare to ID and element.

Difference between $(this) and 'this' in jQuery?

this and $(this) refers to the same element. The only difference is the way they are used. 'this' is used in traditional sense, when 'this' is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.

How do you check if an element is empty?

There are 2 ways to check if element is empty or not. We can check using ":empty" selector.

$(document).ready(function(){

if ($('#element').is(':empty')){

//Element is empty

}

});

And the second way is using the "$.trim()" method.

$(document).ready(function(){

if($.trim($('#element').html())=='') {

//Element is empty

}

});

What is event.PreventDefault?

The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.

What is the difference between event.PreventDefault and event.stopPropagation?

event.preventDefault(): Stops the default action of an element from happening.

event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

What is the difference between event.PreventDefault and "return false"?

e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

What is the difference between event.stopPropagation and event.stopImmediatePropagation?

event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.

How to check if number is numeric while using jQuery 1.7+?

Using "isNumeric()" function which was introduced with jQuery 1.7.

How to check data type of any variable in jQuery?

Using $.type(Object) which returns the built-in JavaScript type for the object.

Can you include multiple version of jQuery? If yes, then how they are executed?

Yes. Multiple versions of jQuery can be included in same page.

Is it possible to hold or delay document.ready execution for sometime?

Yes, its possible. With Release of jQuery 1.6, a new method "jQuery.holdReady(hold)" was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced.

$.holdReady(true);

$.getScript("myplugin.js", function() {

$.holdReady(false);

});

How to write browser specific code using jQuery?

Using jQuery.browser property, we can write browser specific code. This property contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9.

What are various methods to make ajax request in jQuery?

Using below jQuery methods, you can make ajax calls.

load() : Load a piece of html into a container DOM

$.getJSON(): Load JSON with GET method.

$.getScript(): Load a JavaScript file.

$.get(): Use to make a GET call and play extensively with the response.

$.post(): Use to make a POST call and don't want to load the response to some container DOM.

$.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.

Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?

By using jQuery post()/ jQuery get(), you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response.

Where jQuery.ajax() is jQuery's low-level AJAX implementation. $.get and $.post are higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).

What is jQuery UI?

jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library that can be used to build interactive web applications.

What is the difference between jQuery and jQuery UI?

jQuery is the core library. jQueryUI is built on top of it. If you use jQueryUI, you must also include jQuery.