Thursday, 26 September 2013

Can I access Temporary table of one procedure into another prcocedure in sql server?Is it possible?

  Yes.You can use.
Run following Script :

if exists(select name from sys.procedures where name='sp1')
drop proc sp1
go
create procedure sp1
as
begin

select * from #t1

end
go
Go
if exists(select name from sys.procedures where name='sp2')
drop proc sp2
go
go
create procedure sp2
as
begin
select 'SP1 Table' [Value] into #t1
 exec sp1
end
go
 exec sp2


Friday, 13 September 2013

Graphical Query Plan


When SQL Server executes a query it uses a query plan to determine how to access data and complete the query.  SQL Server offers DBAs and developers the ability to see these query plans to assist in query optimization.  Without query plans it would be difficult to figure out how to tune and optimize your queries.

One such version of query plans is Graphical Execution Plans which allows you to see a graphical representation of the processing steps of your query to find optimization opportunities.

The Query Execution Plans describe the steps and the order used to access or modify data in the Microsoft SQL Server database. In this tutorial we will use the terms Execution Plan, Query Plan and Query Execution Plan interchangeably.

Briefly, the Query Plan defines how SQL statements are physically executed by the server. The Query Plan describes the data retrieval and storage methods that are used by the Query Optimizer to execute a specific query. For example, it includes whether the whole table should be read or if an index is used to read a small number of records.

The Execution Plan consists of different operations and each operation has one output which is called the result set. The operations can have one or more inputs such as join operations that have two inputs. Each result set (output) will be the input for the next operation until the SQL statement is finished executing. Therefore the data flow can be drawn as a connection between operators from right to left.

There are many potential ways to execute a query thus SQL Server has to choose the most beneficial one. In the case of very complex queries where there can be many variations, so SQL just picks a plan that is good enough.

The executed Query Plans are also stored in the Procedure Cache, so they can be retrieved and reused if a similar query is executed.

SQL Server can create plans in two ways:

    Actual Execution Plan - created after execution of the query and contains the steps that were performed
    Estimated Execution Plan - created without execution of the query and contains an approximate execution plan

Wednesday, 21 August 2013

SQL Tuning or SQL Optimization

 SQL Tuning or SQL Optimization

Sql Statements are used to retrieve data from the database. We can get same results by writing different sql queries. But use of the best query is important when performance is considered. So you need to sql query tuning based on the requirement. Here is the list of queries which we use reqularly and how these sql queries can be optimized for better performance.

SQL Tuning/SQL Optimization Techniques:

1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.

For Example: Write the query as

SELECT id, first_name, last_name, age, subject FROM student_details;

Instead of:

SELECT * FROM student_details;



2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes.
For Example: Write the query as

SELECT subject, count(subject)
FROM student_details
WHERE subject != 'Science'
AND subject != 'Maths'
GROUP BY subject;

Instead of:

SELECT subject, count(subject)
FROM student_details
GROUP BY subject
HAVING subject!= 'Vancouver' AND subject!= 'Toronto';



3) Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query.
For Example: Write the query as

SELECT name
FROM employee
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_details)
AND dept = 'Electronics';

Instead of:

SELECT name
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details)
AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = 'Electronics';



4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.

For Example: Write the query as

Select * from product p
where EXISTS (select * from order_items o
where o.product_id = p.product_id)

Instead of:

Select * from product p
where product_id IN
(select product_id from order_items



5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
For Example: Write the query as

SELECT d.dept_id, d.dept
FROM dept d
WHERE EXISTS ( SELECT 'X' FROM employee e WHERE e.dept = d.dept);

Instead of:

SELECT DISTINCT d.dept_id, d.dept
FROM dept d,employee e
WHERE e.dept = e.dept;



6) Try to use UNION ALL in place of UNION.
For Example: Write the query as

SELECT id, first_name
FROM student_details_class10
UNION ALL
SELECT id, first_name
FROM sports_team;

Instead of:

SELECT id, first_name, subject
FROM student_details_class10
UNION
SELECT id, first_name
FROM sports_team;



7) Be careful while using conditions in WHERE clause.
For Example: Write the query as

SELECT id, first_name, age FROM student_details WHERE age > 10;

Instead of:

SELECT id, first_name, age FROM student_details WHERE age != 10;

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE first_name LIKE 'Chan%';

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE SUBSTR(first_name,1,3) = 'Cha';

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE first_name LIKE NVL ( :name, '%');

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE first_name = NVL ( :name, first_name);

Write the query as

SELECT product_id, product_name
FROM product
WHERE unit_price BETWEEN MAX(unit_price) and MIN(unit_price)

Instead of:

SELECT product_id, product_name
FROM product
WHERE unit_price >= MAX(unit_price)
and unit_price <= MIN(unit_price)

Write the query as

SELECT id, name, salary
FROM employee
WHERE dept = 'Electronics'
AND location = 'Bangalore';

Instead of:

SELECT id, name, salary
FROM employee
WHERE dept || location= 'ElectronicsBangalore';

Use non-column expression on one side of the query because it will be processed earlier.

Write the query as

SELECT id, name, salary
FROM employee
WHERE salary < 25000;

Instead of:

SELECT id, name, salary
FROM employee
WHERE salary + 10000 < 35000;

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE age > 10;

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE age NOT = 10;

8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY clause.
For Example: Write the query as

SELECT id FROM employee
WHERE name LIKE 'Ramesh%'
and location = 'Bangalore';

Instead of:

SELECT DECODE(location,'Bangalore',id,NULL) id FROM employee
WHERE name LIKE 'Ramesh%';

9) To store large binary objects, first place them in the file system and add the file path in the database.

10) To write queries which provide efficient performance follow the general SQL standard rules.

a) Use single case for all SQL verbs
b) Begin all SQL verbs on a new line
c) Separate all words with a single space
d) Right or left aligning verbs within the initial SQL verb

Monday, 1 July 2013

What is normalization?

What is normalization?
 Database normalization is the process of organizing the fields and tables of a relational database to minimize redundancy and dependency. Normalization usually involves dividing large tables into smaller (and less redundant) tables and defining relationships between them. 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 using the defined relationships.

Why Normalization required?
 Normaliztion is required for avoiding
    a)Delete Anomalies -:If deletion of any record will be done then all references of that records should be deleted  

    b)Update Anomalies -:If  updatation of any record will be done then all references of that records should be updated

    c)Data Redundancy -: Avoiding data repeatation .

Sunday, 30 June 2013

Is it possible to set trigger priority in sql server?

Yes.
    We know trigger is event which is implicitly called on any kind of DML or DDL operation occurred. It may be interview question Suppose I have one table and I created three trigger on that table for update. So which trigger will be fired when?
    If you dont know this concept you will say it will be fiired  randomly.But we can fire it as per our requirement.
  In sql server we have  sp_settriggerorder which will help us to set triggger priority.

sp_settriggerorder 'triggername','value', 'statement_type' 
 
Argument :
trigger Name : Name of trigger
 
value  : It has three value 
First Trigger is fired first.
Last Trigger is fired last.
None Trigger is fired in undefined order.

 
 statement_type:
 
 Specifies the SQL statement that fires the trigger.
like  INSERT, UPDATE, DELETE.

USE  Your_Database; 
GO 
sp_settriggerorder @triggername= 'TriggerName', @order='Type', @stmttype = 'UPDATE';




Saturday, 1 June 2013

SQL query to find second maximum salary of Employee

  Hi,
   Yesterday my friend attended inteview in I B M  for database devloper
 They asked him simple question .Check it out.
           
       Tell me three ways I can get above result .....

Table  -create table Employee (id int,salary money)




1.
SELECT max(salary) FROM Employee WHERE salary NOT IN (SELECT max(salary) FROM Employee);


2.
SELECT max(salary) FROM Employee WHERE salary < (SELECT max(salary) FROM Employee)



3.In sql server - using top  keyword
SELECT TOP 1 salary FROM ( SELECT TOP 2 salary FROM employees ORDER BY salary DESC) AS emp 
 ORDER BY salary ASC

 

Wednesday, 29 May 2013

Is it possible to create foreign key for child table if column has composit primary key?

No, But we can make it possible.

    suppose I have Parent table
eg.
 create table parent (id int  ,value int,primary key(id,value))
   
It has two column .Composit primary key is present on it.

Composit primary : If primary  key  is combination of more than one column then it called as composit primary key.

  I have child table

e.g

create tableChild(id int  foreign key(id) references   parent (id))

Now execute above statement .You will get error.
Message :There are no primary or candidate keys in the referenced table

But we can do it By following way
 make constrain unique on that column.It will work.

script :

Error :
 begin tran 
create table parent (id int  ,value int,primary key(id,value))
create table Child(id int  foreign key(id) references   parent (id))
rollback

Correct :
 begin tran 
create table parent (id int  unique,value int,primary key(id,value))
 create table Child(id int  foreign key(id) references   parent (id))
rollback