SQL Journey

  • Your Email ID:

    Join 6 other followers

  • Top Rated

  • Bookmarks

  • Twitter Updates

  • Blog Stats

    • 16,734 hits
  • SocialVibe


Posts Tagged ‘Create table’

Finding Nth highest number in SQL Server

Posted by Prashant on June 29, 2010

Many times you face this question while working with real time data and most interviews. In this post we will go through different ways to find the records with Nth highest number. Use this script to populate some sample data to test the results.

CREATE TABLE PLAYER
(
PLAYERID INT IDENTITY(100,2) NOT NULL,
NAME VARCHAR(100) NOT NULL,
DOB DATETIME,
COUNTRY VARCHAR(3),
PRIZEMONEY MONEY NOT NULL
)
GO

INSERT INTO PLAYER(NAME,DOB,COUNTRY,PRIZEMONEY) VALUES 
('Andre Agassi','4/29/1970','USA',$31152975),  ('Rafael Nadal','6/3/1986','ESP',$27224163), ('Boris Becker','11/22/1967','GER',$25080956),  
('Yevgeny Kafelnikov','2/18/1974','RUS',$23883797), ('Ivan Lendl','3/7/1960','USA',$21262417),  ('Stefan Edberg','1/19/1966','SWE',$20630941),
('Goran Ivanisevic','9/13/1971','CRO',$19876579),  ('Michael Chang','2/22/1972','USA',$19145632), ('Lleyton Hewitt','2/24/1981','AUS',$18312036), 
('Andy Roddick','8/30/1982','USA',$17109084), ('Novak Djokovic','5/22/1987','SRB',$15984098), ('Gustavo Kuerten','9/10/1976','BRA',$14807000),
('Jonas Bjorkman','3/23/1972','SWE',$14600323),  ('Marat Safin','1/27/1980','RUS',$14373291), ('Jim Courier','8/17/1970','USA',$14034132),  
('Carlos Moya','8/27/1976','ESP',$13382822), ('Nikolay Davydenko','6/2/1981','RUS',$1339499),  ('Michael Stich','10/18/1968','GER',$129528),
('Juan Carlos Ferrero','2/12/1980','ESP',$12588898),  ('John McEnroe','2/16/1959','USA',$12552132), ('Thomas Muster','10/2/1967','AUT',$12225910),  
('Tim Henman','9/6/1974','GBR',$11635542), ('Sergio Bruguera','1/16/1971','ESP',$11632199),  ('Patrick Rafter','12/28/1972','AUS',$11127058),
('Thomas Enqvist','3/13/1974','SWE',$10461641),  ('Petr Korda','1/23/1968','CZE',$10448900), ('Alex Corretja','4/11/1974','ESP',$10411354),  
('Todd Woodbridge','4/2/1971','AUS',$10095245), ('Richard Krajicek','12/6/1971','NED',$10077425), ('Roger Federer','8/8/1981','SUI',$53362068),  
('Pete Sampras','8/12/1971','USA',$43280489)
GO

Here is 4 different ways to find the same result.

--Define Level of N
DECLARE @N INT = 3

--Method-1: Without using any functions
SELECT NAME,DOB,COUNTRY,PRIZEMONEY FROM PLAYER WHERE PRIZEMONEY =
(SELECT DISTINCT PRIZEMONEY FROM PLAYER p1 WHERE (@N-1)=
(SELECT COUNT(DISTINCT p2.PRIZEMONEY) FROM PLAYER p2 WHERE p2.PRIZEMONEY > p1.PRIZEMONEY ))

--Method-2: Using TOP
SELECT NAME,DOB,COUNTRY,PRIZEMONEY FROM PLAYER WHERE PRIZEMONEY =
(SELECT TOP 1 PRIZEMONEY FROM PLAYER
WHERE PRIZEMONEY in (SELECT DISTINCT TOP (@N) PRIZEMONEY FROM PLAYER ORDER BY PRIZEMONEY DESC)
ORDER BY PRIZEMONEY)

--Method-3: Using MIN() function
SELECT NAME,DOB,COUNTRY,PRIZEMONEY FROM PLAYER WHERE PRIZEMONEY =
(SELECT MIN([t].[amt]) FROM
(SELECT DISTINCT TOP (@N) PRIZEMONEY AS [amt] FROM PLAYER ORDER BY PRIZEMONEY DESC) AS [t])

--Method-4: Using Dense_Rank()
;WITH cte
AS (
SELECT NAME,DOB,COUNTRY,PRIZEMONEY,  DENSE_RANK() OVER (ORDER BY PRIZEMONEY DESC) AS [rnk]
FROM PLAYER t
)
SELECT NAME,DOB,COUNTRY,PRIZEMONEY
FROM cte
WHERE [rnk] = @N

Also let me know your suggestions on this.

Posted in Create Table, CTE, Data Types, Functions, Interview Questions, SQL Server | Tagged: , , , , , , , , | Leave a Comment »

CHECK constraint with User Defined Function in SQL Server

Posted by Prashant on June 25, 2010

This post describes how to use result of an user defined function with CHECK constraint in SQL Server.  For demonstration, considered a situation where it is not  allowed to insert or update records where calculated age of a person is less than 18 years as per his/her Date of Birth.

So for this first we need to create the function before creating the CHECK constraint. Here is a function which will return age as per the date of birth provided.

/*
This function will take Date Of Birth as input parameter,
and returns Age in Years to the caller
*/
CREATE FUNCTION [dbo].[fnGetAge](@DateOfBirth DATETIME)
RETURNS SMALLINT
AS
BEGIN
DECLARE @Age SMALLINT
SET @Age =(DATEDIFF(YY, @DateOfBirth, GETDATE())-
(CASE
WHEN GETDATE() >= DATEADD(YY, DATEDIFF(YY, @DateOfBirth, GETDATE()), @DateOfBirth) THEN 0
ELSE 1
END))
RETURN @Age
END;
GO

Now create a table where CHECK constraint will refer to this function to check if the age of the person meets the required criteria or not (minimum 18 Years in this case).

--Create Customer table
CREATE TABLE Customers
(
CustID INT IDENTITY(1,1) NOT NULL,
CustName VARCHAR(100) NOT NULL,
DateOfBirth DATETIME NOT NULL,
Email VARCHAR(100),
CONSTRAINT pkCustomers PRIMARY KEY(CustID),
--Calculate & check if age of customer is atleast 18 Years
CONSTRAINT chkCheckAge CHECK(dbo.fnGetAge(DateOfBirth) >= 18)
)
GO

--Populate table with some sample data.
INSERT INTO Customers(CustName, DateOfBirth, Email)
VALUES ('ABC','19810726','abc@cust.info'),
('XYZ','19840510','xyz@cust.info'),
('MNO','19720417','mno@cust.info')
GO
--Result Message
--(3 row(s) affected)

Now try to insert a record where calculated age is less than 18 years and see what happens.

--Try to insert a record where Age less than 18 Years(as per provided Date of Birth)
INSERT INTO Customers(CustName, DateOfBirth, Email)
VALUES ('TEST','20010315','test@cust.info')
GO

--Error Message
Msg 547, Level 16, State 0, Line 2
The INSERT statement conflicted with the CHECK constraint "chkCheckAge".
The conflict occurred in database "SQLJourney", table "dbo.Customers", column 'DateOfBirth'.
The statement has been terminated.

As the age does not meet the required criteria in defined CHECK constraint, it doesn’t allow to insert this record to the table.

Note:

CHECK constraint evaluates the provided expression while UPDATE operation as well.

You cannot DROP the function till the table (which refers to that function) exists in the database.

Posted in Constraints, Create Table, Functions, Interview Questions, SQL Server | Tagged: , , , , , , , | Leave a Comment »

UNIQUE Key Constraint with Multiple NULL values in SQL Server

Posted by Prashant on June 12, 2010

This was a really interesting situation when we development team members were discussing over this topic. It was a situation where it was not possible to allow multiple NULL values into a column with UNIQUE Key defined in a table. Here I will give the problem first then we will go with the alternate solution for this.

Problem:

In SQL Server it is not allowed to insert multiple NULL values into a UNIQUE Key column. Below is the situation:

--Create employee table
CREATE TABLE EMPLOYEE
(EMPLOYEEID INT NOT NULL
CONSTRAINT PK_EMPLOYEE PRIMARY KEY CLUSTERED
,FNAME VARCHAR(100)
,LNAME VARCHAR(100)
,UNIQUEID INT UNIQUE)
GO
--Insert data values (used row constructor)
INSERT INTO EMPLOYEE(EMPLOYEEID, FNAME, LNAME, UNIQUEID)VALUES
(1,'RAHUL','MISHRA','112342115'),
(2,'SHEEL','KURANI','1725421455'),
(3,'SHEETAL','BAJAJ','1423721455'),
(4,'KAUSHIK','NARANG','1123721955'),
(5,'ADRIAN','THOULISS','1452342145')
GO
--Insert data value with NULL values to UNIQUE key column
INSERT INTO EMPLOYEE(EMPLOYEEID, FNAME, LNAME)
VALUES(6,'SAUGAT','KIOHLI')
--See below the result 
SELECT EMPLOYEEID, FNAME, LNAME, UNIQUEID FROM EMPLOYEE
GO

When I try to enter another record with NULL value to UNIQUEID column, it does not allow me to do that and throws an error.

--Insert data value with NULL values to UNIQUE key column
INSERT INTO EMPLOYEE(EMPLOYEEID, FNAME, LNAME)
VALUES(7,'VAID','GURU')

--ERROR MESSAGE
Msg 2627, Level 14, State 1, Line 2
Violation of UNIQUE KEY constraint 'UQ__EMPLOYEE__04FF5B33023D5A04'.
Cannot insert duplicate key in object 'dbo.EMPLOYEE'.
The statement has been terminated.
Solution:
Here is the alternate solution for the above situation. Instead of define an UNIQUE Key to UNIQUEID column I will create another COMPUTED Column with UNIQUE Key. See how it is done:

--ALTERNATE SOLUTION
--Drop the UNIQUE key
ALTER TABLE EMPLOYEE
DROP CONSTRAINT UQ__EMPLOYEE__04FF5B33023D5A04

--Add a computed column with UNIQUE key
ALTER TABLE EMPLOYEE
ADD ALTUNIQUEID AS CASE WHEN UNIQUEID IS NULL THEN EMPLOYEEID ELSE UNIQUEID END
GO
ALTER TABLE EMPLOYEE
ADD CONSTRAINT UKey_QNIQUEID UNIQUE (ALTUNIQUEID)
GO

--Now insert multiple records with NULL to UNIQUEID column
INSERT INTO EMPLOYEE(EMPLOYEEID, FNAME, LNAME)
VALUES(7,'VAID','GURU'),(8,'TARUN','KISHORE')
GO
--See below the result
SELECT * FROM EMPLOYEE
GO

Your valuable comments are most appreciated.

Posted in Constraints, Create Table, Interview Questions, SQL Server | Tagged: , , , , , | 2 Comments »

Check existence of Table or Database before creating it in SQL Server

Posted by Prashant on June 9, 2010

To check if a table is exists or not a database:

--Check if table exists
IF EXISTS (SELECT 1 FROM sys.tables WHERE name = 'TableName')
PRINT 'TableName available.'
ELSE
PRINT 'TableName not available.'

Similar way we can also check if a database is exists or not before creating.

--Check if database exists
IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'DBName')
PRINT 'DBName available.'
ELSE
PRINT 'DBName not available.'

Please leave your valuable comments on this.

Posted in Database Development, General, SQL Server | Tagged: , , , , | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.