Showing posts with label SQL Knowledge. Show all posts
Showing posts with label SQL Knowledge. Show all posts

Tuesday, January 29, 2013

Using Case in a SQL Query




Using Case in Update Statement
UPDATE dbo.Customer SET stateDescription = CASE WHEN statecode = 'MA' THEN 'Massachusetts' WHEN statecode = 'VA' THEN 'Virginia' WHEN statecode = 'PA' THEN 'Pennsylvania' ELSE NULL END
 
Using Case in Select Statement
SELECT COUNT(*) AS TotalCustomers, 
SUM(CASE WHEN statecode = 'MA' THEN 1 ELSE NULL END) AS TotalMassCustomers, 
AVG(CASE WHEN statecode = 'MA' THEN totalsales ELSE NULL END) AS TotalMassSales 
FROM dbo.Customer 

Using Case in Stored Procedure
CREATE PROCEDURE dbo.getCustomerData @sortby VARCHAR(9), @sortdirection CHAR(4) AS
SET 
nocount ON

SELECT 
customerid, firstname, lastname, statecode, statedescription, totalsales FROM dbo.Customer ORDER BY  CASE @sortdirection
     
WHEN 'asc' THEN
      
CASE @sortby 
       
WHEN 'firstname' THEN firstname 
       
WHEN 'lastname' THEN lastname 
       
END
END 
ASC
, CASE @sortdirection
      
WHEN 'desc' THEN
       
CASE @sortby 
       
WHEN 'firstname' THEN firstname 
       
WHEN 'lastname' THEN lastname 
       
END
END
DESC
GO EXEC dbo.getCustomerData 'lastname', 'desc' 

Wednesday, December 26, 2012

Selecting Record to using cursor in stored procedure

Following is an example using cursor to fetch record from table and performing action on each row using while loop, also used try catch in this stored procedure


ALTER PROCEDURE [dbo].[Test_Procedure_By_Khalid]
(
      -- Add the parameters for the stored procedure here
      @TableName nvarchar(255),
      @AreaName varchar(50),
      @SysDate DateTime,
      @ReturnCode INT   OUTPUT
)
AS
     
      DECLARE @GraphID NVARCHAR(50)
      DECLARE @PERIOD INT
      DECLARE @MODELKEY NVARCHAR(50)
      DECLARE @ORIGNALDATE NVARCHAR(50)
      DECLARE @DATE INT
      DECLARE @QTY INT
      DECLARE @TOTALQTY INT
      DECLARE @MODELKEYTYPE INT
      DECLARE @SCREENID NVARCHAR(50)
      DECLARE @RetailModelClassificationName NVARCHAR(50)
      DECLARE @SELECTEDAREA varchar(50)
      DECLARE @INF_Cursor INT
      DECLARE @THEMONTH NVARCHAR(6)
      DECLARE @LASTMONTH NVARCHAR(6)
      DECLARE @LASTYEARMONTH NVARCHAR(6)

      --Cursor Definition
      DECLARE     @Cur_TableParm    CURSOR
     
BEGIN TRY
      ----------------------------
      -- Start Transaction --
      ----------------------------
      BEGIN TRANSACTION
-- Set Cursor to select data from Table CPT_TableParm
      SET @Cur_TableParm = CURSOR FAST_FORWARD FOR
SELECT GraphID,ModelKey,AreaName,ModelClassificationName,ScreenID FROM CPT_TableParm
      WHERE TableName = @TableName
      AND ActFcType = 1
     
      -- Executing Cursor to select data from Table CPT_TableParm
      OPEN  @Cur_TableParm
      FETCH NEXT FROM @Cur_TableParm  INTO
             @GraphID, @MODELKEY,@SELECTEDAREA,
 @RetailModelClassificationName,@SCREENID
     
      -- Looping through cursor result   
      WHILE  @@FETCH_STATUS = 0
        BEGIN
           
Print  @SELECTEDAREA+','+cast(@PERIOD as varchar)+'~'+@MODELKEY+'~'+@ORIGNALDATE+'~'+cast(@DATE as varchar)+'~'+cast(@QTY as varchar)+'~'+
                                          cast(@TOTALQTY as varchar)+'~'+@GraphID+'~''3''~'+@SCREENID
                              SET @ReturnCode = 2

        FETCH NEXT FROM @Cur_TableParm  INTO
                                    @GraphID, @MODELKEY,@SELECTEDAREA,
@RetailModelClassificationName,@SCREENID
       END
      -- Closing @Cur_TableParm to select data from CPT_TableParm
      CLOSE       @Cur_TableParm
      DEALLOCATE  @Cur_TableParm

END TRY

BEGIN CATCH
-- Rollback Transaction --
      ROLLBACK TRANSACTION
      -- Reset Cursor State
      BEGIN
            SET @INF_Cursor = CURSOR_STATUS('global','@Cur_TableParm')
            IF @INF_Cursor = -1
            BEGIN
                  DEALLOCATE  @Cur_TableParm    -- Delete Cursor
            END
            ELSE IF @INF_Cursor <> -3
                  BEGIN
                        CLOSE       @Cur_TableParm    -- Close Cursor
                        DEALLOCATE  @Cur_TableParm    -- Delete Cursor
                  END

            PRINT       ERROR_MESSAGE()
      END
      RETURN 999
END CATCH

Friday, April 13, 2012

How to find the nth Highest Salary from Employee Table

You can find out the nth Highest Salary from the Employee Table by using following systax

select top 1 * from testEmp
where Emp_Id not in
(select top (n-1) Emp_Id from testEmp order by salary desc)
order by salary desc

Let Suppose following is you table

Emp_Id
Employee_Name
Salary
1602
Khalid Rafique
40000
1650
Jamal Ali Khan
45000
1530
Farhan Khan
29000
1533
Abid sultan
33000
1535
Atiq Khan
38000
1730
Rashid Ali
21000

if you want to find 2nd highest salary, you need to have to write the following query

select top 1 * from testEmp 
where Emp_Id not in
(select top (2-1) Emp_Id from testEmp order by salary desc)
order by salary desc

Result:
Emp_Id
Employee_Name
Salary
1602
Khalid Rafique
40000


if you want to find 3rd highest salary, you need to have to write the following query
select top 1 * from testEmp 
where Emp_Id not in
(select top (3-1) Emp_Id from testEmp order by salary desc)
order by salary desc


Result:
Emp_Id
Employee_Name
Salary
1535
Atiq Khan
38000

if you want to find 4rd highest salary, you need to have to write the following query

select top 1 * from testEmp 
where Emp_Id not in
(select top (4-1) Emp_Id from testEmp order by salary desc)
order by salary desc


Result:
Emp_Id
Employee_Name
Salary
1533
Abid sultan
33000

How to find the dupliate record in sql w.r.t columns

You can find the duplicate record using the folloing query with respect to columns sal and age
if you have Users table
LoginId Password UserName Sal Age
admin 1153291460 Khalid Rafique 1100.00000000 25
asdf tyro1 aa 1200.00000000 28
tyro tyro1 Test Account 1200.00000000 28
tyro23 tyro1 Test Account 1200.00000000 28

One Way
select u1.* from Users u1 
inner join
  (select Sal, Age,COUNT(*)as [Count] from Users
   group by Sal,Age
   having COUNT(*)>1) 
as t1
on u1.Sal = t1.Sal and u1.Age =t1.Age


2nd Way
select * from Users
where CAST(Sal as varchar)+'-'+CAST(Age as varchar) in
(select CAST(Sal as varchar)+'-'+CAST(Age as varchar) from Users
 group by Sal,Age
 having COUNT(*)>1)


following will be the result of Query:

LoginId
Password
UserName
Sal
Age
asdf
tyro1
aa
1200.00000000
28
tyro
tyro1
Test Account
1200.00000000
28
tyro23
tyro1
Test Account
1200.00000000
28

Thursday, March 22, 2012

How to find blocking in SQL server and killing blocking process

Following command will give you detail of all the processes
sp_who2

You can find out all the process which have created blocking through following command
select cmd,* from sys.sysprocesses where blocked > 0

 You can kill the blocking process with the following command
kill 54

Thursday, February 16, 2012

What is SQL GROUP BY Clause

The SQL GROUP BY Clause is used along with the group functions to retrieve data grouped according to one or more columns.
For Example: If you want to know the total amount of salary spent on each department, the query would be:
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept;

The output would be like:
dept salary
---------------- --------------
Electrical 25000
Electronics 55000
Aeronautics 35000
InfoTech 30000
NOTE: The group by clause should contain all the columns in the select list expect those used along with the group functions.
SELECT location, dept, SUM (salary)
FROM employee
GROUP BY location, dept;

The output would be like:
location dept salary
------------- --------------- -----------
Bangalore Electrical 25000
Bangalore Electronics 55000
Mysore Aeronautics 35000
Mangalore InfoTech 30000

What is SQL Having Clause?

Having clause is used to filter data based on the group functions. This is similar to WHERE condition but is used with group functions. Group functions cannot be used in WHERE Clause but can be used in HAVING clause.
For Example: If you want to select the department that has total salary paid for its employees more than 25000, the sql query would be like;
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept
HAVING SUM (salary) > 25000

The output would be like:
dept salary
------------- -------------
Electronics 55000
Aeronautics 35000
InfoTech 30000
When WHERE, GROUP BY and HAVING clauses are used together in a SELECT statement, the WHERE clause is processed first, then the rows that are returned after the WHERE clause is executed are grouped based on the GROUP BY clause. Finally, any conditions on the group functions in the HAVING clause are applied to the grouped rows before the final output is displayed.

What is an Index in SQL?

SQL 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, the 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. 

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

  • index_name is the name of the INDEX.
  • table_name is the name of the table to which the indexed column belongs.
  • column_name1, column_name2.. is the list of columns which make up the INDEX.
In Oracle there are two types of SQL index namely, implicit and explicit.

Implicit Indexes:

They are created when a column is explicity defined with PRIMARY KEY, UNIQUE KEY Constraint.

Explicit Indexes:

They are created using the "create index.. " syntax.
NOTE:
1) Even though sql indexes are created to access the rows in the table quickly, they slow down DML operations like INSERT, UPDATE, DELETE on the table, because the indexes and tables both are updated along when a DML operation is performed. So use indexes only on columns which are used to search the table frequently.
2) Is is not required to create indexes on table which have less data.
3) In oracle database you can define up to sixteen (16) columns in an INDEX.

Wednesday, February 15, 2012

What is a 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 considered to be 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.

Types of Triggers:
There are two types of Triggers.
1)      DML Trigger
There are two types of DML Triggers
1.Instead of Trigger
Instead of Triggers are fired in place of the triggering action such as an insert, update, or delete.
2. After Trigger
After triggers execute following the triggering action, such as an insert, update, or delete.
2)      DDL Trigger
This type of trigger is fired against Drop Table, Create Table, Alter Table or Login events. DDL Triggers are always After Triggers.

How to alter modification in database by system admin himself?
How to prevent accidents due to fat fingers? (Accidental execution of code)
How to display message to contact another developers when another developer tries to modify object another developer working on?
It was interesting conversation. Answer to all the questions is correct assignment of permissions and (when permissions are not an issue) Server and Database Level DDL Triggers. If developers have their own login to SQL Server and it does not have permissions to drop or create objects this will not be issue at all. However, there are still risk of System Admin himself making accidental mistakes. The solution to this will be use Server and Database Level DDL Triggers.
DDL is abbreviation of Data Definition Level. DDL contains schema of the database object. It was always dream of all DBA, when change in mission critical schema of the database or server is attempted it is prevented immediately informing DBA and users automatically. DDL Trigger can now make this dream true. Definition of DDL Trigger (from BOL) is DDL Triggers are a special kind of trigger that fire in response to Data Definition Language (DDL) statements. They can be used to perform administrative tasks in the database such as auditing and regulating database operations.
DML is abbreviation of Data Manipulation Level. DML contains the actual data which is stored in the database schema. UPDATE, INSERT, DELETE, SELECT are clause are used to manipulate database. There is following different between DML and DDL triggers.
  • DDL triggers do not support INSTEAD OF feature DML triggers.
  • DDL triggers do not have feature of inserted and deleted tables like DML triggers as it does not participate in database manipulations.
Following example demonstrates how DDL trigger can be used to prevent dropping stored procedure.
Step 1 :
First create any sample stored procedure.
USE AdventureWorks;
GO
CREATE PROCEDURE TestSP            
AS
SELECT 1 test;
GO 
Step 2 :
Create DDL trigger which will prevent dropping the stored procedure.
USE AdventureWorks
GO 
CREATE TRIGGER PreventDropSP             
ON DATABASE            
FOR DROP_PROCEDURE            
AS
PRINT 'Dropping Procedure is not allowed. DDL Trigger is preventing this from happening. To drop 
stored procedure run following script.Script : DISABLE TRIGGER PreventDropSP ON DATABASE; ; 
ENABLE TRIGGER PreventDropSP ON DATABASE;'
ROLLBACK;
GO 
Step 3 :
Now test above trigger by attempting to drop the stored procedure.
USE AdventureWorks
GO
DROP PROCEDURE TestSP;
GO 
This should throw following message along with error code 3609 :
Dropping Procedure is not allowed.
DDL Trigger is preventing this from happening.
To drop stored procedure run following script.
Script :
DISABLE TRIGGER PreventDropSP ON DATABASE;
;
ENABLE TRIGGER PreventDropSP ON DATABASE;
Msg 3609, Level 16, State 2, Line 1
The transaction ended in the trigger. The batch has been aborted.
Step 4 :
Now DISABLE above trigger and it will let you successfully drop the stored procedure previously attempted to drop. Once it is dropped enable trigger again to prevent future accidents.
USE AdventureWorks
GO            
DISABLE TRIGGER PreventDropSP ON DATABASE;
DROP PROCEDURE TestSP;
ENABLE TRIGGER PreventDropSP ON DATABASE; 
GO 
List of all the DDL events (DROP_PROCEDURE in example above) to use with DDL Trigger are listed on MSDN.

What is a 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.

What is Third Normal Form and what is its advantage?

Third Normal Form (3NF) is most preferable normal form in RDBMS. Normalization is the process of designing a data model to efficiently store data in a database. The rules of 3NF are mentioned here

  • Make a separate table for each set of related attributes, and give each table a primary key.
  • If an attribute depends on only part of a multi-valued key, remove it to a separate table
  • If attributes do not contribute to a description of the key, remove them to a separate table.
Normalization is very close to concept of object oriented schema’s and it stores one data at only one place by removing all the redundant data. It also helps to draw the schema easier. Normalization comes at the cost of performance.

Reference : Pinal Dave (http://blog.SQLAuthority.com) , DataModel.org.

Tuesday, February 14, 2012

General Questions on SQL SERVER

DBMS – Data Base Management System
RDBMS – Relational Data Base Management System or Relational DBMS
A DBMS has to be persistent, that is it should be accessible when the program created the data ceases to exist or even the application that created the data restarted. A DBMS also has to provide some uniform methods independent of a specific application for accessing the information that is stored.
RDBMS adds the additional condition that the system supports a tabular structure for the data, with enforced relationships between the tables. This excludes the databases that don’t support a tabular structure or don’t enforce relationships between tables.
DBMS does not impose any constraints or security with regard to data manipulation it is user or the programmer responsibility to ensure the ACID PROPERTY of the database whereas the RDBMS is more with this regards because RDBMS defines the integrity constraint for the purpose of holding ACID PROPERTY. RDBMS may be or may not be Client Server Database System.
Examples :
DBMS – File System, XML
RDBMS – SQL Server, Oracle
Reference : Pinal Dave (http://blog.SQLAuthority.com)

What are the Properties of the Relational Tables?

Relational tables have the following 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.

How is ACID property related to Database?

ACID (an acronym for Atomicity Consistency Isolation Durability) is a concept that Database Professionals generally look for while evaluating databases and application architectures. For a reliable database, all this four attributes should be achieved.
Atomicity is an all-or-none proposition.
Consistency guarantees that a transaction never leaves your database in a half-finished state.
Isolation keeps transactions separated from each other until they are finished.

What are the 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, then remove it to a separate table.
3NF: Eliminate Columns Not Dependent On Key
Third Normal Form (3NF) is most preferable normal form in RDBMS. Normalization is the process of designing a data model to efficiently store data in a database. The rules of 3NF are mentioned here
  • Make a separate table for each set of related attributes, and give each table a primary key.
  • If an attribute depends on only part of a multi-valued key, remove it to a separate table
  • If attributes do not contribute to a description of the key, remove them to a separate table.
Normalization is very close to concept of object oriented schema’s and it stores one data at only one place by removing all the redundant data. It also helps to draw the schema easier. Normalization comes at the cost of performance.
BCNF: Boyce-Codd Normal Form
If there are non-trivial dependencies between candidate key attributes, then 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.

Reference: Pinal Dave (http://blog.SQLAuthority.com)

 


Difference between Stored procedure and functions

Functions
----------
1) can be used with Select statement
2) Not returning output parameter but returns Table variables
3) You can join UDF
4) Cannot be used to change server configuration
5) Cannot be used with XML FOR clause
6) Cannot have transaction within function

Stored Procedure
-----------------
1) have to use EXEC or EXECUTE
2) return output parameter
3) can create table but won’t return Table Variables
4) you can not join SP
5) can be used to change server configuration
6) can be used with XML FOR Clause
7) can have transaction within SP

Differences between stored procedures and triggers in databases?

Stored procedures are compiled collection of programs or SQL statements that live in the database. A stored procedure can access and modify data present in many tables. Also a stored procedure is not associated with any particular database object. But triggers are event-driven special procedures which are attached to a specific database object say a table. Stored procedures are not automatically run and they have to be called explicitly by the user. But triggers get executed when the particular event associated with the event gets fired. For example in case of a database having say 200 users and the last modified timestamp need to be updated every time the database is accessed and changed. To ensure this one may have a trigger in the insert or update event. So that whenever any insert or update event of the table gets fired the corresponding trigger gets activated and updates the last modified timestamp column or field with the current time. Thus the main difference between stored procedure and trigger is that in case of stored procedure the program logic is executed on the database server explicitly under eth user’s request but in case of triggers event-driven procedures attached to database object namely table gets fired automatically when the event gets fired.

What are the difference between DDL, DML and DCL commands?


DDL


Data Definition Language (DDL) statements are used to define the database structure or schema. Some examples:
  • CREATE - to create objects in the database
  • ALTER - alters the structure of the database
  • DROP - delete objects from the database
  • TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  • COMMENT - add comments to the data dictionary
  • RENAME - rename an object

DML


Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:
  • SELECT - retrieve data from the a database
  • INSERT - insert data into a table
  • UPDATE - updates existing data within a table
  • DELETE - deletes all records from a table, the space for the records remain
  • MERGE - UPSERT operation (insert or update)
  • CALL - call a PL/SQL or Java subprogram
  • EXPLAIN PLAN - explain access path to data
  • LOCK TABLE - control concurrency

DCL


Data Control Language (DCL) statements. Some examples:
  • GRANT - gives user's access privileges to database
  • REVOKE - withdraw access privileges given with the GRANT command

TCL


Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.
  • COMMIT - save work done
  • SAVEPOINT - identify a point in a transaction to which you can later roll back
  • ROLLBACK - restore database to original since the last COMMIT
  • SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use