How to check if a VIEW exist in SQL Server

Many scenarios come in query writing, we have to check particular VIEW exists in the database or not. There are many approaches to check the existing view in the SQL server, some approach script described below.

For the demonstration, I am creating a database "Codefari." Same as table "Employee" and view "EmployeeView." Run below script.


USE[Codefari]
GO
CREATE TABLE Employee
(
       ID INT IDENTITY(1,1),
       FirstName VARCHAR(400),
       LastName VARCHAR(400)
)
GO
INSERT INTO Employee
SELECT 'Dilip','Singh'
UNION ALL
SELECT 'Ashish','Singh'
GO
CREATE VIEW dbo.EmployeeView
AS
SELECT ID, FirstName+' '+LastName AS FullName FROM Employee
GO
SELECT * FROM dbo.EmployeeView
GO


 Using sys.view catalog
We can write a query like below to check a particular VIEW exists in the current database for all schema.


USE[Codefari]
GO
IF EXISTS (SELECT 1 FROM sys.views WHERE Name='EmployeeView')
BEGIN
       PRINT 'View exists.'
END
ELSE
BEGIN
       PRINT 'View does not exist.'
END


Result
View exists

Above script is responsible for checking to exist of view "EmployeView" for all schema in the same database. If you want to check the existing view for a particular schema in the same database, then use the following script.


USE[Codefari]
GO
IF EXISTS (SELECT 1 FROM sys.views WHERE OBJECT_ID=OBJECT_ID('dbo.EmployeeView'))
BEGIN
       PRINT 'View exists.'
END
ELSE
BEGIN
       PRINT 'View does not exist.'
END


Result
View exists

Using sys.objects catalog
Using the following script, you can also check to exist of view "EmployeeView" in the database.


USE[Codefari]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID('dbo.EmployeeView') AND type = 'V')
BEGIN
    PRINT 'View Exists'
END
ELSE
BEGIN
       PRINT 'View does not exist.'
END



Result
View exist

Using sys.sql_modules catalog
We can also use sys.sql_modules catalog to check the existing view "EmployeeView" using the following script.


USE[Codefari]
GO
IF EXISTS (SELECT 1 FROM sys.sql_modules WHERE object_id =  OBJECT_ID('dbo.EmployeeView') AND OBJECTPROPERTY(object_id, 'IsView') = 1)
BEGIN
    PRINT 'View exists.'
END
ELSE
BEGIN
       PRINT 'View does not exist.'
END


Result
View exists

Using OBJECT_ID() function
Using  OBJECT_ID() the function we can check existing of view "EmployeeView" for the same Database. See the following script.


USE[Codefari]
GO
IF OBJECT_ID(N'dbo.EmployeeView', N'V') IS NOT NULL
BEGIN
    PRINT 'View exists.'
END
ELSE
BEGIN
       PRINT 'View does not exist.'
END


Result
View exist

What is difference between UNION and UNION ALL in SQL Server

We use UNION and UNION ALL operator to combine multiple results set into one result set.

UNION operator is used to combining multiple results set into one result set but removes any duplicate rows. Basically, UNION is used to performing a DISTINCT operation across all columns in the result set. UNION operator has the extra overhead of removing duplicate rows and sorting result.

UNION ALL operator use to combine multiple results set into one result set but it does not remove any duplicate result. Actually, this does not remove duplicate rows so it is faster than the UNION operator. If you want to combine multiple results and without duplicate records then use UNION otherwise UNION ALL is better.

Following some rules for using UNION/UNION ALL operator

1.  The number of the column should be the same in the query's when you want to combine them.
2.  The column should be of the same data type.
3.  ORDER BY clause can be applied to the overall result set not within each result set.

4.  Column name of the final result set will be from the first query.


CREATE TABLE #TMP
(
      ID INT IDENTITY(1,1),
      NAME VARCHAR(100),
      [ADDRESS] VARCHAR(1000)
)
GO
INSERT INTO #TMP
  VALUES('Dilip','Gorakhpur'),
        ('Anil','Kushinagar')
GO


UNION


SELECT NAME,[ADDRESS] FROM #TMP
UNION
SELECT NAME,[ADDRESS] FROM #TMP


Result Set
NAME                          ADDRESS
---------------------------------------------------------------------------------
Anil                          Kushinagar
Dilip                         Gorakhpur

(2 row(s) affected)
Note: Above result set, show UNION operator removes duplicates rows.


UNION ALL


SELECT NAME,[ADDRESS] FROM #TMP
UNION ALL
SELECT NAME,[ADDRESS] FROM #TMP


Result Set
NAME                           ADDRESS
---------------------------------------------------------------------------------------
Dilip                          Gorakhpur
Anil                           Kushinagar
Dilip                          Gorakhpur
Anil                           Kushinagar

(4 row(s) affected)

Note: UNION ALL returns all the rows including duplicates row.

Difference between VARCHAR and NVARCHAR in SQL Server

1.    VARCHAR is Non-Unicode variable length character data type while NVARCHAR Unicode variable length character data type.

2.    VARCHAR takes 1 byte per character while NVARCHAR takes 2 byte per Unicode/Non-Unicode character. For example:


DECLARE @name AS VARCHAR(50) = 'Dilip'
SELECT @name AS Name,
DATALENGTH(@name) AS [Length]


Result Set
    Name                                               Length
    -------------------------------------------------- -----------
    Dilip                                              5

    (1 row(s) affected)


                     
DECLARE @name AS NVARCHAR(50) = 'Dilip'
SELECT @name AS Name,
DATALENGTH(@name) AS [Length]


Result Set
Name                                               Length
-------------------------------------------------- -----------
Dilip                                              10

(1 row(s) affected)

3.    VARCHAR can store max 8000 Unicode characters while NVARCHAR can store max 4000 Unicode/Non-Unicode characters.


4.    VARCHAR takes number of bytes equal to the number of characters entered plus two bytes extra for defining offset while NVARCHAR  takes number of bytes equal to twice the number of characters entered plus two bytes extra for defining offset.

What is Fill Factor in SQL Server

Fill Factor works in performance tuning area, for the index the most important property is Fill Factor. Fill Factor responsible to determine the percentage of space on each leaf-level page to be filled with data. As we know page is smallest unit of SQL server which size is 8k. Every page cans one or more than one row which is depending on size of row.

The Fill Factor specifies the % of fullness of the leaf level pages of an index. When an index is created or rebuild then filled up pages with data depend on Fill Factor. For example if we create an index and put the  value of Fill Factor is 70 then pages will filled up with data 70% other 30% space will be remain.

For Example, I am creating a Temp named table for testing of Index with Fill Factor.


CREATE TABLE Temp
(
       id INT IDENTITY(1,1),
       Name VARCHAR(100)
)

DECLARE @count INT=100000;
WHILE (@count>0)
BEGIN
       INSERT INTO Temp
       VALUES('SQL Server tutorial by codefari.com Type'+CONVERT(VARCHAR(100),@count))
       SET @count=@count-1
END

SELECT COUNT(*) FROM Temp




Now run following script


EXEC sp_spaceused 'dbo.Temp'



Result Set





High Fill Factor value

You can see index size 8kb and unused 8kb both are same, because we did not create any index on this table.

Now see following scrip I am creating a non-clustered Index with Fill Factor 100%




USE [Test]
GO

/****** Object:  Index [Name]    Script Date: 11/27/2015 6:34:53 PM ******/
CREATE NONCLUSTERED INDEX [Name] ON [dbo].[Temp]
(
       [Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF,
 DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
 FILLFACTOR = 100) ON [PRIMARY]
GO




Again run following script



EXEC sp_spaceused 'dbo.Temp'




Result Set






Here Index size become 6404 kb and unused 176kb. Here we have taken Fill Factor 100%. 
Note: You may choose high Fill Factor value if there is very little or no changes the underlying table's data. Means if you have an index that is constantly changing you would want to have a lower value to keep some free space available for new index entries.  Otherwise SQL Server would have to constantly do page splits to fit the new values into the index pages.

Low Fill Factor value
Now if we put value of Fill Factor as 50% then what will happen you may see in following example.
Drop the created index first and run the following script again.

USE [Test]
GO

/****** Object:  Index [Name]    Script Date: 11/27/2015 6:34:53 PM ******/
CREATE NONCLUSTERED INDEX [Name] ON [dbo].[Temp]
(
       [Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF,
 DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON,
 FILLFACTOR = 50) ON [PRIMARY]
GO


Again run the following script

EXEC sp_spaceused 'dbo.Temp'


Result Set





Now here you can see index_size is 12544kb and unused 248kb.



Note: With new data records added, the index pages need to have sufficient space to take the new entries. When there is not enough space a page split needs to occur which could impact performance depending on how frequently page splits need to occur.
 


PostgreSQL-Query: Sort result set by specific field values using ORDER BY Clause

Problem: Suppose we have a book_inventory table which has some columns such as id, isbn, title, author, publisher, publish_date, etc.. whe...