SQL Server: Custom Sorting


AscDescThis is one of the many custom sorting we do with SQL queries. In few cases we may need to sort all records of a result set in a particular order except one specific row containing some specific value, which we may want to keep on the top of all other rows or we may like to move it to the bottom. Now, let’s relate this to few real time scenarios.

Scenario-1:

Sometimes we need an element to be placed at bottom in the list. For example, a Dropdownlist containing educational qualifications may contain  an item with text as “Other”. While showing all these educational qualifications from database we may need this particular element (i.e, “Other”) to move to the bottom in the list. If we try to sort this list in the SELECT query by normal ORDER BY keyword (like ORDER BY Qualification) then we may not get the desired sequence.

To get the desired result we need to use CASE WHEN keyword along with ORDER BY. Let’s illustrate this with following example-

Simple ORDER BY :


SELECT * FROM
(
 SELECT 'I.Sc.' AS Qualification
 UNION
 SELECT 'B.Sc.' AS Qualification
 UNION
 SELECT 'Other' AS Qualification
 UNION
 SELECT 'P.G.' AS Qualification
 UNION
 SELECT 'MCA' AS Qualification
 UNION
 SELECT 'DCA' AS Qualification
 UNION
 SELECT 'P.H.D' AS Qualification
) AS TBL
ORDER BY Qualification

OUTPUT:

5

ORDER BY with CASE WHEN :


SELECT * FROM
(
 SELECT 'I.Sc.' AS Qualification
 UNION
 SELECT 'B.Sc.' AS Qualification
 UNION
 SELECT 'Other' AS Qualification
 UNION
 SELECT 'P.G.' AS Qualification
 UNION
 SELECT 'MCA' AS Qualification
 UNION
 SELECT 'DCA' AS Qualification
 UNION
 SELECT 'P.H.D' AS Qualification
) AS TBL
ORDER BY CASE WHEN Qualification='Other' 
THEN 'ZZZZZ' ELSE Qualification END

OUTPUT:

6

EXPLAINATION:

Here we have set the value of item “Other” as “ZZZZZ” while the sorting is being done. Generally “ZZZZZ” will be the last item in any real world list and hence will move to the last.

Scenario 2:

In some other cases we may need the desired item to be moved to top of the result set. An example for this situation can be, a Dropdownlist containing items for Book Category. The list may have an item with text “General” , which is meant for those books whose category is not clearly known. Let’s assume that most of the books are supposed to belong this category. Then we have to place this item in the first index of the Dropdownlist so that it will be easier for user to pick the item. Now, we need a little modification in the ORDER BY clause as follows.


ORDER BY CASE WHEN Qualification='General' THEN NULL ELSE Qualification END

I’ll love to hear from you.

Thanks

You may also like :

Dynamic ORDER BY in SQL Server

CodeProject

SQL Server: Stored Procedure for update with optional parameters


Problem:

One more article in Problem-Solution approach to keep it short and simple.

When we are writing a stored procedure to update different fields of a table for one or more records, we may write as the below script.

CREATE PROCEDURE [dbo].[UpdtEmployee]
(
    @EmpId INT,
    @EmpName VARCHAR(100)=NULL,
    @Address VARCHAR(200)=NULL,
    @EmpPhotoPath VARCHAR(100)=NULL,
    @MobileNo VARCHAR(14)=NULL
)
AS
BEGIN
    UPDATE dbo.Employee
    SET EmpName=@EmpName,
        Address=@Address,
        EmpPhotoPath=@EmpPhotoPath,
        MobileNo=@MobileNo
    WHERE EmpId=@EmpId
END

The problem with the above stored procedure is when we want to update only those fields/columns of the record for which corresponding parameter is not having NULL values then it will not yield the anticipated result. In this scenario this stored procedure will update all the fields with the values from corresponding parameters. Let’s take an example so that the problem can be understood clearly.

Example: Let’s assume that we have inserted values to all the fields of a record. Now we want to modify only the mobile number of that employee. If we call this procedure then it will make values of all other fields to NULL as we have declared the default value for all the parameters as NULL.

Solution:

Solution to this problem is to avoid updating those fields which have corresponding parameters with NULL values or, we can update existing data corresponding to those fields. We will go for the later one. Now, the modified script may look like


CREATE PROCEDURE [dbo].[UpdtEmployee]
(
    @EmpId INT,
    @EmpName VARCHAR(100)=NULL,
    @Address VARCHAR(200)=NULL,
    @EmpPhotoPath VARCHAR(100)=NULL,
    @MobileNo VARCHAR(14)=NULL
)
AS
BEGIN
    UPDATE dbo.Employee
    SET EmpName=ISNULL(@EmpName,EmpName),
        Address=ISNULL(@Address,Address),
        EmpPhotoPath=ISNULL(@EmpPhotoPath,EmpPhotoPath),
        MobileNo=ISNULL(@MobileNo,MobileNo)
    WHERE EmpId=@EmpId
END

Hopefully this article may be useful to you.

Thanks !!!

MySQL: Creating a simple stored procedure


Let’s start creating stored procedure with a very simple one and then we will analyse it line by line.

DELIMITER $$

DROP PROCEDURE IF EXISTS MyFirstSP$$
CREATE PROCEDURE MyFirstSP()
BEGIN
 SELECT * FROM MyTable;
END$$

Analysis:

  • By default MySQL treats semicolon(;) as the statement terminator or end of statement. But as we are going to use it inside the procedure body, so we need another different delimiter to state the end of the stored procedure. DELIMITER $$ sets $$ as the statement terminator.
  •  The DROP PROCEDURE IF EXISTS <SPName> statement checks for a duplicate stored procedure with the same name and if there exists any then issue a DROP command. You can skip this line if you are sure that there is no other stored procedure exists with the same name in your selected database.
  • Statement CREATE PROCEDURE marks the start of the stored procedure definition. Here, MyFirstSP is the name of our stored procedure. The stored procedure name followed by a pair of parentheses. The use of these parentheses is to define parameters inside it. In this stored procedure we don’t need any parameters, but we have to put these parentheses as this is mandatory in MySQL unlike SQL Server.
  • The BEGIN Statement marks the start or begining of a block (here the block is the stored procedure itself).In stored procedures, every statements with multiple statements should be enclosed with a block defined by BEGIN and END, where END statement marks the end of the block;
  •  The statement inside the BEGIN .. END is a simple SELECT query, which fetches all the records from MyTable table.

CodeProject

SQL Server: An optimal way to create procedure with multiple optional parameters


Problem:

I took the Problem-Solution approach to write this post to keep it short and simple.

Here the problem I am talking about is the scenario when you have to write a stored procedure in SQL Server with multiple search options/parameters then you may use some IF…ELSE .. statements to do it. Let’s take an short example.

Example:


CREATE PROCEDURE [dbo].[getEmployeeList]
(
   @DeptId INT=NULL,
   @OfficeId INT=NULL
)
AS
BEGIN
    IF(@DeptId IS NOT NULL AND @OfficeId IS NOT NULL)
        BEGIN
            SELECT *
            FROM dbo.Employees
            WHERE DeptId=@DeptId AND OfficeId=@OfficeId
        END
    ELSE IF(@DeptId IS NOT NULL AND @OfficeId IS NULL)
        BEGIN
            SELECT *
            FROM dbo.Employees
            WHERE DeptId=@DeptId
        END
    ELSE IF(@DeptId IS NULL AND @OfficeId IS NOT NULL)
        BEGIN
            SELECT *
            FROM dbo.Employees
            WHERE OfficeId=@OfficeId
         END
    ELSE
        BEGIN
            SELECT *
            FROM dbo.Employees
        END
END

Here we can have 4 combinations of search options.

Now, if we want add some more parameters like SectionId,DesignationId,CityId etc. to this stored procedure then it will be a tough task to manage it and may end-up with a 100’s lines of script.

Solution:

I found a solution for this problem by creating multiple conditions for a single WHERE… tag. Now, if I implement it to the previous example then the stored procedure will be like the below script-


CREATE PROCEDURE [dbo].[getEmployeeList]
(
    @DeptId INT=NULL,
    @OfficeId INT=NULL
)
AS
BEGIN
   SELECT *
   FROM dbo.Employees
   WHERE (@DeptId IS NULL OR DeptId=@DeptId)
   AND (@OfficeId IS NULL OR OfficeId=@OfficeId)
END

Just add conditions like these two to the WHERE part, as many as optional parameters you have in your stored procedure.

I hope it will be helpful to those who are looking a solution for the above said problem. Please share your thoughts and ideas regarding this post.

Thank you.

Dynamic ORDER BY in SQL Server


Sometimes we need to sort the select list based on the field passed as parameter, which means while writing the query we are not sure to sort the select list based on which field. Then we just can let the query decide this at the time of execution. To do this we will use dynamic ORDER BY clause. If we employ this using stored procedure then our script will look like following

CREATE PROC [dbo].[spGetDynamicSortedStudents]
(
	@SortValue INT
)
AS
BEGIN
	SELECT *
	FROM dbo.Students
	ORDER BY CASE WHEN @SortValue=1 THEN FullName WHEN @SortValue=2 THEN RegNo ELSE StudentClass END
END