Copyright © 2003 - 2012 Curt Hill SQL The Data Definition Language.

Slides:



Advertisements
Similar presentations
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Advertisements

Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
Overview Begin 6:00 Quiz15 mins6:15 Review Table Terms25 mins6:40 Short Break10 mins6:50 SQL: Creating Tables60 mins7:50 Break10 mins8:00 Lab – Creating.
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 28 Database Systems I The Relational Data Model.
Sanjay Goel, School of Business, University at Albany, SUNY 1 SQL- Data Definition Language ITM 692 Sanjay Goel.
1 A GUIDE TO ORACLE8 CHAPTER 2: Creating and ModifyingDatabaseTables 2.
Introduction to Structured Query Language (SQL)
The Relational Model Lecture 3 Book Chapter 3 Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC) From ER to Relational.
A Guide to SQL, Seventh Edition. Objectives Understand the concepts and terminology associated with relational databases Create and run SQL commands in.
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.
Introduction to Structured Query Language (SQL)
Creating Database Tables CS 320. Review: Levels of data models 1. Conceptual: describes WHAT data the system contains 2. Logical: describes HOW the database.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
SQL Overview Defining a Schema CPSC 315 – Programming Studio Spring 2008 Project 1, Lecture 3 Slides adapted from those used by Jeffrey Ullman, via Jennifer.
Database Management System LICT 3011 Eyad H. Elshami.
Database Systems Lecture 5 Natasha Alechina
DATABASES AND SQL. Introduction Relation: Relation means table(data is arranged in rows and columns) Domain : A domain is a pool of values appearing in.
Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial Password: UWPstudent Password is case sensitive.
Oracle Data Definition Language (DDL)
DBMS 3. course. Reminder Data independence: logical and physical Concurrent processing – Transaction – Deadlock – Rollback – Logging ER Diagrams.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
Structured Query Language. Brief History Developed in early 1970 for relational data model: –Structured English Query Language (SEQUEL) –Implemented with.
CS 3630 Database Design and Implementation. Your Oracle Account UserName is the same as your UWP username Followed Not case sensitive Initial.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
1 The Relational Model Instructor: Mohamed Eltabakh
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
Chapter 7 SQL HUANG XUEHUA. SQL SQL server2005 introduction Install components  management studio.
SQL data definition using Oracle1 SQL Data Definition using Oracle.
CSC 2720 Building Web Applications Database and SQL.
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.
Copyright Curt Hill SQL Queries Yet Another Set of Query Features.
1 Creating and Modifying Database Objects. 2 An Oracle database consists of multiple user accounts Each user account owns database objects Tables Views.
1 The Relational Model. 2 Why Study the Relational Model? v Most widely used model. – Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. v “Legacy.
11 3 / 12 CHAPTER Databases MIS105 Lec15 Irfan Ahmed Ilyas.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
1 Chapter 2: Creating and Modifying Database Objects.
Sql DDL queries CS 260 Database Systems.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
1 CS 430 Database Theory Winter 2005 Lecture 10: Introduction to SQL.
DBMS 3. course. Reminder Data independence: logical and physical Concurrent processing – Transaction – Deadlock – Rollback – Logging ER Diagrams.
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
Lecture # 24 Introduction to SQL Muhammad Emran Database Systems.
Physical Model Lecture 11. Physical Data Model The last step is the physical design phase, In this phase data is – Store – Organized and – Access.
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.
Copyright © Curt Hill SQL The Data Manipulation Language.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
CS 3630 Database Design and Implementation
Managing Tables, Data Integrity, Constraints by Adrienne Watt
ORACLE SQL Developer & SQLPLUS Statements
Instructor: Mohamed Eltabakh
SQL OVERVIEW DEFINING A SCHEMA
SQL data definition using Oracle
Oracle Data Definition Language (DDL)
SQL-1 Week 8-9.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
SQL (Structured Query Language)
Presentation transcript:

Copyright © Curt Hill SQL The Data Definition Language

Classification SQL statements can be broken into two categories Data Definition Language (DDL) –Create databases, tables, views Data Manipulation Language (DML) –Change the data –Process queries This presentation is about the DDL Copyright © Curt Hill

Data Definition Language Used for creating databases, tables, views It also establishes most constraints –Primary keys –Foreign keys –Integrity constraints Also deletes databases and tables

Background Up to this point we have dealt with existing tables and data –We do not have to worry about what types of names are legal for table or field names in queries Now we have to worry about these things: –What constitutes a legal name? –What data types exist? Copyright © Curt Hill

Identifiers A name for an item –Servers –Databases –Tables –Views –Fields There are rules for a legal name – Name must be characters

Copyright © Curt Hill Naming rules Legal characters –Letters –Digits –Underscore _ and dollar $ Start with any type of character including digit –May not be only digits Names are case sensitive Some other names may be used if quoted –Not usually a good idea Reserved words should be avoided

Copyright © Curt Hill Creation and deletion The create reserved word is used to create a database, table, view The drop reserved word is used to delete any of these At table (or view) creation time the fields, keys and constraints are given These may be changed later

Copyright © Curt Hill Create Database Simple form only gives the database name: Create database junkdb Some servers allow specification of estimated sizes and disk file names In Oracle, databases are linked so this is not done with SQL

SQL Server Older versions generally needed to give some disk specifics for first creation, no longer required Example: create database college on (name=college, filename='d:\courses\database \sqlserver\college.mdf', size=3MB) 3MB is minimum for current version Copyright © Curt Hill

SQL Server Commentary The on is used to specify a file where the database is to be stored –Must be used for the first create –Once file exists other databases may be placed in it It is one file for all the databases and tables Every SQL Server database has the following three databases: –Master – the system catalog –Tempdb –Msdb Copyright © Curt Hill

Tables Once a database exists the tables need to be created A create table must specify almost everything about it: –Table name –Fields: Name Type, including length –Constraints Such as keys Copyright © Curt Hill

Creating a table Basic form: Create table tn (fields…) –Where tn is the table name The parenthesized list is the attributes of the file These include –Field names and types –Primary and foreign keys –Other constraints

Copyright © Curt Hill Field Types There are several basic types that a field may possess Each implementation may augment these with others These include char, integer, real etc. These may be modified by lengths

Copyright © Curt Hill Character types char(n) –Fixed length character string –Always uses n characters –Padded with blanks –0 < n < 256 varchar(n) –Variable length character strings –The n specifies the maximum length –Not all positions need to be stored depending on the data MySQL does not like to mix the two in a table

Copyright © Curt Hill Numeric types Int(n) or integer(n) –N is optional display width –May be prefixed with Unsigned Float(p,d) –P is precision – maximum total number of digits –D is digits to right of decimal point –These are optional and only used for display Double or real –A larger float –Also allows p and d Decimal or numeric –Usually stored in string format –May also have p and d

Copyright © Curt Hill Binary Large Objects AKA BLOB Stores data that usually cannot be manipulated in SQL –Word Processor Documents –Graphics –Executables Text –Case insensitive blob –Sensitive to character set

SQL Server specific types Bigint (64 bit), smallint(16 bit), tinyint(8 bit) –Different sizes Bit –Zero or one – a boolean Money(64 bit), tinymoney (32 bit) –4 digits to right of decimal Time, date, datetime Copyright © Curt Hill

Oracle specific types Number (p,d) Varchar2 Date Raw(len) –Binary data of given length BLOB and CLOB Copyright © Curt Hill

MySQL specific types Tinyint, smallint, bigint Bit, bool, boolean Many others as well

Copyright © Curt Hill Field definitions Form of a field definition: name type col_attr gen_attr Fields are separated by commas The name is the field name Type is one of the above or other types Column attributes are always optional –Unsigned is specific to numerics –Lengths have different meanings for different types General attributes are always optional

Copyright © Curt Hill Primary Key The most important attribute A table needs one or more fields specified as the primary key The key may be specified as part of the field: naid int primary key It may also be specified after the needed fields are given: Primary key (dept, number)

Copyright © Curt Hill Example: Students Create table students ( s_id int, s_name char(20), s_address char(20), primary key (s_id) )

Copyright © Curt Hill Attribute: NOT NULL NULL or NOT NULL –Whether it is possible for field not to have a value –Default is NULL –A key can not be null Example: name char(20) not null,

Copyright © Curt Hill Attribute: DEFAULT Default constant Supplies a value when an Insert does not Cannot be used on type BLOB or TEXT Example: address char(20) default ‘Unknown’,

Copyright © Curt Hill Attribute: UNIQUE Requires each field to be unique within the table Default for the primary key fields Coded as: UNIQUE or UNIQUE KEY Example: varchar(50) unique,

Copyright © Curt Hill Attribute: CHECK Domain Integrity constraint Form: CHECK (relational) The relational may be almost anything in a where Example: crhr int check (crhr 0),

Copyright © Curt Hill Foreign Key Enforces referential integrity Form: foreign key (local-fields) references field Examples foreign key (dept,course) references course -- Must have same name in course foreign key (chair) references faculty.naid

Copyright © Curt Hill Create Order In the college database that are tables that have no foreign keys: –Students, courses Others that do: –Grades references courses and students Tables with foreign keys need to be created after the tables they depend on The same is true for the insertion process

Copyright © Curt Hill Relationship examples create table grades ( dept char(5), number int, naid int, score int check (score >= 0 AND score <= 100), primary key (dept, number, naid), foreign key (naid) references students, foreign key (dept, number) references course); create table faculty_teach ( dept char(5), number int, naid int, primary key (dept, number, naid), foreign key (naid) references faculty, foreign key (dept, number) references course);

Copyright © Curt Hill Drop Deletes the entire database Drop database junkdb Deletes the table: Drop table junktab

Order again If there are many foreign keys then creation and insertion may be complicated It is also possible to change a table after creation This uses the Alter statement It may add or change fields or constraints Copyright © Curt Hill

Alter Example Adding a field: alter table faculty add(f_age int, f_years int) Removing a field: Alter table students drop column f_balance Copyright © Curt Hill

Changing constraints The Alter may also be used to add or remove constraints Consider changing a primary key: Alter Table newtab Add Primary Key (nt_id) A Foreign key: Alter Table newtab Add Foreign Key (fk) references table t(tk)

Cleaning Since Oracle does not allow either create or drop on a database removing all the tables to start over is complicated Dropping a table that has foreign keys point into it is disallowed Typically use Alter to remove all foreign keys from all tables The tables may then be dropped in any order Copyright © Curt Hill

Views A view is a predefined query that may be used like a table It may be as a simple as a projection upon a single table –Such as removing payroll information from a personnel table It may be complicated rearrangement of data from several tables –Like any query Copyright © Curt Hill

Syntax Form: Create View ViewName As Select … Viewname is the name of the new view and can be any SQL identifier View, As and Create are reserved words A normal Select/From/Where is the last part of the statement Copyright © Curt Hill

View Commentary In a query using a view is just like using a table A view does not create a new table When referenced it is like an automatic nested query Not every option of Select is allowed –Eg. Order By and Into are disallowed Copyright © Curt Hill

Another View Form The column names of the view usually just come from Select –Either original names or their aliases They can be specified explicitly Another form: Create View ViewName (col1, col2,…) As Select … Column count must match Select Copyright © Curt Hill

Types of Views Two classifications of views, simple and complex A simple view would be a reduction of a single table Example: Create view missing as Select s_id, S_name From students Where s_address is Null A complex view involves multiple tables Copyright © Curt Hill

Example Complex View Multiple table or complex view: create view student_hour (sh_id, sh_name, sh_load) as select s_id, s_name, sum(crs_crhr) from students, grades, course where s_id = g_naid AND g_dept = crs_dept And g_course = crs_number group by s_id, s_name Copyright © Curt Hill

Update a View? A simple view may be updated –The DBMS translates the update into the single table update –Not very complicated A complex view may not be updated –Figuring out how to update the multiple tables is difficult to impossible –How could we update a view that involved computations? –The tables that contribute to the view should be updated instead Copyright © Curt Hill

Finally We may now create a database The next presentation will consider populating it with data Copyright © Curt Hill