HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Similar documents
SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Lab # 4. Data Definition Language (DDL)

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Data Definition Language (DDL)

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

BEGINNING T-SQL. Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC

Basis Data Terapan. Yoannita

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 1. Introduction to SQL Server Panayiotis Andreou

SQL: Data Definition Language

Basic SQL. Basic SQL. Basic SQL

user specifies what is wanted, not how to find it

Data Definition Language

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

SQL Structured Query Language Introduction

SQL Data Definition and Data Manipulation Languages (DDL and DML)

Lesson 05: How to Insert, Update, and Delete Data. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

SQL DATA DEFINITION LANGUAGE

Full file at

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

MTAT Introduction to Databases

Lab 4: Tables and Constraints

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Code Centric: T-SQL Programming with Stored Procedures and Triggers

SQL DATA DEFINITION LANGUAGE

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Database and table creation

SQL Server 2008 Tutorial 3: Database Creation

Exact Numeric Data Types

CST272 SQL Server, SQL and the SqlDataSource Page 1

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Database Management Systems,

SQL Data Definition Language

SQL DATA DEFINITION LANGUAGE

How to use SQL to create a database

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2

Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Unit 1 - Chapter 4,5

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Lab # 2 Hands-On. DDL Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia

Oracle SQL Developer. Supplementary Information for Microsoft SQL Server and Sybase Adaptive Server Migrations Release 2.

Full file at

COMP 430 Intro. to Database Systems

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

Course Topics. Microsoft SQL Server. Dr. Shohreh Ajoudanian. 01 Installing MSSQL Server Data types

Introduction to SQL Server 2005/2008 and Transact SQL

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

CSCC43H: Introduction to Databases. Lecture 4

DS Introduction to SQL Part 1 Single-Table Queries. By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

Item: 1 (Ref:Cert-1Z )

MIT Database Management Systems

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

MySQL Introduction. By Prof. B.A.Khivsara

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

Using DDL Statements to Create and Manage Tables. Copyright 2006, Oracle. All rights reserved.

SQL Data Definition: Table Creation

Physical Design of Relational Databases

Every Byte Counts. Why Datatype Choices Matter. Andy Yun, Database Architect/Developer

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

System Pages (Setup Admins Only)

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

CS2300: File Structures and Introduction to Database Systems

1. SQL Overview. Allows users to access data in the relational database management systems.

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

SQL Data Definition Language: Create and Change the Database Ray Lockwood

Queries. Chapter 6. In This Chapter. c SELECT Statement: Its Clauses and Functions. c Join Operator c Correlated Subqueries c Table Expressions

ACCESS isn t only a great development tool it s

Creating and Managing Tables Schedule: Timing Topic

Project Database Rules

Compression Users Guide. Adaptive Server Enterprise 15.7

C Examcollection.Premium.Exam.58q

1) Introduction to SQL

12 Rules Defined by Dr.Codd for a Relational Database Management System

Tables From Existing Tables

3ISY402 DATABASE SYSTEMS

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

Draft. Students Table. FName LName StudentID College Year. Justin Ennen Science Senior. Dan Bass Management Junior

Exam code: Exam name: Database Fundamentals. Version 16.0

After completing this unit, you should be able to: Define the terms

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

Information Systems for Engineers Fall Data Definition with SQL

Outline. Textbook Chapter 6. Note 1. CSIE30600/CSIEB0290 Database Systems Basic SQL 2

SQL: DDL. John Ortiz Cs.utsa.edu

5. SQL Query Syntax 1. Select Statement. 6. CPS: Database Schema

An Introduction to Structured Query Language

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

2.9 Table Creation. CREATE TABLE TableName ( AttrName AttrType, AttrName AttrType,... )

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

Chapter 11 How to create databases, tables, and indexes

Introduction to SQL Part 1 By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

University College of Southeast Norway. Introduction to Database. Systems. Hans-Petter Halvorsen,

Transcription:

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database. According to ANSI, it is the standard language for relational database management systems. SQL statements are used to perform tasks such as update data on a database, or retrieve data from a database. Some common relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL Server, Access, etc. Although most database systems use SQL, most of them also have their own additional proprietary extensions that are usually only used on their system. The standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used to accomplish almost everything that one needs to do with a database. Main and Functional categories are DML and DDL. Slide 2

The SQL statements for data definition You use the data definition language (DDL) statements to create, modify, and delete database objects such as the database itself, the tables contained in a database, and the indexes for those tables. Typically, a database administrator is responsible for using the DDL statements on production databases in a large database system. SQL programmers use these statements to create and work with small databases for testing. In SQL Server, you ll use the Management Studio to generate the DDL statements for you, although you can then verify or correct them as needed. Slide 3

SQL DDL Statements Slide 4

DDL statements to create database and table Statement CREATE DATABASE CREATE TABLE Description Creates a new database. Creates a new table in the current database. Slide 5

Some DDL statements to modify and delete Statement ALTER TABLE DROP DATABASE DROP TABLE Description Modifies the structure of a table. Deletes a database. Deletes a table. Slide 6

The basic syntax of the CREATE DATABASE statement CREATE DATABASE database_name How to create a database The CREATE DATABASE statement creates a new, empty database on the current server. The new database is created using the default settings and the database files are stored in the default directory on the hard drive. One of the files SQL Server creates when it executes the CREATE DATABASE statement is a log file. This file is used to record modifications to the database. SQL Server generates the name for the log file by appending _log to the end of the database name. Slide 7

Creating, Altering and Deleting databases To create a database CREATE DATABASE Company To rename a database ALTER DATABASE Company MODIFY NAME = NewCompany To delete a database DROP DATABASE NewCompany Slide 8

Create Database projects ON (Name=projects, FileName="c:\sqldb\projects.mdf", Size=3, Maxsize = 10, Filegrowth = 2) LOG ON (Name=projects_log, Filename="C:\sqldb\projects_log.ldf", Size=2, Maxsize=3, Filegrowth=1); Slide 9

CREATING TABLES Slide 10

The basic syntax of the CREATE TABLE statement CREATE TABLE table_name (column_name_1 data_type [column_attributes] [, column_name_2 data_type [column_attributes]]... [, table_attributes]) How to create a table The CREATE TABLE statement creates a table based on the column definitions, column attributes, and table attributes you specify. A table can contain between one and 1024 columns. Each column must have a unique name and must be assigned a data type. In addition, you can assign one or more column attributes to it. You can also assign one or more constraints to a column or to the entire table. Slide 11

Data Types Slide 12

Data type overview SQL Server defines 26 unique data types that are divided into the four categories shown below. The temporal data types are typically referred to as date/time data types, or simply date data types. The four data type categories Category String Numeric Temporal (date/time) Other Description Strings of character data Integers, floating point numbers, currency, and other numeric data Dates, times, or both Binary data or system pointers Slide 13

The numeric data types The integer data types are used to store whole numbers, which are numbers without any digits to the right of the decimal point. The decimal data types are used to store decimal values, which can include digits to the right of the decimal point. The precision of a decimal value indicates the total number of digits that can be stored. The scale of a decimal value indicates the number of digits that can be stored to the right of the decimal point. Slide 14

The integer data types Type Bytes Description bigint 8 Large integers from -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807. int 4 Integers from -2,147,483,648 through 2,147,483,647. smallint 2 Small integers from -32,768 through 32,767. tinyint 1 Very small positive integers from 0 through 255. bit 1 Integers with a value of 1 or 0. Slide 15

The decimal data types Type Bytes Description decimal[(p[,s])] 5-17 Decimal numbers with fixed precision (p) and scale (s) from -10 38 +1 through 10 38-1. The precision can be any number between 1 and 38; the default is 18. The scale can be any number between 0 and the precision; the default is 0. numeric[(p[,s])] 5-17 Synonymous with decimal. money 8 Monetary values with four decimal places from -922,337,203,685,477.5808 through 922,337,203,685,477.5807. Synonymous with decimal(19,4). smallmoney 4 Monetary values with four decimal places from -214,748.3648 through 214,748.3647. Synonymous with decimal(10,4). Slide 16

The real data types Type Bytes Description float[(n)] 4 or 8 Double-precision floating-point numbers from -1.79 10 308 through 1.79 10 308. n represents the number of bits used to store the decimal portion of the number (the mantissa): n=24 is single-precision; n=53 is double-precision. The default is 53. real 4 Single-precision floating point numbers from -3.4 10 38 through 3.4 10 38. Synonymous with float(24). Slide 17

The string data types The string data types can be used to store standard characters that use a single byte of storage or Unicode characters that use two bytes of storage. The char and nchar data types are typically used for fixed-length strings. These data types use the same amount of storage regardless of the actual length of the string. The varchar and nvarchar data types are typically used for variable-length strings. These data types use only the amount of storage needed for a given string. Slide 18

The string data types used to store standard characters Type Bytes Description char[(n)] n Fixed-length strings of character data. n is the number of characters between 1 and 8000. The default is 1. varchar[(n)] Variable-length strings of character data. n is the maximum number of characters between 1 and 8000. The default is 1. The number of bytes used to store the string depends on the actual length of the string. Slide 19

The string data types used to store Unicode characters Type Bytes Description nchar(n) 2 n Fixed-length strings of Unicode character data. n is the number of characters between 1 and 4000. The default is 1. nvarchar(n) Variable-length strings of Unicode character data. n is the maximum number of characters between 1 and 4000. The default is 1. The number of bytes used to store the string depends on the actual length of the string. Two bytes are needed to store each character. Slide 20

The temporal (date/time) data types Type Bytes Description datetime 8 Dates and times from January 1, 1753 through December 31, 9999, with an accuracy af 3.33 milliseconds. smalldatetime 4 Dates and times from January 1, 1900 through June 6, 2079, with an accuracy of one minute. Slide 21

Common date formats Format Example yyyy-mm-dd 2002-08-15 mm/dd/yyyy 8/15/2002 mm-dd-yy 8-15-02 Month dd, yyyy August 15, 2002 Mon dd, yy Aug 15, 02 dd Mon yy 15 Aug 02 Common time formats Format Example hh:mi 16:20 hh:mi am/pm 4:20 pm hh:mi:ss 4:20:36 hh:mi:ss:mmm 4:20:36:12 Slide 22

Column Attributes Slide 23

Common column attributes Attribute NULL NOT NULL PRIMARY KEY UNIQUE IDENTITY DEFAULT default_value Description Indicates whether or not the column can accept null values. NULL is the default unless PRIMARY KEY is specified. Identifies the primary key or a unique key for the table. If PRIMARY KEY is specified, the NULL attribute isn t allowed. Identifies an identity column. Only one identity column can be created per table. Specifies a default value for the column. Slide 24

An introduction to constraints Constraints are used to enforce the integrity of the data in a table by defining rules about the values that can be stored in the columns of the table. Constraints can be used at the column level to restrict the value of a single column or at the table level to restrict the value of one or more columns. You code a column-level constraint as part of the definition of the column it constrains. You code a table-level constraint as if it were a separate column definition, and you name the columns it constrains within that definition. Constraints are tested before a new row is added to a table or an existing row is updated. The operation succeeds only if the new or modified row meets all of the constraints. Slide 25

Column and table constraints Constraint NOT NULL PRIMARY KEY At the column level Prevents null values from being stored in the column. Requires that each row in the table have a unique value in the column. Null values are not allowed. UNIQUE CHECK [FOREIGN KEY] REFERENCES Requires that each row in the table have a unique value in the column. Limits the values for a column. Enforces referential integrity between a column in the new table and a column in a related table. Slide 26

Creating a Table Create Database Company Use Company Create Table Employees1 ( ) EmployeeID int identity, FirstName varchar(50) not null, LastName varchar(75) not null, EmailAddress varchar(50), HireDate datetime not null, Salary decimal(19,4) not null money data type can be used for Salary column but the money data type is unique to SQL server. So we can use decimal instead. Slide 27

Creating a Table Create Table Products1 ( ProductID int not null, Name varchar(255) not null, Price decimal(19,4) not null ) Create Table Sales1 ( SalesID int identity ProductID int not null, EmployeeID int not null, Quantity smallint not null ) Slide 28

The Default Clause The DEFAULT clause in the column definition specifies the default value of the column that is, whenever a new row is inserted into the table, the default value for the particular column will be used if there is no value specified for it. Create Table Employees2 ( emp_no int not null, emp_fname varchar(20) not null, emp_lname varchar(20) not null, Datehired smalldatetime default getdate(), dept_no varchar(4) null ) Slide 29

The UNIQUE Clause Sometimes more than one column or group of columns of the table have unique values and therefore can be used as the primary key. All columns or groups of columns that qualify to be primary keys are called candidate keys. Each candidate key is defined using the UNIQUE clause in the CREATE TABLE or the ALTER TABLE statement. The UNIQUE clause has the following form: [CONSTRAINT c_name] UNIQUE ({ col_name1},...) Slide 30

The UNIQUE Clause Create Table Projects1 ( project_no varchar(4) Default 'p1', project_name varchar(15)not null, Budget decimal(19,4)null, Constraint uniq_proj1 Unique(project_no) ) Slide 31

The CHECK Constraint The check constraint specifies conditions for the data inserted into a column. Each row inserted into a table or each value updating the value of the column must meet these conditions. The CHECK clause is used to specify check constraints. The syntax of the CHECK clause is [CONSTRAINT c_name] CHECK expression expression must evaluate to a Boolean value (true or false) and can reference any columns in the current table, but no other tables. Slide 32

The CHECK Constraint Create Table Projects2 ( project_no varchar(4) not null, project_name varchar(15) not null, budget decimal(19,4), Constraint prim_proj2 Primary Key(project_no), Constraint chk_bud Check(budget>0) ) Slide 33

The CHECK Constraint Create Table Customers1 ( ) cust_id cust_group int not null, varchar(3)null, Constraint prim_cust Primary Key(cust_id), Constraint chk_cust Check(cust_group IN('c1', 'c2','c3')) Slide 34

Check for more two columns Create Table Invoices ( InvoiceID int identity, InvoiceTotal decimal(19,4), PaymentTotal decimal(19,4), Constraint check_amount Check((InvoiceTotal > 0) and (PaymentTotal >=0)) ) Slide 35

Check for a pattern Create Table Suppliers ( SupplierID varchar(6) primary key, SupplierFName varchar(50) not null, SupplierLName varchar(50) not null, CompanyName varchar(100) not null, Constraint check_id check(supplierid LIKE '[A-Z]''[A-Z]''[0-9]''[0-9]''[0-9]''[0-9]') ) SN0001 Slide 36

The PRIMARY KEY Constraint The primary key of a table is a column or group of columns whose value is different in every row. Each primary key is defined using the PRIMARY KEY clause in the CREATE TABLE or the ALTER TABLE statement. The PRIMARY KEY clause has the following form: [CONSTRAINT c_name] PRIMARY KEY ({col_name1},...) All options of the PRIMARY KEY clause have the same meaning as the corresponding options with the same name in the UNIQUE clause. In contrast to UNIQUE, the PRIMARY KEY column must be NOT NULL, and its default value is CLUSTERED. Slide 37

Creating a Table Create Table Employees3 ( EmployeeID int PRIMARY KEY, FirstName varchar(50) not null, LastName varchar(75) not null, EmailAddress varchar(50), HireDate datetime not null, Salary decimal(19,4) not null ) Create Table Employees4 ( EmployeeID int not null, FirstName varchar(50) not null, LastName varchar(75) not null, EmailAddress varchar(50), HireDate datetime not null, Salary decimal(19,4) not null, Constraint PK_Emp Primary Key(EmployeeID) ) Slide 38

Two-Column Primary Key Create Table Sales2 ( ) SalesID int identity, ProductID int not null, EmployeeID int not null, Quantity smallint not null, Constraint PK_Sales Primary Key(ProductID, EmployeeID) Note: this is just for illustrative purpose; in real application, these attributes cannot be unique forever (same project and employees might repeat) Slide 39

The FOREIGN KEY Constraint A foreign key is a column or group of columns in one table that contains values that match the primary key values in the same or another table. Each foreign key is defined using the FOREIGN KEY clause combined with the REFERENCES clause. The FOREIGN KEY clause has the following form: [CONSTRAINT c_name] [[FOREIGN KEY] ({col_name1},...)] REFERENCES table_name ({col_name2},...) Slide 40

[CONSTRAINT c_name] [[FOREIGN KEY] ({col_name1},...)] REFERENCES table_name ({col_name2},...) The FOREIGN KEY clause defines all columns explicitly that belong to the foreign key. The REFERENCES clause specifies the table name with all columns that build the corresponding primary key. The number and the data types of the columns in the FOREIGN KEY clause must match the number and the corresponding data types of columns in the REFERENCES clause Slide 41

Foreign Key One Column Create Table Products ( ProductID int primary key, SupplierID varchar(6) not null, Name varchar(255) not null, Price decimal(19,4) not null Constraint fk1 Foreign Key(SupplierID) References Suppliers(SupplierID) ) Slide 42

Foreign Key for Two Columns from Two Tables Create Table Invoices2 ( InvoiceID int identity, SupplierID varchar(6) not null, ProductID int, InvoiceTotal decimal(19,4) not null, PaymentTotal decimal(19,4) not null, Constraint fk1 Foreign Key(SupplierID) References Suppliers(SupplierID), Constraint fk2 Foreign Key(ProductID) References Products(ProductID) ) Slide 43

Altering and Deleting Tables -- To add columns to the table Employees Alter Table Employees Add ActiveFlag bit not null, ModifiedDate datetime not null Alter Table Products Add newprice money not null -- To modify the data type of a column Alter Table Products Alter Column Price money -- To delete a column in Products table Alter Table Products Drop Column newprice -- To delete the table Employees Drop Table Employees Slide 44

More on ALTER TABLE ALTER TABLE Invoices ADD PRIMARY KEY (InvoiceID); ALTER TABLE Invoices ADD FOREIGN KEY (ProductsID) REFERENCES Products(ProductID); ALTER TABLE Invoices ADD CHECK (InvoiceTotal >0); Slide 45

Create a Database named EIS and Create Tables with Constraints for the following schema Slide 46

Thank You