Sql DDL queries CS 260 Database Systems.

Slides:



Advertisements
Similar presentations
Database Chapters.
Advertisements

Pertemuan ke 2 Tipe data & ERD Kurniawan Eka Permana.
Action Queries CS 320. Review: SQL Command Types  Data Definition Language (DDL)  Used to create and modify database objects  Data Manipulation Language.
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.
1 Chapter 2: Creating and Modifying Database Tables.
Guide to Oracle 10g1 Chapter 2: Creating and Modifying Database Tables.
Creating Database Tables © Abdou Illia MIS Spring /21/2015.
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.
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.
Phonegap Bridge – File System CIS 136 Building Mobile Apps 1.
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.
Introduction to SQL  SQL or sequel  It is a standardised language with thousands of pages in the standard  It can be in database system through GUI,
1 Chapter 2: Creating and Modifying Database Tables.
Oracle Data Definition Language (DDL)
Copyright © Curt Hill SQL The Data Definition Language.
Chapter 9 SQL and RDBMS Part C. SQL Copyright 2005 Radian Publishing Co.
ASP.NET Programming with C# and SQL Server First Edition
Database Design lecture 3_1 1 Database Design Lecture 3_1 Data definition in SQL.
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.
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.
Oracle Database Administration
10 Copyright © 2009, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
1 Copyright © 2006, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
SQL Data Definition Language (DDL) Using Microsoft SQL Server 1SDL Data Definition Language (DDL)
1 SQL Tarek El-Shishtawy Professor Ass. Of Computer Engineering.
1 Creating and Modifying Database Objects. 2 An Oracle database consists of multiple user accounts Each user account owns database objects Tables Views.
11 3 / 12 CHAPTER Databases MIS105 Lec15 Irfan Ahmed Ilyas.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
Advanced Database CS-426 Week 1 - Introduction. Database Management System DBMS contains information about a particular enterprise Collection of interrelated.
Advanced Web 2012 Lecture 3 Sean Costain What is a Database? Sean Costain 2012 A database is a structured way of dealing with structured information.
Tables and Constraints Oracle PL/SQL. Datatypes The SQL Data Definition Language Commands (or DDL) enable us to create, modify and remove database data.
Oracle 11g: SQL Chapter 4 Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Lecture5: SQL Overview, Oracle Data Type, DDL and Constraints Ref. Chapter6 Lecture4 1.
SQL CREATING AND MANAGING TABLES lecture4 1. Database Objects ObjectDescription TableBasic unit of storage; composed of rows and columns ViewLogically.
SQL ACTION QUERIES AND TRANSACTION CONTROL CS 260 Database Systems.
1 Chapter 2: Creating and Modifying Database Objects.
SQL Overview Structured Query Language
©Silberschatz, Korth and Sudarshan1 Structured Query Language (SQL) Data Definition Language Domains Integrity Constraints.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
1 CS 430 Database Theory Winter 2005 Lecture 11: SQL DDL.
Academic Year 2015 Autumn. MODULE CC2006NI: Data Modelling and Database Systems Academic Year 2015 Autumn.
Lecture # 24 Introduction to SQL Muhammad Emran Database Systems.
LECTURE FOUR Introduction to SQL DDL with tables DML with tables.
Understand Data Definition Language (DDL) Database Administration Fundamentals LESSON 1.4.
CIT 214 Introduction to Database Management
Guide to Oracle 10g Chapter 2: Creating and Modifying Database Tables.
CS 3630 Database Design and Implementation
Managing Tables, Data Integrity, Constraints by Adrienne Watt
ORACLE SQL Developer & SQLPLUS Statements
SQL data definition using Oracle
Oracle Data Definition Language (DDL)
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Chapter 2: Creating And Modifying Database Tables
Database Instructor: Bei Kang.
SQL (Structured Query Language)
Presentation transcript:

sql DDL queries CS 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 Specifying constraints 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 Specifying constraints 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 Specifying constraints 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 MySQL 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)

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

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

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

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)

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

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)

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

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

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

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

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

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

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) CANDY_CUSTOMER CANDY_PURCHASE CANDY_CUST_TYPE CANDY_PRODUCT

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

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

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

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

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

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

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