DBA Diaries

Thoughts and experiences of a DBA working with SQL Server and MySQL

Database views explained

Posted on December 30, 2011 Written by Andy Hayes 2 Comments

Database views are virtual tables which are built up using a SELECT query. The query may contain one or more tables.

To help explain database views, here is a quick script created using SQL Server to create some tables and data. (If you want to create the tables using MySQL, then substitute the part “IDENTITY(1,1)” with “AUTO_INCREMENT”)

CREATE TABLE Department
(
ID TINYINT PRIMARY KEY IDENTITY(1,1),
Department VARCHAR(50) NOT NULL
)
GO

CREATE TABLE Staff
(
ID INT PRIMARY KEY auto_increment,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Salary INT NOT NULL,
DepartmentID TINYINT NOT NULL REFERENCES Department(ID)
)
GO

INSERT INTO Department(Department)
VALUES('Sales'),('Finance'),('Technology');

INSERT INTO Staff(FirstName, LastName, Salary, DepartmentID)
VALUES
('John','Smith',50000,1)
,('Raymond','Jones',50000,2)
,('Tracey','Carter',50000,3);

So lets create a view of the data joining the two tables together and presenting certain fields.

CREATE VIEW vwStaff
AS
SELECT
S.ID AS StaffID
, S.FirstName
, S.LastName
, D.Department
FROM Staff S
JOIN Department D ON S.DepartmentID = D.ID
GO

GRANT SELECT ON vwStaff TO application_developer;

Instead of selecting from the tables, the application developer would select from the view “vwStaff” to retrieve the data they needed.

SELECT * FROM vwStaff

StaffID     FirstName            LastName             Department
----------- -------------------- -------------------- --------------------
1           John                 Smith                Sales
2           Raymond              Jones                Finance
3           Tracey               Carter               Technology

(3 row(s) affected)

There is no performance difference between running the SQL or running database views. If you look at both SQL Server and MySQL, the execution plans are identical between the SQL and database views.

MySQL….

mysql>
explain SELECT S.ID AS StaffID
, S.FirstName
, S.LastName
, D.Department
FROM Staff S
JOIN Department D ON S.DepartmentID = D.IDG;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: S
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 3
        Extra:
*************************** 2. row ***************************
           id: 1
  select_type: SIMPLE
        table: D
         type: eq_ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 1
          ref: dbadiaries.S.DepartmentID
         rows: 1
        Extra:
2 rows in set (0.00 sec)
mysql> explain SELECT * FROM vwStaffG;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: S
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 3
        Extra:
*************************** 2. row ***************************
           id: 1
  select_type: SIMPLE
        table: D
         type: eq_ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 1
          ref: dbadiaries.S.DepartmentID
         rows: 1
        Extra:
2 rows in set (0.00 sec)

SQL Server….

database views

Advantages of Database Views

  • Data protection – create views to protect sensitive data. For example the salary column was hidden in my example above.
  • Code re-use – simplifies application development. If some business logic changes for presenting data, change it once in the view and not many times in different places.
  • Simplifies access to data for untrained users. Lets say you have a department of data analysts who are experts with Excel but can’t write SQL. Create them a view of the data and have them load that into Excel. They can’t write SQL but they can choose a view from a list of available datasets – everyone is happy.
  • Performance – lets say your data analysts can write SQL but you don’t want them writing run-away queries which bring your database server down. Create them a view instead of allowing them direct access to the data.
  • If you are using BCP to export data, you can format the data through views as BCP data formatting is rather limited.
  • Working around non-deterministic function limitations.

Pitfalls of using Database Views

  • Ease of use – you’re probably thinking, what’s he talking about? Well it is very easy to think “I’ll join to that view I created in the database to satisfy this new query I am writing”. You have to remember that database views are SELECT queries. Every time you run one or join to one, the query is run on the fly to produce the results of the view. As an author of a query and using the view above, if you only needed access to the data in the “Staff” table to form part of your query, why join to a view which pulls in data from the “Department” table? That is extra IO overhead which when dealing with large volumes of data or frequent batch requests can have negative performance implications. It is better to have access to either the table (if you are allowed to) or another view of the “Staff” table which allows you to view the fields which you require and use that.
  • Nested database views – don’t create views based on other views as this has a negative performance impact. Better to create views from the base tables.

Filed Under: All Articles, MySQL Administration, SQL Server Administration Tagged With: mysql, sql server

The importance of the foreign key constraint

Posted on December 4, 2011 Written by Andy Hayes 8 Comments

The foreign key constraint is an important aspect of database design. This article explains why.

Foreign key constraint advantages

The purpose of the foreign key constraint is to enforce referential integrity but there are also performance benefits to be had by including them in your database design.

Firstly lets look at an example of how they are used in database design.

So here are my two tables.

CREATE TABLE Accounts
(
ID INT PRIMARY KEY IDENTITY(1,1),
Name VARCHAR(100)
)
GO

CREATE TABLE Orders
(
ID INT PRIMARY KEY IDENTITY(1,1),
OrderDate DATETIME DEFAULT(GETDATE()),
AccountID INT NOT NULL CONSTRAINT FKAccountID REFERENCES Accounts(ID)
)
GO

Now we’ll insert some data.

INSERT INTO Accounts(Name)
VALUES('Test Company 1'),('Test Company 2');

INSERT INTO Orders(AccountID)
VALUES
(1),(2),(1),(2),(1),(2),(1),(2),(1),(2),(1),(2)
,(1),(2),(1),(2),(1),(2),(1),(2),(1),(2),(1),(2);

Let’s have a quick look at the data.

SELECT * FROM Accounts;

SELECT TOP (5) * FROM Orders;
ID          Name
----------- ---------------
1           Test Company 1
2           Test Company 2

(2 row(s) affected)
ID          OrderDate               AccountID
----------- ----------------------- -----------
1           2011-12-04 11:03:08.533 1
2           2011-12-04 11:03:08.533 2
3           2011-12-04 11:03:08.533 1
4           2011-12-04 11:03:08.533 2
5           2011-12-04 11:03:08.533 1

(5 row(s) affected)

So we have inserted rows into table “Orders” which relate to “Accounts” by the AccountID and ID columns respectively. No problems with that. What happens if we try and insert a new row into “Orders” for an account which does not exist in table “Accounts”?

INSERT INTO Orders(AccountID)
VALUES(3);

We get an error.

Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the FOREIGN KEY constraint “FK__Orders__AccountI__0AD2A005”. The conflict occurred in database “DBADiaries”, table “dbo.Accounts”, column ‘ID’.
The statement has been terminated.

So the foreign key constraint is doing its job and only allowing recognized account ids to be added to the “Orders” table.

Now lets say for whatever reason someone attempted to remove a row from table “Accounts” which had related records in table “Orders”

DELETE Accounts WHERE ID = 2;

We get an error.

Msg 547, Level 16, State 0, Line 1
The DELETE statement conflicted with the REFERENCE constraint “FK__Orders__AccountI__0AD2A005”.
The conflict occurred in database “DBADiaries”, table “dbo.Orders”, column ‘AccountID’.
The statement has been terminated.

Cascading deletes are turned off in this instance so as well as stopping bad data getting into the table, the foreign key constraint is preventing data from being deleted which in this case is exactly what I need it to do.

Foreign key constraint performance benefits

How can a foreign key constraint benefit performance? Well let’s have a look at this simple example using the tables previously created.

Activate “Include Actual Execution Plan” in Management Studio using either Ctrl + M or the button on the toolbar. Run a simple query checking for records in table “Orders” which relate to a row in table “Accounts” and then check the execution plan

SELECT *
FROM Orders O
WHERE EXISTS (SELECT * FROM Accounts A WHERE A.ID = O.AccountID);

Execution plan output:

foreign key constraint

Now we will remove the foreign key constraint

ALTER TABLE Orders DROP CONSTRAINT FKAccountID;

Re run the preceeding SQL statement and check the execution plan again and it has changed.

foreign key constraint

So why is it different? The optimizer has to now execute the EXISTS part of the query because it cannot be sure whether table “Accounts” has any valid references. Having the foreign key in there meant that the optimizer could trust it and therefore by definition it did not have to check table “Accounts” when returning all rows from “Orders”. This is because a valid reference in “Accounts” must exist for a row to be stored in “Orders”

Could a foreign key constraint become untrusted?

The answer is yes.

For example you might decide to disable a foreign key when loading in large amounts of data. It is easier to batch insert consistent rows of data into a database without foreign keys enabled.

An untrusted foreign key would mean that the second execution plan would be used for the query which will not perform as fast as the first. If you had tables with lots of rows in, this could make a massive difference to performance.

For the purposes of this explanation, I have added the FKAccountID foreign key constraint and I ran this statement:

ALTER TABLE Orders NOCHECK CONSTRAINT FKAccountID;

So how do you tell whether your foreign key is trusted? Run this query:

SELECT Name, Is_Not_Trusted
FROM sys.foreign_keys
WHERE Name = 'FKAccountID'

Which outputs this information.

Name                 Is_Not_Trusted
-------------------- --------------
FKAccountID          1

(1 row(s) affected)

To correct this run this SQL:

ALTER TABLE Orders WITH CHECK CHECK CONSTRAINT FKAccountID;

You could also look for all untrusted foreign keys in your database as part of a performance tuning exercise.

So a foreign key constraint has advantages and should be part of your design to ensure that you have a consistent database and to help ensure that the database performs optimally.

Filed Under: All Articles, MySQL Administration, SQL Server Administration Tagged With: performance, sql server

  • « Previous Page
  • 1
  • …
  • 3
  • 4
  • 5

Categories

  • All Articles (82)
  • Career Development (8)
  • MySQL Administration (18)
  • MySQL Performance (2)
  • SQL Server Administration (24)
  • SQL Server News (3)
  • SQL Server Performance (14)
  • SQL Server Security (3)
  • SQL Tips and Tricks (19)

Top 10 Popular Posts

  • Using sp_change_users_login to fix SQL Server orphaned users
  • How to shrink tempdb
  • MySQL SHOW USERS? – How to List All MySQL Users and Privileges
  • How to Transfer Logins to Another SQL Server or Instance
  • How to Delete Millions of Rows using T-SQL with Reduced Impact
  • T-SQL – How to Select Top N Rows for Each Group Using ROW_NUMBER()
  • New T-SQL features in SQL Server 2012 – OFFSET and FETCH
  • How to Kill All MySQL Processes For a Specific User
  • Using exec sp_who2 to help with SQL Server troubleshooting
  • How to move tempdb

Recent Posts

  • How to Setup MySQL Master Master Replication
  • How To Use SQL to Convert a STRING to an INT
  • How to set up MySQL Replication Tutorial
  • How to Use SQL CASE for Conditional Logic in Your SQL Queries
  • Using ISNULL in SQL Server to Replace NULL Values

Search

Connect

  • Twitter
  • Facebook
  • Google+
  • RSS

About

  • Cookie Policy
  • Disclaimer
  • About
Copyright © ‘2021’ DBA Diaries built on the Genesis Framework

This site uses cookies. We assume you are happy with cookies but click the link if you are not. Close