* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Lesson04 Advanced SQL
Serializability wikipedia , lookup
Oracle Database wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Microsoft SQL Server wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Ingres (database) wikipedia , lookup
Concurrency control wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Functional Database Model wikipedia , lookup
Versant Object Database wikipedia , lookup
Clusterpoint wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
ContactPoint wikipedia , lookup
Advanced SQL - DDL
Advanced Database
Dr. AlaaEddin Almabhouh
Topic & Structure Lesson
DDL Statements
Planning your Database
Database Files
Database Schemas
Creating Databases
SQL Data Types
User Defined Data Types
Creating Tables
Slide 2 (of 82)
DDL Statements
SQL DDL allows database objects such as schemas,
domains, tables, views, and indexes to be created and
destroyed.
CREATE statements
DROP statements
To make a new database, table, index, stored procedure, or other
database objects.
To destroy an existing database, table, index, view, etc.
ALTER statements
To modify an existing database objects.
Slide 2 (of 82)
Data Definition
Main SQL DDL statements are:
CREATE DATABASE
CREATE SCHEMA
CREATE TABLE
CREATE VIEW
DROP DATABASE
DROP SCHEMA
DROP TABLE
DROP VIEW
ALTER DATABASE
ALTER SCHEMA
ALTER TABLE
ALTER VIEW
Many DBMSs also provide:
CREATE INDEX
DROP INDEX
ALTER INDEX
Slide 19 (of 82)
Planning your Database
SQL Server uses two types of files to store your
database information:
One or more database files.
One or more transaction log files.
Database Files
Everything in the Model database shows up in your
newly created database.
Once the copy of the database has been made, it
expands to the requested size.
When you create a database in SQL Server, you must
specify at least one file to store the data and hold
your system tables and another file to hold the
transaction log.
Database Files
Databases can comprise up to three file types.
Primary data files have a default extension of
.mdf.
If you create a database that spans multiple data
files, then secondary data files are used, which
have a default filename extension of .ndf.
The transaction log is stored in one or more files,
each with a default .ldf extension.
Database Files
Database Files
You should remember several important facts about
your data and log files:
Create the data and log files on a storage area
network or locally attached drive.
You may have one database per data file although a
single database can span multiple data files.
Transaction logs must reside in their own file; they
can also span multiple log files.
Transaction Logging
1 Data modification is
sent by application
Modification is recorded
Buffer
Cache
3 in transaction log on disk
Disk
Data pages are located in,
2 or read into, buffer cache
and modified
Disk
Checkpoint writes
4 committed transactions
to database
Tip: Place log on separate drive for performance
Slide 2 (of 82)
What Are Filegroups?
A filegroup is a logical collection of data files that enables
administrators to manage all files within the filegroup as a
single item.
SQL Server has a primary filegroup and can also have
user-defined filegroups:
The primary filegroup contains the primary data file with the
system tables. The primary data file typically uses the .mdf
extension.
A user-defined filegroup consists of data files that are grouped
together for allocation and administrative purposes. These
other data files are known as secondary data files and typically
use the .ndf extension.
Advantages of Filegroups
You can logically group database files into a
filegroup.
Using filegroups, you can explicitly place database
objects into a particular set of database files.
Another advantage of filegroups is the ability to
backup only a single filegroup at a time.
Yet another advantage includes the ability to mark
the filegroup and all data in the files that are part
of it as either read-only or read-write.
Disadvantages Filegroups
There are really only two disadvantages to
using filegroups.
The administrative effort involved in keeping track
of the files in the filegroup and the database objects
that are placed in them.
If you are working with a smaller database and have
RAID-5 implemented, you may not be improving
performance.
AdventureWorks Database
sys...
sys...
sysusers
sysobjects
C:\
AdventureWorks_
Data.mdf
Default Filegroup
...
SalesOrderHeader
Customer
Product
D:\
OrdHist1.ndf
OrdHist2.ndf
OrderHistoryGroup
OrdHistYear2
OrdHistYear1
E:\
AdventureWorks_
Log.Idf
When to Create Filegroups
• Use multiple files in a single filegroup for
performance
• Use multiple filegroups to control data
placement
What Are Schemas?
A schema is a namespace for database objects.
In other words, a schema defines a boundary
within which all names are unique.
Schema is logical named collection of related
database objects.
Objects in a schema can be tables, views,
collations, and character sets. All have same
owner
What Are Schemas?
Namespaces for database objects
Person
Contact
(Server1.AdventureWorks.Person.Co
ntact)
Sales
Customer
(Server1.AdventureWorks.Sales.Cust
omer)
dbo
ErrorLog
(Server1.AdventureWorks.dbo.ErrorL
og)
AdventureWorks
How Object Name Resolution Works
Person
SELECT * FROM Contact
Lance
(Default schema = Person)
SELECT * FROM Person.Contact
Contact
Sales
SELECT * FROM ErrorLog
SELECT * FROM Contact
Anders
(Default schema = Sales)
dbo
ErrorLog
Syntax: Creating Database
CREATE DATABASE database_name
[ ON
[ PRIMARY ] [ <filespec> [ ,...n ]
[ , <filegroup> [ ,...n ] ]
[ LOG ON { <filespec> [ ,...n ] } ]
]
[ COLLATE collation_name ]
[ WITH <external_access_option> ]
]
[;]
Example: Creating Database
CREATE DATABASE Sales ON
( NAME = Sales_dat,
FILENAME = '''+ @data_path + 'saledat.mdf'',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = Sales_log,
FILENAME = '''+ @data_path + 'salelog.ldf'',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB )
Creating Schemas
Syntax:
CREATE SCHEMA schema_name
[AUTHORIZATION owner_name]
Example:
CREATE SCHEMA Person
CREATE SCHEMA HumanResources
AUTHORIZATION Alen
What Are System-Supplied Data Types?
Category
Numeric
Integer
int, bigint, smallint, tinyint
Exact
decimal, numeric
Approximate
float, real
Monetary
money, smallmoney
Date and time
Character
Data types
datetime, smalldatetime
Non-Unicode
char, varchar, varchar(max), text
Unicode
nchar, nvarchar, nvarchar(max), ntext
Binary
binary, varbinary, varbinary(max)
Image
image
Global identifier
uniqueidentifier
XML
xml
What are User Defined Data Types?
Based on system-supplied types
Used for common data elements with a specific format
Created by using the CREATE TYPE statement
To modify a user-defined type, you must drop the type by
using a DROP TYPE statement and then re-create it.
CREATE TYPE Price
FROM Money
Not NULL
CREATE RULE range_rule
AS
@range>=1 AND @range<2000;
To bind a rule to user defined data type
EXEC sp_bindrule 'rule_name', 'type_name'
CREATE TABLE
Creates a table with one or more columns of the
specified dataType.
With NOT NULL, system rejects any attempt to
insert a null in the column.
Can specify a DEFAULT value for the column.
Primary keys should always be specified as NOT
NULL.
FOREIGN KEY clause specifies FK along with the
referential action
Slide 23 (of 82)
Syntax: Creating Tables
CREATE TABLE
[ database_name] . [ schema_name ] . table_name
(
<column_definition>
column_name <data_type> [ NULL | NOT NULL ]
[ CONSTRAINT constraint_name ]
[DEFAULT constant_expression ]
[ IDENTITY [ ( seed ,increment ) ]
[ NOT FOR REPLICATION ]
[References table_name(field_name) ]
[ ...n ]
)
[Primary Key]
Example: Creating Tables
CREATE TABLE [dbo].[PurchaseOrderDetail]
(
[PurchaseOrderID] [int] NOT NULL
REFERENCES Purchasing.PurchaseOrderHeader(PurchaseOrderID),
[LineNumber] [smallint] NOT NULL,
[ProductID] [int] NULL
REFERENCES Production.Product(ProductID),
[UnitPrice] [money] NULL,
[OrderQty] [smallint] NULL,
[ReceivedQty] [float] NULL,
[RejectedQty] [float] NULL,
[DueDate] [datetime] NULL,
[rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL
CONSTRAINT [DF_PurchaseOrderDetail_rowguid] DEFAULT (newid()),
[ModifiedDate] [datetime] NOT NULL
CONSTRAINT [DF_PurchaseOrderDetail_ModifiedDate] DEFAULT (getdate()),
[LineTotal] AS (([UnitPrice]*[OrderQty])),
[StockedQty] AS (([ReceivedQty]-[RejectedQty])),
CONSTRAINT [PK_PurchaseOrderDetail_PurchaseOrderID_LineNumber]
PRIMARY KEY CLUSTERED ([PurchaseOrderID], [LineNumber])
)
ON [PRIMARY]
Considerations for Creating Tables
Column collation
Column nullability
Special column types
Identity columns – Identity Specification property
Computed columns – Formula property
uniqueidentifier columns – NEWID() function
CREATE TABLE Sales.CustomerOrders
(OrderID int IDENTITY NOT NULL,
OrderDate datetime NOT NULL,
CustomerID int NOT NULL,
Notes nvarchar(200) NULL)
ALTER TABLE
Add a new column to a table.
Drop a column from a table.
Add a new table constraint.
Drop a table constraint.
Set a default for a column.
Drop a default for a column.
Slide 26 (of 82)
Example - ALTER TABLE
Adds a column that allows null values
ALTER TABLE Staff
ADD title VARCHAR(20) NULL ;
Modifies a table to remove a column
ALTER TABLE Staff
DROP COLUMN position;
Changes a column of a table from INT to DECIMAL
ALTER TABLE Staff
ALTER COLUMN salary DECIMAL (5, 2);
Slide 27 (of 82)
DROP TABLE
DROP TABLE TableName [RESTRICT | CASCADE]
e.g.
DROP TABLE PropertyForRent;
Removes named table and all rows within it.
With RESTRICT, if any other objects depend for their
existence on continued existence of this table, SQL
does not allow request.
With CASCADE, SQL drops all dependent objects
(and objects dependent on these objects).
Slide 29 (of 82)
TRUNCATE TABLE
Removes all rows from a table without logging the
individual row deletions.
TRUNCATE TABLE is similar to the DELETE statement
with no WHERE clause.
The DELETE statement removes rows one at a time and
records an entry in the transaction log for each deleted
row. TRUNCATE TABLE removes the data by deallocating
the data pages used to store the table data and records
only the page deallocations in the transaction log.
Syntax: TRUNCATE TABLE table_name
Q&A
Slide 32 of 15