SQL Basics 1: Relational Database Management System
SQL Basics 1: Relational Database Management System
Normalization
OLTP
• Data in an OLTP database is generally organized into relational tables to reduce
redundant information and to increase the speed of updates.
• SQL Server enables a large number of users to perform transactions and
simultaneously change real-time data in OLTP databases.
• T-SQL Queries are used to access the data
• Examples of OLTP databases include airline ticketing and banking transaction
systems.
OLAP
• OLAP technology organizes and summarizes large amounts of data so that an analyst
can evaluate data quickly and in real time.
• SQL Server Analysis Services organizes this data to support a wide array of
enterprise solutions from corporate reporting and analysis to data modeling and
decision support
• MDX Queries are used to access the data
Data Integrity
• The consistency and accuracy of the data stored in the database with respect to the
processes the system supports, is referred as data integrity
• To prevent invalid data entry into the database tables.
• To enforce the rules that are associated with the information in the database.
Referential integrity
• Ensures consistency among tables
• Ensures that the relationships among the primary keys ( in the referenced table) and
foreign keys ( in the referencing tables) are always maintained.
Stored Procedure
• Collections of Pre-Compiled Transact-SQL Statements
• Encapsulate Repetitive Tasks
• Accept Input, OutPut Parameters and Return Values
• Return Status Value to Indicate Success or Failure
• Ex : SP_HELPTEXT, SP_DEDENDS
SQL Basics 3
View
ability to store a predefined query as an object in the
database
View Advantages
Trigger
• A trigger is a special type of stored procedure that automatically runs when an event
occurs
• To enforce referential integrity or consistency among logically related data in
different tables. Because users
• To enforce complex business rules that maintain data integrity
• Used for Auditing purpose
• Compare Before and After States of Data Under Modification
• DML trigger statements use two special temporary tables: the deleted table and the
inserted tables.
• Functions UPDATE(column),COLUMNS_UPDATED()
determining which columns from the firing view or table have been updated
INSTEAD OF Trigger
• INSTEAD OF Trigger Can Be on a Table or View
• The Action That Initiates the Trigger Does NOT Occur. So we need to write explicitly
INSERT to do insert on the original table
• Allows Updates to Views Not Previously Updateable
Recursive Triggers
SQL Basics 5
DDL Trigger
• 2005 feature
• fire in response to a variety of Data Definition Language (DDL) statements.
• These statements are primarily statements that start with CREATE, ALTER, and
DROP.
• used for administrative tasks such as auditing and regulating database operations
• EVENTDATA function
Information about an event that fires a DDL trigger is captured (time,TSQL)
returns an xml value
• Database Scope
CREATE_TABLE,CREATE_VIEW
• Server Scope
CREATE_DATABASE,CREATE_LOGIN
DELETE TRUNCATE
To Delete one or more records To Delete all the records
It is logged operation.Deleteion not a logged operation.Deletion is not
of Each row is logged. done row by row. Instead of data pages .
Slow Fast
Can be rolled back Can't
Can not reset the Identity Value reset the identity value to orginal
Can be used if any FK present Can not be used if any FK present
Fires trigger No.
Temporary table
• Stored in the tempdb system database (# or ##)
SQL Basics 6
• Used for row by row processing (rather than cursor) and storing intermediate data
• implicitly dropped by the system ..whenever SQL Server restarts
SQL Profiler
SQL Profiler is a graphical tool that allows you to monitor events, such as
when the stored procedure has started or completed, or when individual
Transact-SQL statements within a stored procedure have started or completed.
In addition, you can monitor whether a stored procedure is found in the
procedure cache.
Index
• SQL Server’s internal method of organizing the data in a table in such a way, that
the data can be retrieved optimally.
• Used for reading data faster ..(SELECT)
• Physically stored .Whenever INSERT,UPDATE are operation are happening on a
table ,their respective index also gets modified/rearranged.
• So having Excess of Index would slow down in INSERT,UPDATE
LinkedServer
• Linked server allows for access to distributed, heterogeneous queries
against OLE DB data sources
Ex. Data Source Remote SQL Server,Oracle Excel ,Text file
• Executing a Query in remote server
SQL Basics 7
Distributed Queries
• access data from multiple heterogeneous data sources using OPENDATASOURCE or
the OPENROWSET function (Same like Linked Server)
• can be called a Ad-Hoc Queries
SubQuery
• Query within the another query
• A subquery is usually added in the WHERE Clause of the sql statement
• But not depended
Derived tables
• is a virtual table that’s calculated on the fly from a select statement.
• executes faster than Temp Table
SQLCMD utility
• utility to execute Transact-SQL statements, system procedures, and script files at the
command prompt. This utility uses OLE DB to execute Transact-SQL batches.
BCP utility
• bulk copies data between an instance of Microsoft SQL Server 2005 and a data file
in a user-specified format.
Dynamic SQL
• Building SQL statements at run time in Transact-SQL scripts
sp_executesql
• system stored procedure to execute a Unicode string
• supports parameter substitution
• to execute a dynamically built string containing an SQL statement
• Prevents SQL Injections
SQL Injection
• "An attack technique used to exploit web sites by altering backend SQL statements
through manipulating application input."
• SQL Injection happens when a developer accepts user input that is directly placed
into a SQL Statement and doesn't properly filter out dangerous characters. This can
allow an attacker to not only steal data from your database, but also modify and
delete it.
SQL Basics 8
• Attackers commonly insert single qoutes into a URL's query string, or into a forms
input field to test for SQL Injection.
• Can be prevented using parameterized queries .(sp_executeSQL)
Transaction
• is a logical unit of work
• defined by using BEGIN TRANSACTION and COMMIT TRANSACTION
READ UNCOMMITTED
• can read rows that have been modified by other transactions but not yet committed
• Lead to Dirty Read
• Same as SELECT …FROM Table (NOLOCK)
• least restrictive of the isolation levels
READ COMMITTED
• cannot read data that has been modified but not committed by other transactions.
• This prevents dirty reads
• SQL Server’s Default option
REPEATABLE READ
• no other transactions can modify data that has been read by the current transaction
until the current transaction completes
• Other transactions can insert new rows that match the search conditions of
statements Lead to Phantom reads
• Shared locks are placed on all data
SERIALIZABLE
• No other transactions can modify data that has been read by the current transaction
until the current transaction completes
• Other transactions cannot insert new rows with key values that would fall in the
range of keys read by any statements in the current transaction until the current
transaction completes
• Range locks are placed in the range of key values
• most restrictive of the isolation
Authentication
• A user must have a login account to connect to SQL Server. SQL Server
recognizes two login authentication mechanisms—Windows Authentication and SQL
Server Authentication—each of which has a different type of login account.
• Windows Authentication
When using Windows Authentication, a Windows 2000 account or group
SQL Basics 9
controls user access to SQL Server. A user does not provide a SQL Server login
account when connecting. A SQL Server system administrator must define either the
Windows 2000 account or the Windows 2000 group as a valid SQL Server login
account.
• System Database
• Master
Controls the user databases and operation of SQL Server as a whole by keeping
track of information such as user accounts, configurable environment variables, and
system error messages
• Model
Provides a template or prototype for new user databases
• tempdb
Provides a storage area for temporary tables and other temporary working storage
needs
Recreated whenever SQL Server gets restarted
• msdb
Provides a storage area for scheduling information and job history
CLR Programming
• In SQL Server 2005, you can create a database object inside an instance of SQL
Server that is programmed in an assembly created in the Microsoft .NET Framework
common language runtime (CLR).
• Database objects that can leverage the rich programming model provided by the CLR
include triggers, stored procedures, functions, aggregate functions, and types.
• Used for CPU Intensive , complex programming
OUTPUT Clause
• Returns information from, or expressions based on, each row affected by an INSERT,
UPDATE, or DELETE statement.
• These results can be returned to the processing application for use in such things as
confirmation messages, archiving, and other such application requirements.
Alternatively, results can be inserted into a table or table variable
• Can be used instead of having a trigger
• SQL 2005 feature
Table Partition
• Partitioning is the separation of database rows from one large table into one or more
smaller tables.
• There can be performance and administrative advantages in using partitioning
because you are essentially using one or more tables as one large table.
• SQL 2005 feature
• The EXCEPT and INTERSECT operators allow you to compare the results of two or
more SELECT statements and return distinct values.
• The EXCEPT operator returns any distinct values from the query on the left side of
the EXCEPT operator that are not also returned by the query on the right side.
• INTERSECT returns any distinct values that are returned by both the query on the
left and right sides of the INTERSECT operator.
• Result sets that are compared using EXCEPT or INTERSECT must all have the same
structure. They must have the same number of columns, and the corresponding
result set columns must have compatible data types