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

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

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

Copyright © 2003 - 2012 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 © 2003 - 2012 Curt Hill

Copyright © 2003 - 2012 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 © 2003 - 2012 Curt Hill

Copyright © 2003 - 2012 Curt Hill

Identifiers• A name for an item

– Servers– Databases– Tables– Views– Fields

• There are rules for a legal name– Name must be 1-256 characters

Copyright © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 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 versionCopyright © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 Curt Hill

Copyright © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 Curt Hill

Oracle specific types

• Number (p,d)• Varchar2• Date• Raw(len)

– Binary data of given length

• BLOB and CLOB

Copyright © 2003 - 2012 Curt Hill

Copyright © 2003 - 2012 Curt Hill

MySQL specific types

• Tinyint, smallint, bigint• Bit, • bool, boolean• Many others as well

Copyright © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 Curt Hill

Example: Students

• Create table students ( s_id int, s_name char(20), s_address char(20), primary key (s_id) )

Copyright © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 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:email varchar(50) unique,

Copyright © 2003 - 2012 Curt Hill

Attribute: CHECK• Domain Integrity constraint• Form:

CHECK (relational)• The relational may be almost

anything in a where• Example:crhr int check (crhr < 12 AND crhr>0),

Copyright © 2003 - 2012 Curt Hill

Foreign Key• Enforces referential integrity• Form:

foreign key (local-fields) references field

• Examplesforeign key (dept,course) references course-- Must have same name in course

foreign key (chair) references faculty.naid

Copyright © 2003 - 2012 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 © 2003 - 2012 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 © 2003 - 2012 Curt Hill

Drop

• Deletes the entire databaseDrop 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 © 2003 - 2012 Curt Hill

Alter Example

• Adding a field:alter table faculty add(f_age int, f_years int)

• Removing a field:Alter table studentsdrop column f_balance

Copyright © 2003 - 2012 Curt Hill

Copyright © 2003 - 2012 Curt Hill

Changing constraints• The Alter may also be used to add

or remove constraints• Consider changing a primary key:Alter Table newtabAdd Primary Key (nt_id)

• A Foreign key:Alter Table newtabAdd 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 © 2003 - 2012 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 © 2003 - 2012 Curt Hill

Syntax• Form:Create View ViewName AsSelect …

• 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 © 2003 - 2012 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 © 2003 - 2012 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,…) AsSelect …

• Column count must match Select

Copyright © 2003 - 2012 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 asSelect s_id, S_nameFrom studentsWhere s_address is Null

• A complex view involves multiple tables

Copyright © 2003 - 2012 Curt Hill

Example Complex View

• Multiple table or complex view:create view student_hour (sh_id, sh_name, sh_load) asselect s_id, s_name, sum(crs_crhr)from students, grades, coursewhere s_id = g_naid AND g_dept = crs_dept And g_course = crs_numbergroup by s_id, s_name

Copyright © 2003 - 2012 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 © 2003 - 2012 Curt Hill

Finally

• We may now create a database• The next presentation will consider

populating it with data

Copyright © 2003 - 2012 Curt Hill