Você está na página 1de 10

SQL Basics 1

Relational Database Management System

• Maintaining the relationships among data in a database.


• Ensuring that data is stored correctly and that the rules defining the relationships
among data are not violated.
• Recovering all data to a point of known consistency, in the event of a system failure.

Normalization

Normalization is the process of organizing the data into related tables.


Rules are established for the normalization of data. These rules are known as First,
Second, and Third normal Forms.

First Normal Form : Column cannot contain multiple values


Second Normal Form : Every non-key column must depend on the entire
key and not just a part of the primary key
Third Normal Form : All non-key columns must not depend on any other
non-key columns.
De-Normalization

• Denormalization is introduction of controlled redundancy in


the database.
• to optimize performace of select query. to minimize joins used in the query. Used in
Reporting Applications

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.

Entity integrity (ROW)


• Requires that all rows in a table have a unique identification value
Ex : PRIMARY ,UNIQUE
SQL Basics 2

Domain integrity (COLUMN)


• Specifies a set of permissible or possible data values that are valid for that field
• enforced by restricting the type ( through datatypes), the formats of the columns
(rules and CHECK constraints )or the range of possible values ( rules, FOREIGN KEY
and CHECK constraints).

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.

PRIMARY KEY UNIQUE KEY

enforce the uniqueness of a column,


• uniquely identify each row in or combination of columns, that is
the table not the primary key
• Only one per table Can be more than one
• By Default , for Primary key By Default , for Unique key Non
Clustered Index gets created Clustered Index gets created
• does not allow NULL Allow one NULL Value
• Generally Identity Column is
the best choice.
Can be called as Alternate key
• Can be defined on more than
one column Yes
• can be refered by other table
as FK Yes

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

Stored Procedure Advantages :


• Share Application Logic
• Shield Database Schema Details
• Provide Security Mechanisms
• Improve Performance
• allow modular programming.so can be resused
• Reduce Network Traffic

System Stored Procedures (sp_)


• Stored in the master database, system storedprocedures (identified by the
sp_ prefix) provide an effective method to retrieve information from system
tables.

• Ex : SP_HELPTEXT, SP_DEDENDS
SQL Basics 3

Extended stored procedures (xp_)


• implemented as dynamic-link libraries (DLLs) executed outside of the
• SQL Server environment.
• Created by Languages like C,C++
• Extended stored procedures are typically identified
• by the xp_ prefix.
• Will be replaced by CLR Procedures in future

User-defined Function (UDF)


• Scalar Functions
• In-Line Table-valued Functions
• Multi-Statement Table-valued Functions
Scalar User-defined Function
• RETURNS a Scalar VALUE like int,VARCHAR
• RETURNS Clause Specifies Data Type
• Function Is Defined Within a BEGIN and END Block
• Return Type Is Any Data Type Except text, ntext, image,cursor, or timestamp

In-Line Table-valued Function


• Content of the Function Is a SELECT Statement
• Do Not Use BEGIN and END
• RETURN Specifies table as the Data Type
• Can be called a Parameteried View

Multi-Statement Table-valued Function


• BEGIN and END Enclose Multiple Statements
• RETURNS Clause Specifies table Data Type
• RETURN Statement returns the table data

function Stored Procedure


must return a value may or may not
not supported for output param supports for output parameter
can be used in SELECT Queries ,
WHERE,CHECK Can't
Can be used in JOINS as a table
can be invoked only by two part
names (dbo.)
Cannot affect the state of database.
Can't modify (INSERT,UPDATE ) on
physical tables . Only in Table
variable it can be done
does not allow PRINT,TRY CATCH.So
difficult to debug.
does not support for certain Non-
Deterministic function

Parsed and compiled at runtime Pre compiled


SQL Basics 4

Functions are mainly used to Procedures are mainly used to


compute values. process the tasks.

View
ability to store a predefined query as an object in the
database

• A subset of rows or columns of a base table.


• A union of two or more base tables.
• A join of two or more base tables.
• A statistical summary of a base table.
• A subset of another view, or some combination of views and base tables.
• Virtual Table ie not physically stored

View Advantages

• Focus the Data for Users


Focus on important or appropriate data only
Limit access to sensitive data
• Mask Database Complexity
Hide complex database design
• Simplify complex queries, including distributed queries to heterogeneous data
• Simplify Management of User Permissions
• Improve Performance
• Organize Data for Export to Other Applications

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

• Activating a Trigger Recursively


• Types of Recursive Triggers
• Direct recursion occurs when a trigger fires and performs
an action that causes the same trigger to fire again
• Indirect recursion occurs when a trigger fires and
performs an action that causes a trigger on another table
to fire
ALTER DATABASE DB SET RECURSIVE_TRIGGERS ON

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

CHECK Constraint Trigger


• Pro Active Reactive
• Checks before insertion
happens Checks after insertion happens
• Perfotmance : Fast Comparatively Slow
• Validatation are Limited with Validatation can be with other table
in the table Can Used for relational integrity

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.

Data Definition Language (DDL)


CREATE ,ALTER ,DROP
Data Manipulation Language (DML)
SELECT,INSERT,UPDATE
Data Control Language (DCL)
GRANT,REVOKE .. Permission related

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

Clustered Index Non-Clustered Index


• Physical ordering of the data
is same as their indexed
order. not
• Leaf Level of the page Leaf Level of the page contains
contains actual data clustered index key or data page key
• only one clustered index per
table. maximum of 249
• Generally created first Created after Clustered
• By Default , for Primary key By Default , for Unique key Non
Clustered Index gets created Clustered Index gets created
• Best for range data .(Since
data are stored in sequence) Best for single value

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

Computed Column/Derived Column


• Set the value of a column based on other columns data.
• Not Stored physically
• PERSISTED keyword enable the computed column value to be stored physically on to
the disk

SubQuery
• Query within the another query
• A subquery is usually added in the WHERE Clause of the sql statement
• But not depended

Correlated Sub Query


• A query is called correlated subquery when both the inner query
and the outer query are interdependent.
• For every row processed by the inner query, the outer query is processed as well.
• The inner query depends on the outer query before it can be processed

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

Transaction Isolation Level


• ability to shield transactions from the effects of updates performed by other
concurrent transactions.
• The isolation property is one of the four properties, atomicity, consistency, isolation,
and durability (ACID)
• define the type of locks acquired on read operations
• Setting transaction isolation levels is a trade off between integrity and concurrent
access to data.

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.

• SQL Server Authentication


When using SQL Server Authentication, a SQL Server system administrator
defines a SQL Server login account and password. Users must supply both SQL
Server logins and passwords when they connect to SQL Server.

• 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

SQL Server 2005 features


• CLR Programming
• XML Data Type
• TRY CATCH
• DDL Triggers
• Table Partition

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

XML Data type


• The xml data type lets you store XML documents and fragments in a SQL Server
database
• Supports for XML schema ,XQuery Languages
SQL Basics 10

• Used to send collection of data from middle tier to Backend


• Can be used to store varying attribute so frequently without breaking the schemas.

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

EXCEPT & INTERSECT

• 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

Você também pode gostar