Download presentation
Presentation is loading. Please wait.
Published byAnna Mathews Modified over 8 years ago
1
Advanced SQL - DDL Advanced Database Dr. AlaaEddin Almabhouh
2
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)
3
DDL Statements SQL DDL allows database objects such as schemas, domains, tables, views, and indexes to be created and destroyed. CREATE statements To make a new database, table, index, stored procedure, or other database objects. DROP statements To destroy an existing database, table, index, view, etc. ALTER statements To modify an existing database objects. Slide 2 (of 82)
4
Data Definition Main SQL DDL statements are: CREATE DATABASEDROP DATABASEALTER DATABASE CREATE SCHEMADROP SCHEMA ALTER SCHEMA CREATE TABLEDROP TABLE ALTER TABLE CREATE VIEWDROP VIEW ALTER VIEW Many DBMSs also provide: CREATE INDEXDROP INDEXALTER INDEX Slide 19 (of 82)
5
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.
6
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.
7
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.
8
Database Files
9
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.
10
Transaction Logging Slide 2 (of 82) Data pages are located in, or read into, buffer cache and modified Data pages are located in, or read into, buffer cache and modified 2 2 Modification is recorded in transaction log on disk 3 3 Checkpoint writes committed transactions to database 4 4 Data modification is sent by application Data modification is sent by application 1 1 Tip: Place log on separate drive for performance Disk Buffer Cache
11
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.
12
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.
13
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.
14
AdventureWorks Database Default FilegroupOrderHistoryGroup E:\ C:\ D:\ AdventureWorks_ Log.Idf AdventureWorks_ Data.mdf OrdHist2.ndf OrdHist1.ndf sys... sysusers sysobjects... SalesOrderHeader Customer Product OrdHistYear2 OrdHistYear1
15
When to Create Filegroups Use multiple files in a single filegroup for performance Use multiple filegroups to control data placement
16
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
17
What Are Schemas? Namespaces for database objects Person Contact (Server1.AdventureWorks.Person.Co ntact) Sales Customer (Server1.AdventureWorks.Sales.Cust omer) AdventureWorks dbo ErrorLog (Server1.AdventureWorks.dbo.ErrorL og)
18
Sales Contact Person How Object Name Resolution Works SELECT * FROM Person.Contact Lance (Default schema = Person) Anders (Default schema = Sales) ErrorLog dbo SELECT * FROM Contact SELECT * FROM ErrorLog
19
Syntax: Creating Database CREATE DATABASE database_name [ ON [ PRIMARY ] [ [,...n ] [, [,...n ] ] [ LOG ON { [,...n ] } ] ] [ COLLATE collation_name ] [ WITH ] ] [;]
20
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 )
21
Creating Schemas Syntax: CREATE SCHEMA schema_name [AUTHORIZATION owner_name] Example: CREATE SCHEMA Person CREATE SCHEMA HumanResources AUTHORIZATION Alen
22
What Are System-Supplied Data Types? CategoryData types Numeric Integer int, bigint, smallint, tinyint Exact decimal, numeric Approximate float, real Monetary money, smallmoney Date and time datetime, smalldatetime Character 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
23
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. 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 TYPE Price FROM Money Not NULL CREATE RULE range_rule AS @range>=1 AND @range<2000; 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'
24
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)
25
Syntax: Creating Tables CREATE TABLE [ database_name]. [ schema_name ]. table_name ( column_name [ NULL | NOT NULL ] [Primary Key] [ CONSTRAINT constraint_name ] [DEFAULT constant_expression ] [ IDENTITY [ ( seed,increment ) ] [ NOT FOR REPLICATION ] [References table_name(field_name) ] [...n ] )
26
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]
27
Column collation Column nullability Special column types Identity columns – Identity Specification property Computed columns – Formula property uniqueidentifier columns – NEWID() function Column collation Column nullability Special column types Identity columns – Identity Specification property Computed columns – Formula property uniqueidentifier columns – NEWID() function Considerations for Creating Tables CREATE TABLE Sales.CustomerOrders (OrderID int IDENTITY NOT NULL, OrderDate datetime NOT NULL, CustomerID int NOT NULL, Notes nvarchar(200) NULL) CREATE TABLE Sales.CustomerOrders (OrderID int IDENTITY NOT NULL, OrderDate datetime NOT NULL, CustomerID int NOT NULL, Notes nvarchar(200) NULL)
28
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)
29
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)
30
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)
31
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
32
Slide 32 of 15 Q & A
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.