• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/382

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

382 Cards in this Set

  • Front
  • Back
SQL NOT NULL Constraint Example
CREATE TABLE Persons

(
P_Id int NOT NULL,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL UNIQUE Constraint
The UNIQUE constraint uniquely identifies each record in a database table.

The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.

Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
SQL UNIQUE Constraint on CREATE TABLE
CREATE TABLE Persons

(
P_Id int NOT NULL,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
UNIQUE (P_Id)
)
SQL UNIQUE Constraint on ALTER TABLE
ALTER TABLE Persons

ADD UNIQUE (P_Id)
to DROP a UNIQUE Constraint
To drop a UNIQUE constraint, use the following SQL:

MySQL:

ALTER TABLE Persons
DROP INDEX uc_PersonID
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values.

A primary key column cannot contain NULL values.

Each table should have a primary key, and each table can have only ONE primary key.
SQL PRIMARY KEY Constraint on CREATE TABLE
CREATE TABLE Persons

(
P_Id int NOT NULL PRIMARY KEY,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax
CREATE TABLE Persons

(
P_Id int NOT NULL,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
)
SQL PRIMARY KEY Constraint on ALTER TABLE
ALTER TABLE Persons

ADD PRIMARY KEY (P_Id)
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax
ALTER TABLE Persons

ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
To DROP a PRIMARY KEY Constraint
ALTER TABLE Persons

DROP CONSTRAINT pk_PersonID
SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
SQL FOREIGN KEY Constraint on CREATE TABLE
CREATE TABLE Orders

(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)
Allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax
CREATE TABLE Orders

(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
SQL FOREIGN KEY Constraint on ALTER TABLE
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already created, use the following SQL:

ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To DROP a FOREIGN KEY Constraint
ALTER TABLE Orders

DROP CONSTRAINT fk_PerOrders
SQL CHECK Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a single column it allows only certain values for this column.

If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
SQL CHECK Constraint on CREATE TABLE

The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons" table is created. The CHECK constraint specifies that the column "P_Id" must only include integers greater than 0.
CREATE TABLE Persons

(
P_Id int NOT NULL CHECK (P_Id>0),
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
Allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax
CREATE TABLE Persons

(
P_Id int NOT NULL,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)
SQL CHECK Constraint on ALTER TABLE
To create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ADD CHECK (P_Id>0)
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax
ALTER TABLE Persons

ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
To DROP a CHECK Constraint
ALTER TABLE Persons

DROP CONSTRAINT chk_Person
SQL DEFAULT Constraint
The DEFAULT constraint is used to insert a default value into a column.

The default value will be added to all new records, if no other value is specified.
SQL DEFAULT Constraint on CREATE TABLE
The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created:

CREATE TABLE Persons
(
P_Id int NOT NULL,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes'
)
The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE()
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
SQL DEFAULT Constraint on ALTER TABLE
To create a DEFAULT constraint on the "City" column when the table is already created, use the following SQL:

ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'SANDNES'
To DROP a DEFAULT Constraint
ALTER TABLE Persons

ALTER COLUMN City DROP DEFAULT
SQL CREATE INDEX Statement
The CREATE INDEX statement is used to create indexes in tables.

Indexes allow the database application to find data fast; without reading the whole table.
SQL CREATE INDEX Syntax
Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name
ON table_name (column_name)
CREATE INDEX Example
The SQL statement below creates an index named "PIndex" on the "Last Name" column in the "Persons" table:

CREATE INDEX PIndex
ON Persons (Last Name)

If you want to create an index on a combination of columns, you can list the column names within the parentheses, separated by commas:

CREATE INDEX PIndex
ON Persons (Last Name, FirstName)
create an index on a combination of columns
CREATE INDEX PIndex

ON Persons (Last Name, FirstName)
DROP INDEX Syntax for MS SQL Server
DROP INDEX table_name.index_name
The DROP TABLE Statement
The DROP TABLE statement is used to delete a table.

DROP TABLE table_name
The DROP DATABASE Statement
The DROP DATABASE statement is used to delete a database.

DROP DATABASE database_name
The TRUNCATE TABLE Statement
What if we only want to delete the data inside the table, and not the table itself?

Then, use the TRUNCATE TABLE statement:

TRUNCATE TABLE table_name
SQL ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
SQL ALTER TABLE Syntax
ALTER TABLE table_name

ADD column_name datatype
To delete a column in a table
ALTER TABLE table_name

DROP COLUMN column_name
use ALTER TABLE to

change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name

ALTER COLUMN column_name datatype
SQL ALTER TABLE Example



P_Id Last Name FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Now we want to add a column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons
ADD DateOfBirth date
Change Data Type Example
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons
ALTER COLUMN DateOfBirth year
DROP COLUMN Example
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

We use the following SQL statement:

ALTER TABLE Persons
DROP COLUMN DateOfBirth
SQL AUTO INCREMENT Field
Auto-increment allows a unique number to be generated when a new record is inserted into a table.
AUTO INCREMENT a Field
CREATE TABLE Persons

(
P_Id int NOT NULL AUTO_INCREMENT,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
Let the AUTO_INCREMENT sequence start with another value
ALTER TABLE Persons AUTO_INCREMENT=100
The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table:
CREATE TABLE Persons

(
P_Id int PRIMARY KEY IDENTITY,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned a unique value. The "FirstName" column would be set to "Lars" and the "Last Name" column would be set to "Monsen".
INSERT INTO Persons (FirstName,LastName)

VALUES ('Lars','Monsen')
SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table
CREATE TABLE Persons

(
P_Id PRIMARY KEY AUTOINCREMENT,
Last Name varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.
SQL CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
SQL CREATE VIEW Examples
CREATE VIEW [Current Product List] AS
SELECT ProductID,ProductName
FROM Products
WHERE Discontinued=No

We can query the view above as follows:

SELECT * FROM [Current Product List]
SQL Updating a View
You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
SQL Dropping a View
You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax
DROP VIEW view_name
MySQL Date Functions
Function Description

NOW() Returns the current date and time

CURDATE() Returns the current date

CURTIME() Returns the current time

DATE() Extracts the date part of a date or date/time expression

EXTRACT() Returns a single part of a date/time

DATE_ADD() Adds a specified time interval to a date

DATE_SUB() Subtracts a specified time interval from a date

DATEDIFF() Returns the number of days between two dates

DATE_FORMAT() Displays date/time data in different formats
NOW()
Returns the current date and time
CURDATE()
Returns the current date
CURTIME()
Returns the current time
DATE()
Extracts the date part of a date or date/time expression
EXTRACT()
Returns a single part of a date/time
DATE_ADD()
Adds a specified time interval to a date
DATE_SUB()
Subtracts a specified time interval from a date
DATEDIFF()
Returns the number of days between two dates
DATE_FORMAT()
Displays date/time data in different formats
GETDATE()
Returns the current date and time
DATEPART()
Returns a single part of a date/time
DATEADD()
Adds or subtracts a specified time interval from a date
DATEDIFF()
Returns the time between two dates
CONVERT()
Displays date/time data in different formats
SQL Server Date Functionsv
Function Description

GETDATE() Returns the current date and time

DATEPART() Returns a single part of a date/time

DATEADD() Adds or subtracts a specified time interval from a date

DATEDIFF() Returns the time between two dates

CONVERT() Displays date/time data in different formats
MySQL comes with the following data types for storing a date or a date/time value in the database
DATE - format YYYY-MM-DD

DATETIME - format: YYYY-MM-DD HH:MM:SS

TIMESTAMP - format: YYYY-MM-DD HH:MM:SS

YEAR - format YYYY or YY
SQL Server comes with the following data types for storing a date or a date/time value in the database
DATE - format YYYY-MM-DD

DATETIME - format: YYYY-MM-DD HH:MM:SS

SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS

TIMESTAMP - format: a unique number
OrderId ProductName OrderDate

1 Geitost 2008-11-11
2 Camembert Pierrot 2008-11-09
3 Mozzarella di Giovanni 2008-11-11
4 Mascarpone Fabioli 2008-10-29

Now we want to select the records with an OrderDate of "2008-11-11" from the table above.

We use the following SELECT statement:
SELECT * FROM Orders WHERE OrderDate='2008-11-11'

The result-set will look like this:

OrderId ProductName OrderDate
1 Geitost 2008-11-11
3 Mozzarella di Giovanni 2008-11-11
SQL NULL Values
If a column in a table is optional, we can insert a new record or update an existing record without adding a value to this column. This means that the field will be saved with a NULL value.

NULL values are treated differently from other values.

NULL is used as a placeholder for unknown or inapplicable values.
SQL IS NULL

How do we select only the records with NULL values in the "Address" column?
We will have to use the IS NULL operator:

SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL

The result-set will look like this:

Last Name FirstName Address
Hansen Ola
Pettersen Kari
SQL IS NOT NULL

How do we select only the records with no NULL values in the "Address" column?
We will have to use the IS NOT NULL operator:

SELECT LastName,FirstName,Address FROM Persons

WHERE Address IS NOT NULL
ISNULL() function
MySQL does have an ISNULL() function. However, it works a little bit different from Microsoft's ISNULL() function.
SQL Server / MS Access ISNULL()
ISNULL() returns a zero if the value is NULL:
NVL(), IFNULL(), and COALESCE() use
NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the same result.
Microsoft Access Data Types
Text, Memo, Byte, Integer, Long, Single, Double, Currency, autoNumber, Date/Time, Yes/No, Ole Object, Hyperlink, Lookup Wizard
CHAR(size)

MySQL Data Types
Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters
VARCHAR(size)

MySQL Data Types
Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type
TINYTEXT

MySQL Data Types
Holds a string with a maximum length of 255 characters
TEXT

MySQL Data Types
Holds a string with a maximum length of 65,535 characters
BLOB

MySQL Data Types
For BLOBs (Binary Large Objects). Holds up to 65,535 bytes of data
MEDIUMTEXT

MySQL Data Types
For BLOBs (Binary Large Objects). Holds up to 16,777,215 bytes of data
MEDIUMBLOB

MySQL Data Types
Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB

MySQL Data Types
For BLOBs (Binary Large Objects). Holds up to 4,294,967,295 bytes of data
ENUM(x,y,z,etc.)

MySQL Data Types
Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted.

Note: The values are sorted in the order you enter them.

You enter the possible values in this format: ENUM('X','Y','Z')
SET

MySQL Data Types
Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice
TINYINT(size)

MySQL Data Types
-128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis
SMALLINT(size)

MySQL Data Types
-32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis
MEDIUMINT(size)

MySQL Data Types
-8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis
INT(size)

MySQL Data Types
-2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis
BIGINT(size)

MySQL Data Types
-9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis
FLOAT(size,d)

MySQL Data Types
A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter
DOUBLE(size,d)

MySQL Data Types
A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter
DECIMAL(size,d)

MySQL Data Types
A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter
DATE()

MySQL Data Types
A date. Format: YYYY-MM-DD

Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME()

MySQL Data Types
*A date and time combination. Format: YYYY-MM-DD HH:MM:SS

Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP()

MySQL Data Types
*A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS

Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC
TIME()

MySQL Data Types
A time. Format: HH:MM:SS

Note: The supported range is from '-838:59:59' to '838:59:59'
YEAR()

MySQL Data Types
A year in two-digit or four-digit format.

Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069
char(n)

SQL Server Data Types
Fixed-length character string. Maximum 8,000 characters
char(n)

SQL Server Data Types
Variable-length character string. Maximum 8,000 characters
varchar(max)

SQL Server Data Types
Variable-length character string. Maximum 1,073,741,824 characters
text

SQL Server Data Types
Variable-length character string. Maximum 2GB of text data
nchar(n)

SQL Server Data Types
Fixed-length Unicode data. Maximum 4,000 characters
nvarchar(n)

SQL Server Data Types
Variable-length Unicode data. Maximum 4,000 characters
nvarchar(max)

SQL Server Data Types
Variable-length Unicode data. Maximum 536,870,912 characters
ntext

SQL Server Data Types
Variable-length Unicode data. Maximum 2GB of text data
bit

SQL Server Data Types
Allows 0, 1, or NULL
binary(n)

SQL Server Data Types
Fixed-length binary data. Maximum 8,000 bytes
varbinary(n)

SQL Server Data Types
Variable-length binary data. Maximum 8,000 bytes
varbinary(max)

SQL Server Data Types
Variable-length binary data. Maximum 2GB
image

SQL Server Data Types
Variable-length binary data. Maximum 2GB
tinyint

SQL Server Data Types
Allows whole numbers from 0 to 255
smallint

SQL Server Data Types
Allows whole numbers between -32,768 and 32,767
int

SQL Server Data Types
Allows whole numbers between -2,147,483,648 and 2,147,483,647
bigint

SQL Server Data Types
Allows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807
decimal(p,s)

SQL Server Data Types
Fixed precision and scale numbers.

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0
numeric(p,s)

SQL Server Data Types
Fixed precision and scale numbers.

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0
smallmoney

SQL Server Data Types
Monetary data from -214,748.3648 to 214,748.3647
money

SQL Server Data Types
Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807
float(n)

SQL Server Data Types
Floating precision number data from -1.79E + 308 to 1.79E + 308.

The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.
real

SQL Server Data Types
Floating precision number data from -3.40E + 38 to 3.40E + 38
datetime

SQL Server Data Types
From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds
datetime2

SQL Server Data Types
From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds
smalldatetime

SQL Server Data Types
From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute
date

SQL Server Data Types
Store a date only. From January 1, 0001 to December 31, 9999
time

SQL Server Data Types
Store a time only to an accuracy of 100 nanoseconds
datetimeoffset

SQL Server Data Types
The same as datetime2 with the addition of a time zone offset
timestamp

SQL Server Data Types
Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable
sql_variant

SQL Server Data Types
Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp
uniqueidentifier

SQL Server Data Types
Stores a globally unique identifier (GUID)
xml

SQL Server Data Types
Stores XML formatted data. Maximum 2GB
cursor

SQL Server Data Types
Stores a reference to a cursor used for database operations
table

SQL Server Data Types
Stores a result-set for later processing
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.
SQL Scalar functions
SQL scalar functions return a single value, based on the input value.
AVG()

COUNT()

FIRST()

LAST()

MAX()

MIN()

SUM()
* AVG() - Returns the average value

* COUNT() - Returns the number of rows

* FIRST() - Returns the first value

* LAST() - Returns the last value

* MAX() - Returns the largest value

* MIN() - Returns the smallest value

* SUM() - Returns the sum
UCASE()

LCASE()

MID()

LEN()

ROUND()

NOW()

FORMAT()
* UCASE() - Converts a field to upper case

* LCASE() - Converts a field to lower case

* MID() - Extract characters from a text field

* LEN() - Returns the length of a text field

* ROUND() - Rounds a numeric field to the number of decimals specified

* NOW() - Returns the current system date and time

* FORMAT() - Formats how a field is to be displayed
AVG() function returns the average value of a numeric column.

SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name
SQL AVG() Example
O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen



SELECT AVG(OrderPrice) AS OrderAverage FROM Orders
find the customers that have an OrderPrice value higher than the average OrderPrice value
SELECT Customer FROM Orders

WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)
SQL COUNT(column_name) Syntax
The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column:



SELECT COUNT(column_name) FROM table_name
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:



SELECT COUNT(*) FROM table_name
SQL COUNT(DISTINCT column_name) Syntax
The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:

SELECT COUNT(DISTINCT column_name) FROM table_name



Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.
SQL COUNT(column_name) Example
O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen

2 2008/10/23 1600 Nilsen

3 2008/09/02 700 Hansen

4 2008/09/03 300 Hansen

5 2008/08/30 2000 Jensen

6 2008/10/04 100 Nilsen



Now we want to count the number of orders from "Customer Nilsen".



We use the following SQL statement:

SELECT COUNT(Customer) AS CustomerNilsen FROM Orders

WHERE Customer='Nilsen'



The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders in total:

CustomerNilsen

2
SQL COUNT(*) Example
we omit the WHERE clause, like this:

SELECT COUNT(*) AS NumberOfOrders FROM Orders
SQL COUNT(DISTINCT column_name) Example
SELECT COUNT(DISTINCT Customer) AS NumberOfCustomers FROM Orders
SQL FIRST() Function
SQL FIRST() Syntax

SELECT FIRST(column_name) FROM table_name
SQL LAST() Function
SQL LAST() Syntax

SELECT LAST(column_name) FROM table_name
SQL LAST() Example



O_Id OrderDate OrderPrice Customer

1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
SELECT LAST(OrderPrice) AS LastOrderPrice FROM Orders


Note Tip: Workaround if LAST() function is not supported:

SELECT OrderPrice FROM Orders ORDER BY O_Id DESC LIMIT 1


The result-set will look like this:

LastOrderPrice

100
SQL MAX() Function
The MAX() function returns the largest value of the selected column.

SQL MAX() Syntax

SELECT MAX(column_name) FROM table_name
SQL MIN() Function
The MIN() function returns the smallest value of the selected column.

SQL MIN() Syntax

SELECT MIN(column_name) FROM table_name
SQL SUM() Function
The SUM() function returns the total sum of a numeric column.

SQL SUM() Syntax

SELECT SUM(column_name) FROM table_name
SELECT SUM(OrderPrice) AS OrderTotal FROM Orders
OrderTotal

5700
The GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
GROUP BY More Than One Column
SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders
GROUP BY Customer,OrderDate
SQL HAVING Clause
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.
SQL HAVING Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
SQL HAVING Example



O_Id OrderDate OrderPrice Customer
1 2008/11/12 1000 Hansen
2 2008/10/23 1600 Nilsen
3 2008/09/02 700 Hansen
4 2008/09/03 300 Hansen
5 2008/08/30 2000 Jensen
6 2008/10/04 100 Nilsen
SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000



The result-set will look like this:

Customer SUM(OrderPrice)
Nilsen 1700
Now we want to find if the customers "Hansen" or "Jensen" have a total order of more than 1500.

We add an ordinary WHERE clause to the SQL statement:
SELECT Customer,SUM(OrderPrice) FROM Orders
WHERE Customer='Hansen' OR Customer='Jensen'
GROUP BY Customer
HAVING SUM(OrderPrice)>1500


The result-set will look like this:
Customer SUM(OrderPrice)
Hansen 2000
Jensen 2000
SQL UCASE() Function
The UCASE() function converts the value of a field to uppercase.

SQL UCASE() Syntax

SELECT UCASE(column_name) FROM table_name

Syntax for SQL Server

SELECT UPPER(column_name) FROM table_name
SQL LCASE() Function
The LCASE() function converts the value of a field to lowercase.

SQL LCASE() Syntax

SELECT LCASE(column_name) FROM table_name

Syntax for SQL Server

SELECT LOWER(column_name) FROM table_name
The MID() Function
The MID() function is used to extract characters from a text field.

SQL MID() Syntax

SELECT MID(column_name,start[,length]) FROM table_name



Parameter Description

column_name Required. The field to extract characters from

start Required. Specifies the starting position (starts at 1)

length Optional. The number of characters to return. If omitted, the MID() function returns the rest of the text
SQL MID() Example



P_Id LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to extract the first four characters of the "City" column above.

We use the following SELECT statement:
SELECT MID(City,1,4) as SmallCity FROM Persons


The result-set will look like this:

SmallCity

Sand

Sand

Stav
SQL LEN() Function
The LEN() Function

The LEN() function returns the length of the value in a text field.

SQL LEN() Syntax

SELECT LEN(column_name) FROM table_name
SQL ROUND() Function
The ROUND() Function

The ROUND() function is used to round a numeric field to the number of decimals specified.

SQL ROUND() Syntax

SELECT ROUND(column_name,decimals) FROM table_name

Parameter Description

column_name Required. The field to round.

decimals Required. Specifies the number of decimals to be returned
SQL NOW() Function
The NOW() Function

The NOW() function returns the current system date and time.

SQL NOW() Syntax

SELECT NOW() FROM table_name
SQL FORMAT() Function
The FORMAT() function is used to format how a field is to be displayed.

SQL FORMAT() Syntax

SELECT FORMAT(column_name,format) FROM table_name

Parameter Description

column_name Required. The field to be formatted.

format Required. Specifies the format.
SQL FORMAT() Example

We have the following "Products" table:

Prod_Id ProductName Unit UnitPrice
1 Jarlsberg 1000 g 10.45
2 Mascarpone 1000 g 32.56
3 Gorgonzola 1000 g 15.67

Now we want to display the products and prices per today's date (with today's date displayed in the following format "YYYY-MM-DD").

We use the following SELECT statement:
SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate
FROM Products

The result-set will look like this:

ProductName UnitPrice PerDate
Jarlsberg 10.45 2008-10-07
Mascarpone 32.56 2008-10-07
Gorgonzola 15.67 2008-10-07
sp_who
shows everybody that is running a request on the SQL server
use of DMV
SELECT * FROM sys.dm_exec_sessions

SELECT * FROM sys.dm_exec_requests
what is DMV
dynamic management views
DBCC
Transact-SQL programming language provides DBCC statements that act as Database Console Commands for Microsoft SQL Server 2008. These statements check the physical and logical consistency of a database. Many DBCC statements can fix detected problems
sys.dm_clr_loaded_assemblies
Assemblies in available in SQL Server
sys.dm_db_file_space_usage
Database file usage to determine if databases are getting low on space and need immediate attention
sys.dm_exec_cached_plans
Cached query plans available to SQL Server
sys.dm_exec_sessions
Sessions in SQL Server
sys.dm_exec_connections
Connections to SQL Server
sys.dm_db_index_usage_stats
Seeks, scans, lookups per index
sys.dm_io_virtual_file_stats
IO statistics for databases and log files
sys.dm_broker_connections
Service Broker connections to the network
sys.dm_os_memory_objects
SQL Server memory usage
sys.dm_tran_active_transactions
Transaction state for an instance of SQL Server
list of all db query
SELECT DISTINCT DB_NAME(database_id)

FROM sys.master_files
Can 32 bit version of SQL 2008 be installed on 64 bit windows
Yes with WOW
What version for .Net is required by SQL 2008
.Net Framework 3.5 and Windows Installer 4.5
SQL Server requires
.Net framework 3.5

Microsoft Data Access Components 2.8 SP1

Share Memory

Named Pipe

TCP/IP networking support

IE 6 SP1 and up
You can install all editions of SQL Server 2008 on either
Windows 2003 Standard

Windows 2008 Server Standard
Describe the Service Broker ?
intro in SQL 2005 message queuing system. Based on user-defined messages and processing actions, it provides asynchronous data processing capabilities
SSIS

ETL

MSMS

WMI
SQL Server Integration Service

Extract, Transform, Load

Microsoft Message Queue

Windows Management Instrumentation
Describe the SSIS?
feature all the capabilities you can find in ETL + to build apps. that can manage db and system resources, respond to DB and System event, while interacting with user
SSIS additional functionality
ftp and folder manipulation

import/export files in DB

interact with Web service

respond to WMI event
What containers allow SSIS
to execute entire tasks and workflows within a loop with a variety of inputs
Specialized tasks included in SSIS part1

(4)
copy SQL Server objects

manage DB backups

re-indexing

extendibility with VSTA
What does SSRS stand for?
SQL Server Reporting Service

platform for designing reports and distributing data
What are the SSRS components?
report server

report designer
What does SSAS stand for? What does it do?
SQL Server Analysis Service

create to fill the gap between the data needs of business and the ability if IT to provide data.
What are the SSAS components?
Online Analytical Processing

Data Mining
What does OLAP stand for?
Online Analytical Processing
What does BIDS stand for?
Business Intelligence Development Studio
Data Mining engine use
Allows users to find patterns and make predictions. It could be used examine data trends over time.
What is an enumeration request?
Applications can broadcast a special command request across a network to locate any servers running SQL server. By disabling enumeration responses by setting the Hide Instances to Yes you will prevent discovery of you SQL server preventing a possible attack.
What are the possible profile configurations and what do that do?
public - can be accessed by any user with the ability to send mail

private - cab be accessed only by those users who have been granted access to the mail profile explicitly
What happens to Database Mail if SQL Server Agent is not running?
Messages will accumulate in a queue within the MSDB database
What is the query to enable Database Mail feature
EXEC sp_configure 'Database Mail XPs', 1
GO

RECONFIGURE WITH OVERRIDE
GO
What service database does mail utilize?
SQL Server Agent is used to send messages as a background process.
What happens if SQL Server Agent is not running
Messages accumulate in queue within the Msdb database.
How many mail accounts can a mail profile contain?
One and more
What are notification Services?
A feature that was available in SQL 2005 that is not longer available in 2008.
What is Activity Monitor?
It is a feature of SSMS that displays query activity on the server.
What is the first thing you can do on the path to achieving optimal performance disk I/O performance?
Separate the transaction logs from data files so that you can isolate disk I/O.
Types of files are used by SQL Server?
Data and transaction logs.
What are data files for?
Data files are responsible for the long-term storage of all the data within a DB.
What are transaction log files for?
Responsible for storing all the transactions that are executed against a DB
Three thing about the .mdf extension?
1) First data file created within a DB
2) Associated with the primary filegroup
3) Primary data file which contains all the system objects necessary to a database
What is the .ndf extension?
Used for all other data files underneath a DB regardless of the filegroup to which the file is associated.
What is the .ldf extension?
Used for the transaction logs.
Describe the check pointing process.
All data manipulation within SQL occurs in memory within a set of buffers. Data is first written to a memory buffer, then written to the transaction log, and finally persisted to a data file via a background process called check pointing.
What is the DEFAULT property for a filegroup?
It is used to define the filegroup where SQL Server places objects if you do not specify the ON clause during object creation.
Why would you change the default filegroup?
After you create a DB you should mark the second filegroup as the default filegroup. By changing the default filegroup, you ensure that any object you create are not accidentally placed on the primary filegroup.
What is the command for changing the default filegroup?
ALTER DATABASE <db name. MODIFY FILEGROUP <fg name> DEFAULT
What is the main reason not to place any of your objects on the primary filegroup is?
To provide as much isolation in the I/O as possible.
Give several reasons to use secondary filegroup vs. primary filegroup.
1) To provide as much isolation in the I/O as possible .

2) The data in the system object doesn't change as often as data in your object.

3) By minimizing the write activity to the primary data file you reduce the possibility of introducing corruption due to hardware failures.

4) Increase the availability of the DB by minimizing the changes made to the primary filegroup.
What determines the state of the DB?
The state of the primary filegroup determines the state of the database. You can increase the availability of the database by minimizing the changes made to the primary filegroup.
How does SQL Server write to the transaction log?
Sequentially
When does SQL Server read from the log?
Only during restart recoveries.
What does FILESTREAM allows you to do?
To associate files with a database. The files are stored in a folder on the OS, but are linked directly into A DB where the files can be backed up, restored, full-text-indexed, and combined with other structured data.
What does the tempdb database do?
temporary objects

workstables used in grouping/storing

worktables to support cursors

version store supporting snapshot isolation level

overflow for table variables
What would you ever do multiple tempdb databases?
Common practice for tempdb is to create one file per processor. The one file per processor is with respect to what SQL Server would consider a processor and not the physical processor, which could have multiple cores as well as hyper-threading.
Generally, what is the Recover model in SQL Server?
Every DB within a SQL Server instance has a property setting called the recovery model. Define the type of backups you can perform against a DB.
Describe the Full Recovery Mode.
All changes made using both DML and DDL are logged to the transaction log. It is possible to recover a DB in the Full recovery model to a give point in time so that data loss can be minimized.'
What is the best practice recovery model?
Every production DB that accepts transactions should be set to the Full recovery model.
What is the Bulk-logged recovery model?
It allows certain operations to be executed with minimal logged. When a minimally logged operation is performed, SQL Server does not log every row changed but only the extents, reducing over head and improving performance.
What are the five operations that are performed in minimally logged manner with the DB set in bulk-logged recovery?
BCP

BULK INSERT

SELECT..INTO

CREATE INDEX

ALTER INDEX .. REBUILD
Describe the simple recovery model.
A DB in Simple recovery model logs operations to the transaction log exactly as the Full recovery model does. However, each time the DB checkpoint process executes, the committed portion of the transaction log is discarded.
What is the Cmd for setting DB recovery model
"ALTER DATABASE database_name SET RECOVERY { FULL / BULK_LOGGED / SIMPLE }"
How do pages get damaged in SQL Server?
It is possible to damage data pages during a write to a disk if you have a power failure or failures in disk subsystem components during the write operation. Because the damage happens to a page on disk the only time that you see a result of the damage is when SQL Server attempts to read the page off disk.
What command allows you to discover and log damaged pages?
PAGE_VERIFY CHECKSUM
Does SQL Server by default checks for damaged pages?
No, you need to turn PAGE_VERIFY CHECKSUM to have SQL check for damaged pages.
What is the default thing to happen in a SQL Server DB if a damaged page is found?
The default config of SQL Server does not check for damaged pages and could cause the DB to go off-line if a damaged page is encountered.
When is error 824 returned?
What error is returned to the calling application and logged to SQL Server error log and Windows Application Event Log and the ID of the damaged page is logged to the suspect_pages table in the msdb DB.
What do the AUTO OPTIONS do in SQL Server?
The AUTO database options are those that enable certain actions to occur automatically.
List five AUTO OPTIONS.
AUTO_CLOSE

AUTO_SHRINK

AUTO_CREATE_STATISTICS

AUTO_UPDATE_STATISTICS

AUTO_UPDATE_STATISTICS_ASYNCH
Best practices for AUTO_SHRINK
Disabled and manually shrink files only when needed.
Access to a DB is controlled with this options
ONLINE

OFFLINE

EMERGENCY
DB is in ONLINE STATE
You can perform all operations that that would otherwise be possible.
What happens to a damaged data page is SQL Server is part of mirroring session?
SQL Server2008 automatically replaces the page with a copy of the page from the mirror. An entry is logged and can be reviewed with the sys.dm_db_mirroring_auto_page repair view
What SQL Server does with every query's plan when the query is executed
SQL caches the query plan. When a query is executed, SQL Server parses and compile the query. Then the query is compared to the query cache. If match is found, SQL Server retrieves the plan that has already been generated and executes the query.
What are the options that PAGE_VERIFY can be set to?
TORN_PAGE_DETECTION

CHECKSUM
What is PAGE_VERIFY TORN_PAGE_DETECTION?
Exist only for backward compatibility should not be used
What is PAGE_VERIFY CHECKSUM?
SQL Server calculates a checksum for the page prior to the write. Each time a page is read off disk, a checksum is recalculated and compared to the checksum write to the page. If the checksum do not match, the page has been corrupted.
What is the DBCC CHECKDB command?
You can force SQL Server to read every page from the disk and check the integrity by executing the DBCC CHECKDB cmd.
Schemas explanation?
In addition to being a security structure, a schema provides a convenient mechanism to group objects together within a DB.
Syntax to create schema?
CREATE SCHEMA <schema name> AUTHORIZATION <owner name>
What are the numeric data types? 9 of them.
TINYINT

SMALLINT

INT

BIGINT

DECIMAL(P,S)

NUMERIC(P,S)

SMALLMONEY

MONEY

REAL

FLOAT
What option would you specify on a column to control the collation behavior?
COLLATE works only of a character-based column.
32 bit minimal requirements

64 bit maximum requirements
p3 1gh 512mb

Itanium, Opteron, Athlon, Xeon 1.6ghz 512mb
OS supported for all editions of SQL Servers are
Windows Server 2008 Standard and up

Windows Server 2003 Standard SP2 or up
SQL Developer, Evaluation and Express are supported
Windows XP Pro Sp2 and up

Vista Home Basic or up
SQL Express
Xp Home and up
Xp Home Reduced Media Edition
Xp Table Edition SP2 or up
Xp Media Center 2002 SP2 or up
Xp Pro Reduced Media Edition
Xp Pro Embedded Edition Sp2
Xp Pro Embedded Edition
Is SQL server 2008 is not supported on
Windows Server 2008 Server Core, because .Net Framework is not supported on Server Core. SQL Server 2008 relies on .Net framework capabilities to support FILESTREAM, SPATIAL, and DATE data types, along whit server additional features.
What version of .Net is required by SQL 2008
.Net Framework 3.5 and Windows Installer 4.5
SQL Server requires

(7)
.Net framework 3.5

Microsoft Data Access Components 2.8 SP1

Share Memory

Named Pipe

TCP/IP networking support

IE 6 SP1 and up
Service Broker

(descr.)
Intro in SQL 2005 message queuing system. Based on user-defined messages and processing actions, it provides asynchronous data processing capabilities.
SSIS

ETL

MSMS

WMI
SQL Server Integration Service

Extract, Transform, Load

Microsoft Message Queue

Windows Management Instrumentation
SSIS

(descr.)
Feature all the capabilities you can find in ETL + to build apps. That can manage db and system resources, respond to DB and System event, while interacting with user.
SSIS additional func.

(4)
ftp and folder manipulation

import/export files in DB

interact with Web service

respond to WMI event
DDL triggers
Allow you to trap and respond to login events. You can scope DDL triggers at instance or a DB level.
Generic syntax for creating a DDL trigger
CREATE TRIGGER trigger_name
ON { ALL SERVER / DATABASE }
[ WITH <ddl_trigger_option> [ ,...n ] ]
{ FOR / AFTER } { event_type / event_group } [ ,...n ]
AS { sql_statement [ ; ] [ ,...n ] / EXTERNAL NAME < method specifier > [ ; ] }

<ddl_trigger_option> ::=
[ ENCRYPTION ]
[ EXECUTE AS Clause ]
DDL not applicable
When a query (like ALTER TABLE) changes the file structure in windows cannot be rolled back.
DDL triggers most important feature
DDL triggers is ability to roll back an action. The Policy-Based Management Framework creates DDL triggers for all policies that you configure to prevent an out-of-compliance situation.
EVENTDATA()
Within the execution context of the DDL trigger, you have access to a special function, that provide information about the DDL action.

Returns an XML document with a structure depending upon the event.
General syntax for creating a server audit
CREATE SERVER AUDIT audit_name

{
TO { [ FILE (<file_options> [ , ...n ]) ] / APPLICATION_LOG / SECURITY_LOG }
[ WITH ( <audit_options> [ , ...n ] ) ]
}

[ ; ]

<file_options>::=

{
FILEPATH = 'os_file_path'
[ , MAXSIZE = { max_size { MB / GB / TB } / UNLIMITED } ]
[ , MAX_ROLLOVER_FILES = { integer / UNLIMITED } ]
[ , RESERVE_DISK_SPACE = { ON / OFF } ]

}


<audit_options>::=

{
[ QUEUE_DELAY = integer ]
[ , ON_FAILURE = { CONTINUE / SHUTDOWN } ]
[ , AUDIT_GUID = uniqueidentifier ]
}
SQL Server 2008 auditing capabilities
Combines all the auditing capabilities into an audit specification.

Audit specification begin with a server-level audit object that define the logging location for the audit trial.

Audits can be created on server/database.
QUEUE_DELAY option of CREATE SERVER AUDIT
When = 0 audit records are sent to the audit log synchronously
ON_FAILURE option of CREATE SERVER AUDIT
Control how the instance behaves if audit records cannot be written.

CONTINUE(default) - instance continues running and processing transactions

SHUTDOWN - instance shuts down
CREATE SERVER AUDIT
creates an instance of an audit object
Possible way to encrypt
hash

passphrase

symmetric key

asymmetric key

certificates
What encryption SQL uses to handle password encryption
MD5
List of (5) hash algorithms available in SQL
SHA

SHA1

MD2

MD4

MD5(recommended)
TDE
Transparent data encryption

Provides real time encryption and decryption service to ensure that data within the files and backups is encrypted.'
The process of implementing TDE.
1) Create a DB master key in the master DB

2) Create a certificate in the master database

3) Create a DB encryption key in the target DB using the certificate in the master DB

4) Alter the DB and enable encryption
EKM
Extensible Key Management

Feature in SQL Server 2008 allowing it to integrate with enterprise key management.

Keys can be maintained in a central location within an enterprise and exported for use within SQL Server.
What are the item that you can capture data for with System Monitor?
Objects

Counters

Counter instances
What types of data can System monitor capture?
System Monitor captures numeric data for performance counters that are defined for hardware or software components
What are the three counters that, by themselves, indicate a system problem?
S: Processor Queue Length

Network Interface: Output Queue Length

Physical Disk:Avg.Disk Queue Length
System Monitor use
To capture numeric statistics about hardware and software components.
Counters three-level hierarchy
Counter object

counter

counter instance
A counter must have at least on .......
Counter
Counter can have.......
zero and more instances
Blank profiler trace template
An empty trace; allows you to create an entire trace from scratch.
SP_Counts profiler trace template
Captures each stored procedure executed so that you can determine how many of each procedure is being executed.
Standard profiler trace template
The most common template to start with; captures stored procedure and ad hoc SQL being executed along with performance statistics for each procedure and bath. Every login and logout is also captured.
TSQL profiler trace template
Captures a list of all the stored procedures and ad hoc SQL batches that are executed, but doesnt include any performance statistics.
TSQL_Duration profiler trace template
Captures the duration of every stored procedure and ad hoc SQL batch that is executed.
TSQL_Grouped profiler trace templates
Captures every login and logout along with the stored procedures and ad hoc SQL batches that are executed. Includes information to identify the application and user executing the request but does not include any performance data.
TSQL_Locks profiler trace templates
Captures blocking and deadlock information such as blocked processes, deadlock chains, deadlock graph, lock escalation, and lock timeouts. This template also captures every stored procedure, each command within a stored procedure, and every ad hoc SQL request.
TSQL_Replay profiler trace templates
Captures the stored procedures and ad hoc SQL batches executed against the instance in a format that allows you to replay the trace against a test system. This template is commonly used to perform load and regression tests.
TSQL_SPs profiler trace templates
Captures performance data for all ad hoc SQL batches, stored procedures and each statement inside a stored procedure. Every login and logout is also captured.
Tuning profiler trace templates
Captures basic performance information for ad hoc SQL batches stored procedures, and each statement inside a stored procedure.
Broker SQL trace Event Groups
13 events for Service Broker message, queues, and conversations
CLR SQL trace Event Groups
1 event for the loading of a Common Language Runtime assembly
Cursors
7 events for the creation, access, and disposal of cursors
Database SQL trace Event Groups
6 events for data/log file/grow/shrink as well as Database Mirroring state changes
Deprecation SQL trace Event Groups
2 events for errors, warnings, and information messages being logged. Events to detect suspect pages, blocked processes, and missing column statistics.
Errors and Warnings SQL trace Event Groups
16 events for errors, warnings, and information messages being logged. Events to detect suspect pages, blocked processes, and missing column statistics.
Full Text SQL trace Event Groups
3 events to track the progress of a full text index crawl
Full Text SQL trace Event Groups
3 events to track the progress of a fill text index crawl
Locks SQL trace Event Groups
9 events for lock acquisition, escalation, release, and deadlocks
OLEDB SQL trace Event Groups
5 events for distributed queries and remote stored procedure calls
Objects SQL trace Event Groups
3 events that track when an object is created, altered, or dropped
Performance SQL trace Event Groups
14 events that allow you to capture show plans, use of plan guides, and parallelism. This event group also allows you to capture full text queries.
Progress Report SQL trace Event Groups
1 event for online index creation progress
Query Notification SQL trace Event Groups
4 events to tack the parameters, subscription, and templates for query notifications
Scans SQL trace Event Groups
2 events to track when a table or index is scanned
Security Audit SQL trace Event Groups
44 events to track the use of permissions, impersonations, changes to security objects, management actions are taken to objects, start/stop of an instance, and backup/restore of a database.
Server SQL trace Event Groups
3 events for mounting a tape, change to the server memory, and closing a trace file.
Sessions SQL trace Event Groups
3 events for existing connections when the trace starts as well as tracking the execution of logon triggers and resource governor classifier functions.
Stored procedures SQL trace Event Groups
12 events for the execution of a stored procedure, cache usage, recompilation, and statements within a stored procedure.
Transactions SQL trace Event Groups
13 events for the begin, save, commit, and rollback of transactions
TSQL SQL trace Event Groups
9 events for the execution of ad hoc T-SQL or XQuery calls. Events for an entire SQL batch as well as each statement within a batch.
User Configurable SQL trace Event Groups
10 events that you can configure with SQL Trace
model db use
model d=database is used as the template for all databases created on an instance of SQL Server.

Because tempdb is created every time SQL Server is started, the model database must always exist on a SQL Server system.
msdb use
Used by SQL Server Agent for scheduling alerts and jobs and by other features such as Service Broker and Database Mail.
SQL Server Profiler purpose
Application that allows you to define graphically settings that are translated into stored procedure calls to create and manage traces.
What is a trace?
Collection of stored procedures to create trace on a instance.

Traces can be stopped, started, ended and paused.
Trace behavior
1) After trace is started SQL Server Trace API returns only events matching the trace definition all other are discarded.

2) When trace is stopped, all event collection terminates, and if the race is started again all previous data is cleared.

3) To temporary stop data collection for a trace you can pause it.
sp_trace_create

(SQL Trace Event Group)
A stored procedure that creates a new trace object.

Equivalent to the definition on the General tab of the New Trace dialog in Profiler.
sp_trace_generateevent

(SQL Trace Event Group)
A stored procedure that allows you to define your own trace event.
sp_trace_setevent

(SQL Trace Event Group)
A stored procedure that adds a data column for an event to be captured by a trace.

You need to call sp_trace_setevent once for each data column being captured for an event.

Equivalent to the event and data column selection grid in the Events Selection tab of the New Trace dialog in Profiler.
sp_trace_setfilter

(SQL Trace Event Group)
A stored procedure that adds a filter to a trace.

Equivalent to the Edit Filter dialog box in Profiler.
sp_trace_setstatus

(SQL Trace Event Group)
A stored procedure that starts, stops, and closes a trace.

A status of 0 stops a trace.

1 starts
2 closes and remove the trace from the instance
fn_trace_geteventinfo

(SQL Trace Event Group)
A function that return the filters applied to a specified trace.
fn_trace_getfilterinfo

(SQL Trace Event Group)
A function that return the filters applied to a specified trace.
fn_trace_getfilterinfo

(SQL Trace Event Group)
A function that returns the filters applied to a specified trace.
fn_trace_getinfo

(SQL Trace Event Group)
A function that returns status and property information about all traces defined in the instance.
fn_trace_gettab
A function that reads one of more trace files and return the contents as a result set. Commonly used to import trace files into a table.
retrieve the contents of the current error log as a result set by executing the system extended stored procedure
sys.xp_readerrorlog
Where are errors and info messages related to SQL Server Agent found SQL Server Agent Log file named....
sqlagent.out
Where is the database mail log contained in the
dbo.sysmail_log table in msdb database
What happens when you run out of space in the transaction log?
(4)
All write activity to the DB stops.

You can still read from the db.

Write operations roll back with error 9002 send back to the application.

Error is written to Windows Application Log.
error 1101 or 1105
Database has run out of disk space.

You cant insert new data.
MARS
Multiple active result sets
1101, 1105, 9002

3958, 3959, 3966 and 3967
Space issues for the tempdb are encountered.
9002 error
When you run out of transaction log space.
1101 and 1105 error
When the data files are out of space.
SQL Startup sequence
1) Master db is brought online

2) Tempdb is recreated

3) Write occurs to the folder that store the data and log files
???
Boots SQL server in single user mode

Allows to change location of tempdb
???
List the location and the filename for the master table.
???
Lists the location and file name of the master transaction log file.
???
Lists the name and location of the Sql error log.
???
Adding a trace flags.
How to rebuild a master database in SQL Server 2008
Using the new Installation Center Event through it still uses setup.
use for distribution database
If you have configured replication this is one of our system tables.
mssqlsystemresource
Intro in 2005

contains stored procedures

functions

DMV is by default hidden
Kill all connections to a DB.
DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'navigator1'

DECLARE @SQL varchar(max)
SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'

FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

--SELECT @SQL
EXEC(@SQL)
Convert from decimal to hex.
convert(varbinary(16),<column>)
Utilities to view the state and configuration of SQL Server service.
Windows Service Console

SQL Server Configuration Manager
SQL Server starts up
1) Master DB is brought online.

2) Tempdb is re-created.

3) Creation of tempdb causes a write to occur to the folder that stores the data and log files for tempdb.
Sql server single user mode
Use the -m code
Device activation error
SQL Server could not access a data or log file for a database.
What device activation errors for tempdb and master do?
Prevent the instance from starting.
SQL Server service account
Dedicated account per service

3 choices

local user account
domain user account
built in user account
When to use local user account for SQL?
If SQL is not part of a Domain.
When to use domain user account for SQL?
99% of the time

If service will interact with network services, access resources like file shares or multiple linked server connections to other SQL Servers.
When to use built in system accounts?
bad choices
master db purpose and use
Main system database.

DB of all DBs

1 of for each service
model db purpose and use
Used as a template for creating user DB

Changes here are reflected to all new user DB
msdb purpose and use
Stores info related to automation

SQL Server agents and jobs schedule
???
Lists the location and file name for the master data file.
???
Lists the location and file name of the master transaction log file.
???
Lists the name and location of the Sql Server error log.
???
Adding trace flag.
How you fix a corrupt master db
By running SQL Server installation.
distribution DB(sys db)
If you have configured replication you also see a database named distribution.
mssqlsystemresource DB(sys db)
Introduced in SQL 2005

Contains most of the store procedure, function, DMV and other code that ships with SQL.

DB is usually hidden
device activation error indicates what???
That SQL Server either cannot find or cannot write to a data or log file.