Advanced SQL - DDL Advanced Database Dr. AlaaEddin Almabhouh.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Project Management Database and SQL Server Katmai New Features Qingsong Yao
Module 4: Creating Data Types and Tables. Overview Creating Data Types Creating Tables Generating Column Values Generating Scripts.
1 Pertemuan 11 SQL Data Definition Matakuliah: >/ > Tahun: > Versi: >
Murali Mani SQL DDL and Oracle utilities. Murali Mani Datatypes in SQL INT (or) INTEGER FLOAT (or) REAL DECIMAL (n, m) CHAR (n) VARCHAR (n) DATE, TIME.
Creating Tables, Defining Constraints Rose-Hulman Institute of Technology Curt Clifton.
SQL DDL constraints Restrictions on the columns and tables 1SQL DDL Constraints.
1 Nassau Community CollegeProf. Vincent Costa Acknowledgements: Introduction to Database Management, All Rights ReservedIntroduction to Database Management.
Working with SQL and PL/SQL/ Session 1 / 1 of 27 SQL Server Architecture.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Session 7 Creating and Managing Databases. RDBMS and Data Management/ Session 7/2 of 27 Session Objectives Describe the system and user-defined databases.
Introduction to SQL  SQL or sequel  It is a standardised language with thousands of pages in the standard  It can be in database system through GUI,
Oracle Data Definition Language (DDL)
Overview What is SQL Server? Creating databases Administration Security Backup.
© 2002 by Prentice Hall 1 David M. Kroenke Database Processing Eighth Edition Chapter 13 Managing Databases with SQL Server 2000.
Chapter 4 SQL. SQL server Microsoft SQL Server is a client/server database management system. Microsoft SQL Server is a client/server database management.
Database Technical Session By: Prof. Adarsh Patel.
Databases Lesson 5.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Chapter 7 SQL HUANG XUEHUA. SQL SQL server2005 introduction Install components  management studio.
Architecture Rajesh. Components of Database Engine.
Oracle Data Definition Language (DDL) Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2008.
SQL Data Definition Language (DDL) Using Microsoft SQL Server 1SDL Data Definition Language (DDL)
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
Chapter 5: Part 1: DDL STRUCTURED QUERY LANGUAGE (SQL)
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
Module 3: Creating Data Types and Tables. Overview Working with Data Types Working with Tables Generating Column Values Generating Scripts.
Application Data and Database Activities Auditing Dr. Gabriel.
Christopher M. Pascucci.NET Programming: Databases & ADO.NET.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Module 3 Designing and Implementing Tables. Module Overview Designing Tables Working with Schemas Creating and Altering Tables.
Data Types Lesson 4. Skills Matrix Table A table stores your data. Tables are relational in that they are organized as rows and columns (a matrix). Each.
Tables and Constraints Oracle PL/SQL. Datatypes The SQL Data Definition Language Commands (or DDL) enable us to create, modify and remove database data.
SQL Server 2005 Implementation and Maintenance Chapter 3: Tables and Views.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Session 11 Creating Tables and Using Data Types. RDBMS and Data Management/Session 11/2 of 40 Session Objectives Define the data types and list the categories.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Chapter 7 SQL: Data Definition Pearson Education © 2009.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Visual Programing SQL Overview Section 1.
IMS 4212: Data Manipulation 1 Dr. Lawrence West, MIS Dept., University of Central Florida Additional Data Manipulation Statements INSERT.
Sql DDL queries CS 260 Database Systems.
Session 1 Module 1: Introduction to Data Integrity
SQL Overview Structured Query Language
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
ITS232 Introduction To Database Management Systems Siti Nurbaya Ismail Faculty of Computer Science & Mathematics, Universiti Teknologi MARA (UiTM), Kedah.
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
Populating and Querying tables Insert, Update, Delete and View (DML)
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Physical Model Lecture 11. Physical Data Model The last step is the physical design phase, In this phase data is – Store – Organized and – Access.
Constraints Advanced Database Systems Dr. AlaaEddin Almabhouh.
CDT/1 Creating data tables and Referential Integrity Objective –To learn about the data constraints supported by SQL2 –To be able to relate tables together.
SQL Basics Review Reviewing what we’ve learned so far…….
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
In this session, you will learn to: Manage databases Manage tables Objectives.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
Creating Database Objects
Fundamentals of DBMS Notes-1.
國立臺北科技大學 課程:資料庫系統 Chapter 7 SQL Data Definition.
Managing Tables, Data Integrity, Constraints by Adrienne Watt
SQL: Schema Definition and Constraints Chapter 6 week 6
Module 2: Creating Data Types and Tables
Minggu 5, Pertemuan 9 SQL: Data Definition
Module 5: Implementing Data Integrity by Using Constraints
Migrating a Disk-based Table to a Memory-optimized one in SQL Server
STRUCTURED QUERY LANGUAGE
SQL data definition using Oracle
Oracle Data Definition Language (DDL)
Chapter 2: Creating And Modifying Database Tables
Creating Database Objects
Presentation transcript:

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  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)

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)

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

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 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

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 Default FilegroupOrderHistoryGroup E:\ C:\ D:\ AdventureWorks_ Log.Idf AdventureWorks_ Data.mdf OrdHist2.ndf OrdHist1.ndf sys... sysusers sysobjects... SalesOrderHeader Customer Product OrdHistYear2 OrdHistYear1

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) AdventureWorks dbo ErrorLog (Server1.AdventureWorks.dbo.ErrorL og)

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

Syntax: Creating Database CREATE DATABASE database_name [ ON [ PRIMARY ] [ [,...n ] [, [,...n ] ] [ LOG ON { [,...n ] } ] ] [ COLLATE collation_name ] [ WITH ] ] [;]

Example: Creating Database CREATE DATABASE Sales ON ( NAME = Sales_dat, FILENAME = + 'saledat.mdf'', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = Sales_log, FILENAME = + '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? 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

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 CREATE RULE range_rule 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_name [ NULL | NOT NULL ] [Primary Key] [ CONSTRAINT constraint_name ] [DEFAULT constant_expression ] [ IDENTITY [ ( seed,increment ) ] [ NOT FOR REPLICATION ] [References table_name(field_name) ] [...n ] )

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]

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)

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

Slide 32 of 15 Q & A