Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sql DDL queries CS 260 Database Systems.

Similar presentations


Presentation on theme: "Sql DDL queries CS 260 Database Systems."— Presentation transcript:

1 sql DDL queries CS 260 Database Systems

2 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

3 Overview Creating tables Specifying constraints
CREATE Naming practices Data types Specifying constraints Modifying/dropping tables

4 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> );

5 Creating Tables Oracle example CREATE TABLE student(
student_id NUMBER(6), student_name VARCHAR2(30), student_DOB DATE );

6 Overview Creating tables Specifying constraints
CREATE Naming practices Data types Specifying constraints Modifying/dropping tables

7 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

8 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

9 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

10 Overview Creating tables Specifying constraints
CREATE Naming practices Data types Characters Numbers Dates Objects Specifying constraints Modifying/dropping tables

11 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

12 Data Types Characters Oracle MySQL CHAR, NCHAR VARCHAR2, NVARCHAR2
CLOB MySQL CHAR VARCHAR TEXT

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

14 Data Types CHAR, NCHAR (Oracle) and CHAR (MySQL) Examples Oracle MySQL
CREATE TABLE <table_name> ( student_gender CHAR(1) ); CREATE TABLE <table_name> ( student_gender CHAR );

15 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

16 Data Types VARCHAR2, NVARCHAR2 (Oracle) and VARCHAR (MySQL) Examples
CREATE TABLE <table_name> ( student_name VARCHAR2(30) ); CREATE TABLE <table_name> ( student_name VARCHAR(30) );

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

18 Data Types CLOB (Oracle) and TEXT (MySQL) Examples Oracle MySQL
CREATE TABLE <table_name> ( student_summary CLOB ); CREATE TABLE <table_name> ( student_summary MEDIUMTEXT );

19 Data Types Numbers Use for data that is entirely numeric Oracle MySQL
Not always the case for phone numbers, postal codes, social security numbers, etc. Oracle NUMBER MySQL INT DOUBLE DECIMAL (NUMERIC)

20 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 and 10126 If only one value is specified, then the value applies to the precision

21 Data Types Numbers in Oracle NUMBER Examples
CREATE TABLE <table_name> ( student_age NUMBER(2) ); CREATE TABLE <table_name> ( item_price NUMBER(5,2) );

22 Data Types Numbers in MySQL INT DOUBLE DECIMAL (NUMERIC)
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) Must specify the precision and scale Can be more precise than DOUBLE or FLOAT but takes more space

23 Data Types Numbers in MySQL Number examples
CREATE TABLE <table_name> ( student_age INT(2) ); CREATE TABLE <table_name> ( item_price DECIMAL(5,2) );

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

25 Data Types Dates in MySQL Date example (both Oracle and 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 );

26 Data Types Objects Oracle MySQL
BLOB BFILE MySQL BLOB is an acronym for “binary large object”

27 Data Types Objects in Oracle BLOB BFILE
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

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

29 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’) );

30 Overview Creating tables Specifying constraints
Primary keys Foreign keys Composite keys NOT NULL DEFAULT UNIQUE CHECK conditions Modifying/dropping tables

31 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

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

33 Constraints Viewing constraints Oracle MySQL
Oracle provided constraint names will begin with “SYS_” MySQL SELECT constraint_name FROM user_constraints WHERE table_name = ‘<table name>’ SELECT index_name FROM information_schema.table_constraints WHERE constraint_schema = ‘<schema>’;

34 Primary Keys Primary key creation syntax
CREATE TABLE <table_name> ( <pk_field_name> <type> PRIMARY KEY, <fieldN_name> <type> ); Single column primary keys can be specified at the column level CREATE TABLE <table_name>( <pk_field_name> <type>, <fieldN_name> <type>, CONSTRAINT <constraint_name> PRIMARY KEY (<pk_field_name>) ); Alternatively, primary keys can be specified at the table-level

35 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)?

36 Sample Database (CANDY)
CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT

37 Foreign Keys Foreign key creation syntax CREATE TABLE candy_customer (
<fk_field_name> <type> REFERENCES <parent_table>(<parent_table_pk_field_name>), <fieldN_name> <type> ); Foreign keys in Oracle can be specified at the column level 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>) ); Alternatively, foreign keys can be specified at the table-level

38 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>) );

39 NOT NULL Requires a column’s values to be non-null
CREATE TABLE <table_name>( <fieldM_name> <type> NOT NULL, <fieldN_name> <type> ); Works in both Oracle and MySQL CREATE TABLE <table_name>( <fieldM_name> <type> CONSTRAINT <constraint_name> NOT NULL, <fieldN_name> <type> ); Works in Oracle only

40 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 );

41 UNIQUE Requires all column values to be unique Syntax and example
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) );

42 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 <table_name>( <field1_name> <type>, <fieldN_name> <type>, CONSTRAINT <constraint_name> CHECK (<condition>) ); CREATE TABLE student ( student_gender VARCHAR(1), CONSTRAINT student_gender_ck CHECK (student_gender IN (‘M’,’F’)) );

43 Overview Creating tables Specifying constraints
Modifying/dropping tables

44 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

45 Modifying Database Tables
Add column Modify column syntax Remove column syntax ALTER TABLE <table_name> ADD <field_name> <datatype> <constraints> ALTER TABLE student ADD student_age NUMBER(2) NOT NULL ALTER TABLE <table_name> MODIFY <field_name> <datatype> <constraints> ALTER TABLE student MODIFY student_age NUMBER(3) NOT NULL ALTER TABLE <table_name> DROP COLUMN <field_name> ALTER TABLE student DROP COLUMN student_age

46 Modifying Database Tables
Add constraint syntax Remove constraint syntax Oracle MySQL ALTER TABLE <table_name> ADD CONSTRAINT constraint_name <constraint> (<column(s)>) ALTER TABLE student ADD CONSTRAINT student_pk PRIMARY KEY (student_id) ALTER TABLE <table_name> DROP CONSTRAINT <constraint_name> ALTER TABLE student DROP CONSTRAINT student_pk ALTER TABLE <table_name> DROP PRIMARY KEY ALTER TABLE student DROP PRIMARY KEY

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

48 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 statement ALTER TABLE student MODIFY student_age NUMBER(3) NOT NULL ADD CONSTRAINT student_pk PRIMARY KEY (student_id)


Download ppt "Sql DDL queries CS 260 Database Systems."

Similar presentations


Ads by Google