Date post: | 18-Jan-2016 |
Category: |
Documents |
Upload: | rebecca-hoover |
View: | 246 times |
Download: | 5 times |
SQL DDL QUERIESCS 260
Database Systems
Introduction to DDL
Data Definition Language (DDL) Used to create and modify database objects
In contrast to DML (data manipulation language) used to view, insert, update, and delete data in those database objects
These database objects include tables, views, users, sequences, and stored programs
Common DDL commands CREATE ALTER DROP
DDL commands modify the database as soon as they are issued
Overview
Creating tables CREATE Naming practices Data types
Specifying constraints Modifying/dropping tables
Creating Tables
To create a table, use the CREATE command
Syntax
The <data_type> may also identify the field’s storage capacity
CREATE TABLE <table_name> (<field1_name> <data_type>,<field2_name> <data_type>,…<fieldN_name> <data_type>
);
Creating Tables
Oracle example
CREATE TABLE student( student_id NUMBER(6), student_name VARCHAR2(30), student_DOB DATE);
Overview
Creating tables CREATE Naming practices Data types
Specifying constraints Modifying/dropping tables
Naming Practices
Naming tables and fields Oracle database table and field names
must conform to the Oracle naming standard 1 to 30 characters long Must begin with a character Can contain characters, numbers, $, _ and #
Each table must have a name that is unique in its schema
Each field must have a name that is unique in its table
Naming Practices
Good table naming practices Name every table using a combination of
two words Separate words in tables names using an
underscore Use the same descriptive first word for all
related table names Makes it easier to see related tables
Naming Practices
Good field naming practices Name every field using a combination of
two words, with the first word indicating the table name Makes it easier to identify the table that a field
belongs to when writing/analyzing a query involving multiple tables
Don’t do this for foreign keys Use the name that is in the parent table instead
Overview
Creating tables CREATE Naming practices Data types
Characters Numbers Dates Objects
Specifying constraints Modifying/dropping tables
Data Types
When creating tables, each field’s data type must be specified Specifies the type of data stored in the field May include the field’s storage capacity
Purposes Dictates the internal encoding Optimizes internal storage use Provides error checking
Data Types
Characters Oracle
CHAR, NCHAR VARCHAR2,
NVARCHAR2 CLOB
MySQL CHAR VARCHAR TEXT
Data Types
CHAR, NCHAR (Oracle) and CHAR (MySQL) Fixed-length character strings Trailing blank spaces are padded to meet the
specified capacity Useful for fields where fixed width values are
expected Oracle
Maximum of 2,000 characters
Must specify capacity NCHAR uses Unicode
encoding while CHAR uses the server platform’s default encoding scheme
MySQL Maximum of 255
characters Capacity specification
unnecessary (default is 1)
CHAR, NCHAR (Oracle) and CHAR (MySQL) Examples
Oracle
MySQL
Data Types
CREATE TABLE <table_name> ( student_gender CHAR(1));
CREATE TABLE <table_name> ( student_gender CHAR);
Data Types
VARCHAR2, NVARCHAR2 (Oracle) and VARCHAR (MySQL) Variable-length character strings No trailing space padding to meet the specified capacity Useful for fields where fixed width values are not
expected
Oracle Maximum of 4,000
characters Must specify capacity NVARCHAR2 uses Unicode
encoding while VARCHAR2 uses the server platform’s default encoding scheme
MySQL Maximum of 255
characters Must specify capacity
VARCHAR2, NVARCHAR2 (Oracle) and VARCHAR (MySQL) Examples
Oracle
MySQL
Data Types
CREATE TABLE <table_name> ( student_name VARCHAR2(30));
CREATE TABLE <table_name> ( student_name VARCHAR(30));
Data Types
CLOB (Oracle) and TEXT (MySQL) Stores large amounts of variable-length character
strings Useful for fields where large amounts of variable
width values are expected
Oracle Up to 4GB of data No capacity
specification Also has LONG (2GB)
for legacy purposes
MySQL Up to 64K of data No capacity
specification Also has TINYTEXT
(255 bytes), MEDIUMTEXT (16MB), and LONGTEXT (4GB)
CLOB (Oracle) and TEXT (MySQL) Examples
Oracle
MySQL
Data Types
CREATE TABLE <table_name> ( student_summary CLOB);
CREATE TABLE <table_name> ( student_summary MEDIUMTEXT);
Data Types
Numbers Use for data that is entirely numeric
Not always the case for phone numbers, postal codes, social security numbers, etc.
Oracle NUMBER
MySQL INT DOUBLE DECIMAL (NUMERIC)
Data Types
Numbers in Oracle NUMBER
Precision and scale may be specified Precision: total number of digits Scale: number of digits to the right of the
decimal point If neither is specified, the maximum values are
used Allows values from 10-130 and 10126
If only one value is specified, then the value applies to the precision
Data Types
Numbers in Oracle NUMBER
Examples
CREATE TABLE <table_name> ( student_age NUMBER(2));
CREATE TABLE <table_name> ( item_price NUMBER(5,2));
Data Types
Numbers in MySQL INT
Signed or unsigned integers Can specify number of digits (up to 11) Also has TINYINT, SMALLINT, MEDIUMINT and BIGINT
DOUBLE Signed floating point numbers Can specify the precision and scale (defaults to 16 and 4) Also has FLOAT (less precise)
DECIMAL (NUMERIC) Signed floating point numbers Must specify the precision and scale Can be more precise than DOUBLE or FLOAT but takes more
space
Data Types
Numbers in MySQL Number examples
CREATE TABLE <table_name> ( student_age INT(2));
CREATE TABLE <table_name> ( item_price DECIMAL(5,2));
Data Types
Dates in Oracle DATE
Stores dates between 1/1/4712 BC and 12/31/9999
Consists of both a date and a time component Default date format: ‘DD-MON-YY’ If a date is specified without a time component,
the default time is midnight 24-hour clock time: 00:00:00
Format: ‘HH24:MI:SS’ 12-hour clock time: 12:00:00
Format: ‘HH12:MI:SS’
Data Types
Dates in MySQL DATE
Stores dates between 1/1/1000 and 12/31/9999 Consists of a date component only Default date format: ‘YYYY-MM-DD’
DATETIME Consists of both date and timestamp
components Date example (both Oracle and MySQL)
CREATE TABLE <table_name> ( student_dob DATE);
Data Types
Objects Oracle
BLOB BFILE
MySQL BLOB
BLOB is an acronym for “binary large object”
Data Types
Objects in Oracle BLOB
Stores large amounts of variable-length binary data (images, files, etc.)
Can optionally specify a capacity (default is 2GB) Maximum capacity is 8TB Significant overhead (treated by DBMS much like
other data) BFILE
Stores a reference (directory and file name) to a binary file on the database server
Maximum file size is 4GB
Data Types
Objects in MySQL BLOB
Like in Oracle, stores large amounts of variable-length binary data (images, files, etc.)
Cannot specify a capacity Maximum capacity of 64K Also has TINYBLOB (255 bytes), MEDIUMBLOB
(16MB), and LONGBLOB (4GB) Significant overhead (as in Oracle)
Data Types
Object examples Both Oracle and MySQL
Oracle BFILE example
Use the “BFILENAME” function when inserting values to a BFILE field
CREATE TABLE student ( student_image BLOB);
CREATE TABLE student2 ( student_image BFILE);
INSERT INTO student2 VALUES( BFILENAME(‘directory’, ‘filename.ext’));
Overview
Creating tables Specifying constraints
Primary keys Foreign keys Composite keys NOT NULL DEFAULT UNIQUE CHECK conditions
Modifying/dropping tables
Constraints
Constraints are rules that restrict the values that can be entered into a column or table
Table level constraints Specified after the comma separated list of
fields in the create table statement Column level constraints
Specified with the associated column in the comma separated list of fields in the create table statement
Some column constraints can be specified at the table level, but not vice versa
Constraints
Constraint naming conventions Some constraints, like primary keys and foreign
keys, are named Convention: tablename_fieldname_constraintType
constraintTypes Primary keys: pk Foreign keys: fk
Limited to 30 characters Oracle assigns system generated names if none
are provided User provided constraint names are far more readable
MySQL primary keys are always named “PRIMARY”
Constraints
Viewing constraints Oracle
Oracle provided constraint names will begin with “SYS_”
MySQL
SELECT constraint_nameFROM user_constraintsWHERE table_name = ‘<table name>’
SELECT index_nameFROM information_schema.table_constraintsWHERE constraint_schema = ‘<schema>’;
Primary Keys
Primary key creation syntax
CREATE TABLE <table_name> ( <pk_field_name> <type> PRIMARY KEY, … <fieldN_name> <type>);
CREATE TABLE <table_name>( <pk_field_name> <type>, … <fieldN_name> <type>, CONSTRAINT <constraint_name> PRIMARY KEY (<pk_field_name>));
Single column primary keys can be specified at the column level
Alternatively, primary keys can be specified at the table-level
Foreign Keys
Foreign key rules A foreign key MUST have the same data type as the
parent primary key field A foreign key SHOULD have the same size as the
parent primary key field A foreign key SHOULD have the same field name as
the parent primary key field A foreign key MUST be designated as such after the
parent primary key field has been designated as a pk Knowing this, in what order must the tables in our candy
database be created (assuming pks/fks are created at the same time as their corresponding tables)?
Sample Database (CANDY)CUST_ID CUST_NAME CUST_TYPE CUST_ADDR CUST_ZIP CUST_PHONE USERNAME PASSWORD
1 Jones, Joe P 1234 Main St. 91212 434-1231 jonesj 12342 Armstrong,Inc. R 231 Globe Blvd. 91212 434-7664 armstrong 33333 Sw edish Burgers R 1889 20th N.E. 91213 434-9090 sw edburg 23534 Pickled Pickles R 194 CityView 91289 324-8909 pickpick 53335 The Candy Kid W 2121 Main St. 91212 563-4545 kidcandy 23516 Waterman, Al P 23 Yankee Blvd. 91234 w ateral 89007 Bobby Bon Bons R 12 Nichi Cres. 91212 434-9045 bobbybon 30118 Crow sh, Elias P 7 77th Ave. 91211 434-0007 crow el 10339 Montag, Susie P 981 Montview 91213 456-2091 montags 9633
10 Columberg Sw eets W 239 East Falls 91209 874-9092 columsw e 8399
PURCH_ID PROD_ID CUST_ID PURCH_DATE DELIVERY_DATE POUNDS STATUS
1 1 5 28-Oct-04 28-Oct-04 3.5 PAID2 2 6 28-Oct-04 30-Oct-04 15 PAID3 1 9 28-Oct-04 28-Oct-04 2 PAID3 3 9 28-Oct-04 28-Oct-04 3.7 PAID4 3 2 28-Oct-04 3.7 PAID5 1 7 29-Oct-04 29-Oct-04 3.7 NOT PAID5 2 7 29-Oct-04 29-Oct-04 1.2 NOT PAID5 3 7 29-Oct-04 29-Oct-04 4.4 NOT PAID6 2 7 29-Oct-04 3 PAID7 2 10 29-Oct-04 14 NOT PAID7 5 10 29-Oct-04 4.8 NOT PAID8 1 4 29-Oct-04 29-Oct-04 1 PAID8 5 4 29-Oct-04 7.6 PAID9 5 4 29-Oct-04 29-Oct-04 3.5 NOT PAID
PROD_ID PROD_DESC PROD_COSTPROD_PRICE
1 Celestial Cashew Crunch 7.45$ 10.00$
2 Unbrittle Peanut Paradise 5.75$ 9.00$
3 Mystery Melange 7.75$ 10.50$
4 Millionaire’s Macadamia Mix 12.50$ 16.00$
5 Nuts Not Nachos 6.25$ 9.50$
CUST_TYPE_IDCUST_TYPE_DESC
P Private
R Retail
W Wholesale
CANDY_CUSTOMER
CANDY_PURCHASE
CANDY_CUST_TYPE
CANDY_PRODUCT
Foreign Keys
Foreign key creation syntaxCREATE TABLE candy_customer ( <fk_field_name> <type> REFERENCES <parent_table>(<parent_table_pk_field_name>), … <fieldN_name> <type>);
CREATE TABLE candy_customer ( <fk_field_name> <type>, … <fieldN_name> <type>, CONSTRAINT <constraint_name> FOREIGN KEY (<fk_field_name>) REFERENCES <parent_table>(<parent_table_pk_field_name>));
Foreign keys in Oracle can be specified at the column level
Alternatively, foreign keys can be specified at the table-level
Composite Keys
A composite key can be created only after you define the fields that make up the composite key (at the table-level)
Convention: constraint_name should consist of a combination of all fields names in the composite key (limited to 30 characters)
CREATE TABLE <table_name>( <ck_field1_name> <type>, <ck_field2_name> <type>, … <fieldN_name> <type>, CONSTRAINT <constraint_name> PRIMARY KEY (<ck_field1_name>, <ck_field2_name>));
NOT NULL
Requires a column’s values to be non-null
CREATE TABLE <table_name>( <fieldM_name> <type> NOT NULL, … <fieldN_name> <type>);
CREATE TABLE <table_name>( <fieldM_name> <type> CONSTRAINT <constraint_name> NOT NULL, … <fieldN_name> <type>);
Works in both Oracle and MySQL
Works in Oracle only
DEFAULT
Provides a default column value if no value is provided when data is inserted Default values may be hardcoded or use
functions Syntax
Example
CREATE TABLE <table_name>( <fieldM_name> <type> DEFAULT <value>);
CREATE TABLE student( date_added DATE DEFAULT SYSDATE);
UNIQUE
Requires all column values to be unique A table can have only one primary key but
can have many unique columns Syntax and example
CREATE TABLE <table_name>( <fieldM_name> <type>, … <fieldN_name> <type>, CONSTRAINT <constraint_name> UNIQUE (<fieldM_name>));
CREATE TABLE student( student_id NUMBER(9) PRIMARY KEY, … student_username VARCHAR2(20), CONSTRAINT student_username_uk UNIQUE (student_username));
CHECK Conditions
Restricts a column’s value to one or more possible values (not supported in MySQL) Still allows NULL and/or empty strings
Syntax and example
CREATE TABLE student ( student_gender VARCHAR(1), CONSTRAINT student_gender_ck CHECK (student_gender IN (‘M’,’F’)));
CREATE TABLE <table_name>( <field1_name> <type>, … <fieldN_name> <type>, CONSTRAINT <constraint_name> CHECK (<condition>));
Overview
Creating tables Specifying constraints Modifying/dropping tables
Modifying Database Tables
Allowed modifications Changing a table or column name Adding a new column Deleting a primary key or foreign key constraint
Allowed if existing data fits new specifications Changing a column’s data type, size, or default
value Adding a primary key or foreign key constraint Adding a CHECK condition constraint Adding a NOT NULL or UNIQUE constraint
Modifying Database Tables
Add column
Modify column syntax
Remove column syntax
ALTER TABLE <table_name> ADD <field_name> <datatype> <constraints>
ALTER TABLE <table_name> MODIFY <field_name> <datatype> <constraints>
ALTER TABLE <table_name> DROP COLUMN <field_name>
ALTER TABLE student ADD student_age NUMBER(2) NOT NULL
ALTER TABLE student MODIFY student_age NUMBER(3) NOT NULL
ALTER TABLE student DROP COLUMN student_age
Modifying Database Tables
Add constraint syntax
Remove constraint syntax Oracle
MySQL
ALTER TABLE <table_name> ADD CONSTRAINT constraint_name <constraint> (<column(s)>)
ALTER TABLE <table_name> DROP CONSTRAINT <constraint_name>
ALTER TABLE student ADD CONSTRAINT student_pk PRIMARY KEY (student_id)
ALTER TABLE student DROP CONSTRAINT student_pk
ALTER TABLE student DROP PRIMARY KEY
ALTER TABLE <table_name> DROP PRIMARY KEY
Modifying Database Tables
Delete table syntax
A table cannot be dropped if its primary key is referenced as a foreign key in other tables
In Oracle, you can remove constraints simultaneously
In MySQL, you first need to remove the foreign key constraints for each foreign key
DROP TABLE <table_name>
DROP TABLE <table_name> CASCADE CONSTRAINTS
ALTER TABLE <table_name_with_fk> DROP FOREIGN KEY <foreign_key_name>
DROP TABLE <table_name_with_pk>
Modifying Database Tables
Debugging DDL Commands Attempt to identify trivial errors by
comparing the command with the error message/position
Take an incremental approach Create the table one field at a time until you
find the field that is causing the problem Modify one column at a time
Multiple modifications could be performed in a single statementALTER TABLE student MODIFY student_age NUMBER(3) NOT NULLADD CONSTRAINT student_pk PRIMARY KEY (student_id)