Introduction to SQL Outline Overview of Structured Query language (SQL) Components of SQL DDL Commands: Basics 2 SQL: Overview Pronunciation: “S-Q-L” or “Sequel” Stands for: Structured Query Language SQL has become the de facto standard language for creating and querying relational databases SQL has been implemented in various platforms that include mainframe and personal computer systems 3 SQL Standard: Purposes Specify the syntax and semantics of SQL data definition and manipulation languages – Define the data structures and basic operations for designing, accessing, maintaining, controlling, and protecting SQL database – Provide a vehicle for portability of database definition and application modules between conforming DBMSs 4 SQL Standards: Key Benefits Reduced training costs Increased productivity Improved application portability Reduced dependence on a single vendor Enhanced cross-system communications 5 SQL: Components Data Definition Language (DDL) Three types of SQL commands - Creating a database – Commands that define a database, including creating, altering, and dropping tables and establishing constraints Maintain and Data Manipulation Language (DML) -query the – Commands that maintain and query a database Data Control Language (DCL) 6 – Commands that control a database, including administering privileges and committing data database SQL: Data Definition Language Data Definition Language (DDL) consists of the SQL commands used to define a database, including – Creating, altering, dropping tables and established constraints For production (operational) databases, DDL commends usually are restricted to DBA to protect a fundamental database structure from unexpected or accidental changes it's like giving the keys to the castle only to those who are trained and responsible for it, to prevent accidents or mistakes that could disrupt the database's operation 7 DDL Commands Table-related commands: Defines a table and its columns – CREATE TABLE – DROP TABLE – ALTER TABLE - Make changes to an existing database Index-related commands: Defines an index on one column or a concatenation of columns that enables rapid access to the rows of a table Makes it easier and faster – CREATE INDEX – DROP INDEX View-related commands: Defines a logical table from one or Virtual table more tables or views – CRETAE VIEW – DROP VIEW 8 Creating A Table: Process Select appropriate data type for each attribute, including length, precision, and value range Determine the NULL value issue for each attribute Determine the UNIQUE issue for each attribute Determine the primary key and foreign key(s) Determine the DEFAULT value issue for each attribute Determine the update and delete behavior Create the table 9 Create Table: Data Dictionary Shows the columns in the EMPLOYEE table Attribute SSN Char 9 First Varchar 15 NN Last Varchar 15 NN Birth_Date Date -- Address Varchar 20 Gender Char 1 Salary Decimal Dep_No Char DEPARTMENT EMPLOYEE 10 Data type Length Unique Null PK Y Dep_No Char(3), FOREIGN KEY (Dep_No) REFERENCES Department(Dept_No) 10.2 3 DEPARTMENT (Dept_No) Dept_Name Dept_No Location SSN First Last BirthDate FK PK - Primary key NN- not null, cannot be a null value FK - Foreign key Y - It is the primary key Address Gender Salary Dept_No Create Table: Data Dictionary (2) DEPARTMENT TABLE Attribute Data type Length Unique Null PK Dept_Name Varchar 15 Dept_No Char 3 Location Varchar 50 FK Y Y NN -DEPARTMENT NAME IS UNIQUE - TWO HUMAN --RESOURCES IN COMPANY LOCATION CANNOT BE NULL NO FOREIGN KEY FOR DEPARTMENT TABLE * Foreign key and Primary key should have the same Dept_Name Dept_No Location DEPARTMENT data type EMPLOYEE SSN First Last BirthDate Address Gender Salary Dept_No CREATE DATA DICTIONARY BASED ON THE LOGICAL SCHEMA 11 Creating A Table: Data Type (1) Varchar(M) Variable character – Variable Character Field is a set of character data of indeterminate length – M represents the maximum column length in characters Char (M) Characters – Character Field is a set of character data of determinate length – M represents the column length in characters Text – Extremely long field for text. May not be used as key and can be difficult to sort 12 Creating A Table: Data Type (2) Integer Fixed length – Ranging from -2,147,483,648 to 2147,483,647. Decimal (M,D) – M is the total number of digits and D is the number of digits after the decimal point. – The maximum number of digits (M) is 65 Date – Ranging from '1000-01-01' to '9999-12-31' in 'YYYY-MM-DD' format TIME – Ranging from '-838:59:59' to '838:59:59' in 'HH:MM:SS' format 13 Table Creation: Syntax Simplified syntax for CREATE TABLE: define table name CREATE TABLE tablename ({column definition [constraint]}, …); define 1st column define 2nd column where format of column definition: column_name {datatype [(size)]} format of constraint: [CONSTRAINT constraint_name] Constraint_type [constraint_attributes] 14 Create Table: Example table name CREATE TABLE PROJECT( 1st columnchar with length of '3' Prj_No char(3) primary key, 2nd column Prj_Name varchar(30) not null UNIQUE, 3rd column Dep_No char(3), CONSTRAINT FK_PRJ_DEPT foreign key (Dep_No) references DEPT(D_No) on delete SET NULL ); 15 Order Management Database Example Customer_ID CUSTOMER 1..1 Name City TEL State O_No Order_Date Ship_Date Shipping_Addr Status Payment Contact 1..1 TEL Status MSPR Name Provides Product_ID Cost 0..N PRODUCT_ Consists_Of ORDER 0..N 1..M Order_Cycle 0..N PRODUCT 1..1 Keeps 0..N INVENTORY 1..1 Quantity Is_Created _For 0..N PROMOTION 16 Name VENDOR ZIP Address Places VID Street PM_No Effective_Date End_Date Sales_Price Quantity Stack_No Order Management Database Example VENDOR VID PRODUCT Product_ID VName Contact TEL Order_Cycle Product_Name VID Status MSRP Cost INVENTORY Stack_No Product_ID Quantity PROMOTION PM_No ORDER_DETAIL O_No PORDER O_No CUSTOMER 17 Product_ID Sales_Price Eff_Date End_Date Product_ID Quantity Order_Date Customer_ID Ship_Date Customer_ID Customer_Name Ship_Addr TEL Street Status Payment City State ZIP Create Table: Example (1) CREATE TABLE VENDOR( VID char (10), Comma(,) to separate attributes VName varchar(50) NOT NULL UNIQUE, Contact varchar(50), TEL char(10), Semi-colon(;) to end a command Order_Cycle char(25), CONSTRAINT PK_Vendor primary key (VID)); keyword primary key for the vendor Defining multiple columns together as the primary key 18 Create Table: Example (1) CREATE TABLE VENDOR( VID char (10), VName varchar(50) NOT NULL UNIQUE, Contact varchar(50), TEL char(10), Details of the constraint Order_Cycle char(25), CONSTRAINT PK_Vendor primary key (VID)); Keyword for defining a constraint 19 Name of the constraint Create Table: Example (2) CREATE TABLE VENDOR( VID char (10) PRIMARY KEY, VName varchar(50) NOT NULL UNIQUE, Contact varchar(50), TEL char(10), Order_Cycle char(25)); Define the primary key as an anonymous constraint. 20 Named versus Anonymous Constraints When a constraint is created without a name, the DBMS will assign one (such as PK__B__B_COL1__75435199) Benefits of naming a constraint – If a query (insert, update, delete) violates a constraint, SQL will generate an error message that will contain the constraint name. If the constraint name is clear and descriptive, the error message will be easier to understand – If a constraint needs to be modified in the future, it's very hard to do if you don't know what it's named 21 Exercise Please create the table CUSTOMER based on the following specification Attribute 22 Data type Length Unique Null PK Customer_ID char 10 Y Customer_Name varchar 50 NN TEL char 10 NN Address varchar 100 City varchar 30 State char 2 ZIP char 5 FK Solution CREATE TABLE CUSTOMER( Customer_ID char(10) primary key, Customer_name varchar(50) Not null, tel char(10) not null, address varchar(100), city varchar(30), state char(2), zip char(5) ); 23 SQL Constraints SQL constraints are used to specify rules for data in a table – NOT NULL - Ensures that a column cannot have a NULL value – UNIQUE - Ensures that all values in a column are different – PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table – FOREIGN KEY - Uniquely identifies a row/record in another table – DEFAULT - Sets a default value for a column when no value is specified – INDEX - Used to create and retrieve data from the database very quickly 24 Create Table with FK: Example (1) Create Table PRODUCT ( Product_ID char(13) primary key, Product_Name varchar(50) not null unique, to define VID char(10) references Vendor(VID), Used foreign key Status char(10), MSRP decimal(10.2), Cost decimal (10.2) not null ); 25 Create Table with FK: Example (2) Create Table INVENTORY ( Stack_No char(10), Product_ID char(13) references Product(Product_ID), Quantity integer, Constraint PK_Inventory primary key (Stack_NO) ); 26 Exercise Please create the table PORDER based on the following specification Attribute Data type Length Unique Null PK O_No char Order_Date date Customer_ID char 27 10 FK Y NN 10 Ship_Date date Ship_Addr varchar 300 Status varchar 50 Payment varchar 50 NN Customer(Customer_ID) Solution 1 CREATE TABLE PORDER ( O_No char(10), Order_Date date not null, Customer_ID char(10) not null, Ship_Date date, Ship_Addr varchar(300), Status varchar(50), Payment varchar(50), CONSTRAINT PK_PORDER primary key(O_No), CONSTRAINT FK_PORDER_CUST foreign key (Customer_ID) references Customer(Customer_ID) ); 28 Solution 2 CREATE TABLE PORDER ( O_No char(10) primary key, Order_Date date not null, Customer_ID char(10) not null references Customer(Customer_ID), Ship_Date date, Ship_Addr varchar(300), Status varchar(50), Payment varchar(50) ); 29 Create Table with FK: Example (3) Create Table ORDER_DETAIL ( O_No char(10), Product_ID char(13) not null, Quantity integer, Constraint PK_ODetail primary key (O_No, Product_ID), Constraint FK_OD_PO foreign key (O_No) references PORDER(O_No), Constraint FK_OD_PRD foreign key (Product_ID) references Product(Product_ID) ); Defines the composite primary key! 30 Default Value The DEFAULT constraint is used to insert a default value into a column when that column is left blank. Create Table Promotion ( PM_No char(10) primary key, Product_ID char(13) not null references Product(Product_ID) , Sales_Price decimal(10,2) DEFAULT 9.99, Eff_Date date not null, End_Date date ); 31 Removing Tables Use DROP TABLE statement to remove a table and all its data – CREATE commands may be reversed by using a DROP command. – DROP TABLE destroys a table, including its definition, contents, and any constraints associated with it. Example name of the table – DROP TABLE ORDER_DETAIL; 32 Changing Table Definitions (1) ALTER TABLE statement may include keywords ADD: add new columns to an existing table Add a gender column to CUSTOMER table ALTER TABLE CUSTOMER ADD (gender VARCHAR(1)); Add column – When a new column is added, its value will be NULL for all existing rows. 33 Changing Table Definitions (2) MODIFY: Change the columns’ names, datatype, lengths, and constraints – Change the length of Ship_Addr to 500 ALTER TABLE PORDER Modify ship_Addr varchar(500); DROP: Remove one columns from a table – Drop the attribute Order_Cycle from the Vendor TABLE ALTER TABLE VENDOR DROP Order_Cycle; 34 Exercise Please use the ALTER TABLE command to modify the VENDOR table on the Contact column to make the length as 30 Please use the ALTER TABLE command to modify the VENDOR table to set TEL as unique 35 Solution ALTER TABLE VENDOR MODIFY contact varchar(30); ALTER TABLE VENDOR MODIFY tel char(10) unique; ≡ ALTER TABLE VENDORMODIFY contact varchar(30),MODIFY tel char(10) unique; 36 Changing Table Definitions (3): Rename Table We can use the following statements to rename a table: ALTER TABLE <table_name> RENAME TO <new_table_name>; For example, we can change the table name “vender” to “supplier” ALTER TABLE VENDOR RENAME TO SUPPLIER; 37