SQL: Part 1 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.

Slides:



Advertisements
Similar presentations
9 Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Advertisements

9 Creating and Managing Tables. Objectives After completing this lesson, you should be able to do the following: Describe the main database objects Create.
Data Definition Language (DDL)
Manipulating Data Schedule: Timing Topic 60 minutes Lecture
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
9-1 Copyright  Oracle Corporation, All rights reserved. Data Manipulation Language A DML statement is executed when you: – Add new rows to a table.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
8 Copyright © Oracle Corporation, All rights reserved. Manipulating Data.
Copyright  Oracle Corporation, All rights reserved. 9 Manipulating Data: INSERT, UPDATE, DELETE.
At the end of this lesson, you should be able to: Describe each DML statement Insert rows into a table Update rows in a table Delete rows from a table.
Structured Query Language S Q L. What is SQL It is a database programming language developed by IBM in the early 1970’s. It is used for managing and retrieving.
o At the end of this lesson, you will be able to:  Describe the life-cycle development phases  Discuss the theoretical and physical aspects of a relational.
4-1 Copyright  Oracle Corporation, All rights reserved. Data Manipulation Language (DML)
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 (DDL & DML Commands)
Lecture 2: Using DDL Statements to Create and Manage Tables & Indexes
10 Creating and Managing Tables Objectives At the end of this lesson, you will be able to: Describe the main database objects Create tables Describe.
10 Copyright © Oracle Corporation, All rights reserved. Including Constraints.
10-1 Copyright  Oracle Corporation, All rights reserved. Database Objects ObjectDescription TableBasic unit of storage; composed of rows and columns.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
Copyright  Oracle Corporation, All rights reserved. 10 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.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
11-1 Copyright  Oracle Corporation, All rights reserved. What Are Constraints? Constraints enforce rules at the table level. Constraints prevent.
10 Copyright © Oracle Corporation, All rights reserved. Including Constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Copyright  Oracle Corporation, All rights reserved. 11 Including Constraints.
Copyright  Oracle Corporation, All rights reserved. Introduction.
Copyright  Oracle Corporation, All rights reserved. 4 Introduction.
9 Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Schema Objects.
INCLUDING CONSTRAINTS lecture5. Outlines  What are Constraints ?  Constraint Guidelines  Defining Constraint  NOT NULL constraint  Unique constraint.
11 Including Constraints Objectives At the end of this lesson, you will be able to: Describe constraints Create and maintain constraints At the.
Manipulating Data. Objectives After completing this lesson, you should be able to do the following: Describe each DML statement Insert rows into a table.
9 Manipulating Data. 9-2 Objectives At the end of this lesson, you should be able to: Describe each DML statement Insert rows into a table Update rows.
9 Copyright © Oracle Corporation, All rights reserved. Creating and Managing Tables.
SQL CREATING AND MANAGING TABLES lecture4 1. Database Objects ObjectDescription TableBasic unit of storage; composed of rows and columns ViewLogically.
Copyright  Oracle Corporation, All rights reserved. 12 Creating Views.
Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Copyright © 2004, Oracle. All rights reserved. Lecture 2: Using DDL Statements to Create and Manage Tables & Indexes ORACLE.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
DDL and Views. Database Objects Logically represents subsets of data from one or more tables View Generates numeric valuesSequence Basic unit of storage;
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Creating and Managing Tables 14. ObjectivesObjectives After completing this lesson, you should be able to do the following: After completing this lesson,
Relational Database Management System(RDBMS) Structured Query Language(SQL)
At the end of this lesson, you will be able to: Describe constraints Create and maintain constraints.
Including Constraints. What Are Constraints? Constraints enforce rules at the table level. You can use constraints to do the following: – Enforce rules.
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
Copyright  Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
Installation Oracle 11g Express 2 double click the "setup" button to install the Oracle.
LECTURE FOUR Introduction to SQL DDL with tables DML with tables.
Physical Model Lecture 11. Physical Data Model The last step is the physical design phase, In this phase data is – Store – Organized and – Access.
SQL Statements SELECT INSERTUPDATEDELETECREATEALTERDROPRENAMETRUNCATECOMMITROLLBACKSAVEPOINTGRANTREVOKE Data Retrieval Language (DRL) Data Retrieval Language.
Creating and Managing Tables. Database Objects ObjectDescription TableBasic unit of storage; composed of rows and columns ViewLogically represents subsets.
Communicating with a RDBMS Using SQL Database SQL> SELECT loc 2 FROM dept; SQL> SELECT loc 2 FROM dept; SQL statement is entered Statement is sent to database.
Insert, update, delete TCL. Data Manipulation Language – A DML statement is executed when you: Add new rows to a table Modify existing rows in a table.
Including Constraints
SQL Creating and Managing Tables
Manipulating Data.
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
Using DDL Statements to Create and Manage Tables
SQL Creating and Managing Tables
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
SQL Creating and Managing Tables
(SQL) Manipulating Data
SQL Statements SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME
Using DDL Statements to Create and Manage Tables
Using DDL Statements to Create and Manage Tables
Presentation transcript:

SQL: Part 1 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial use. Do not redistribute. Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial use. Do not redistribute.

2 OUTLINE  Overview of SQL  Creating and Modifying Tables  Including Constraints  Basics of Manipulating Data  Overview of SQL  Creating and Modifying Tables  Including Constraints  Basics of Manipulating Data

What is SQL? A standardized non-procedural language used to create, manipulate and manage a database; consists of: – Data Definition Language (DDL): –Commands that create, alter and drop tables – Data Manipulation Language (DML) –Commands that maintain and query tables – Data Control Language (DCL) –Commands that administer privileges and commit data The many “flavors” of SQL: – Original Flavor: SQL/DS – Improved Flavors: SQL/86, SQL/89, SQL/92 – Emerging Flavors: SQL-3, SQL*Plus, PL/SQL, Transact-SQL A standardized non-procedural language used to create, manipulate and manage a database; consists of: – Data Definition Language (DDL): –Commands that create, alter and drop tables – Data Manipulation Language (DML) –Commands that maintain and query tables – Data Control Language (DCL) –Commands that administer privileges and commit data The many “flavors” of SQL: – Original Flavor: SQL/DS – Improved Flavors: SQL/86, SQL/89, SQL/92 – Emerging Flavors: SQL-3, SQL*Plus, PL/SQL, Transact-SQL

4 SQL Statements SELECT INSERTUPDATEDELETECREATEALTERDROPRENAMETRUNCATECOMMITROLLBACKSAVEPOINTGRANTREVOKESELECT INSERTUPDATEDELETECREATEALTERDROPRENAMETRUNCATECOMMITROLLBACKSAVEPOINTGRANTREVOKE Data retrieval (DML) Data retrieval (DML) Data manipulation language (DML) Data definition language (DDL) Transaction control Data control language (DCL)

SQL Processing Order Taken with permission from McFadden, Hoffer & Prescott, 1999

Creating and Modifying Tables

7 Tables in the SQL Database User Tables – Collection of tables created and maintained by the user – Contain user information Data Dictionary – Collection of tables created and maintained by the SQL server – Contain database information User Tables – Collection of tables created and maintained by the user – Contain user information Data Dictionary – Collection of tables created and maintained by the SQL server – Contain database information

8 Naming Conventions Generally, must begin with a letter Can be 1–128 characters long Can contain A–Z, a–z, 0–9, $, and # Must not duplicate the name of another object owned by the same user Must not be a reserved word Object names starting with special characters #) have certain uses Generally, must begin with a letter Can be 1–128 characters long Can contain A–Z, a–z, 0–9, $, and # Must not duplicate the name of another object owned by the same user Must not be a reserved word Object names starting with special characters #) have certain uses

9 The CREATE TABLE Statement You must have : – CREATE TABLE privilege – A storage area You specify: – Table name – Column name, column data type, and column size You must have : – CREATE TABLE privilege – A storage area You specify: – Table name – Column name, column data type, and column size CREATE TABLE table (column datatype [DEFAULT expr][,...])

10 Creating Tables SQL> CREATE TABLE dept 2(deptno NUMERIC(2), 3 dname VARCHAR(14), 4 loc VARCHAR(14)) Table created. Create the table Confirm table creation SQL> EXEC sp_help dept Name Null? Type DEPTNO NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13)

11 Data Types Data TypeDescription VARCHAR(size)Variable-length character data CHAR(size) Fixed-length character data NUMERIC(p,s) Variable-length numeric data DATETIME Date and time values INT and SMALLINTInteger up to 4 bytes or small integer up to 2 bytes VARBINARYVariable length binary data up to 8KB IMAGEVariable length binary data up to 2.14 GB

12 The ALTER TABLE Statement Use the ALTER TABLE statement to: Add a new column Modify an existing column Define a default value for the new column Use the ALTER TABLE statement to: Add a new column Modify an existing column Define a default value for the new column ALTER TABLE table ADD (column datatype [DEFAULT expr] ALTER TABLE table ALTER COLUMN (column datatype [DEFAULT expr]

13 Adding a Column DEPT30 EMPNO ENAME ANNSAL HIREDATE BLAKE MAY MARTIN SEP ALLEN FEB TURNER SEP “…add a new column into DEPT30 table…” DEPT30 EMPNO ENAME ANNSAL HIREDATE BLAKE MAY MARTIN SEP ALLEN FEB TURNER SEP JOB New column

14 Adding a Column You use the ADD clause to add columns. EMPNO ENAME ANNSAL HIREDATE JOB BLAKE MAY MARTIN SEP ALLEN FEB TURNER SEP rows selected. EMPNO ENAME ANNSAL HIREDATE JOB BLAKE MAY MARTIN SEP ALLEN FEB TURNER SEP rows selected. SQL> ALTER TABLE dept30 2 ADD (job VARCHAR(9)) Table altered. The new column becomes the last column.

15 Modifying a Column You can change a column’s datatype, size, and default value. A change to the default value affects only subsequent insertions to the table. You can change a column’s datatype, size, and default value. A change to the default value affects only subsequent insertions to the table. ALTER TABLEdept30 ALTER COLUMN ename VARCHAR(15) Table altered.

16 Dropping a Table All data and structure in the table is deleted. Any pending transactions are committed. All indexes are dropped. You cannot roll back this statement. All data and structure in the table is deleted. Any pending transactions are committed. All indexes are dropped. You cannot roll back this statement. SQL> DROP TABLE dept30 Table dropped.

17 Changing the Name of an Object To change the name of a table, view, sequence, or synonym, you execute the RENAME statement. You must be the owner of the object. To change the name of a table, view, sequence, or synonym, you execute the RENAME statement. You must be the owner of the object. SQL> RENAME dept TO department Table renamed.

18 Truncating a Table The TRUNCATE TABLE statement: – Removes all rows from a table – Releases the storage space used by that table You cannot roll back row removal when using TRUNCATE. Alternatively, you can remove rows by using the DELETE statement. The TRUNCATE TABLE statement: – Removes all rows from a table – Releases the storage space used by that table You cannot roll back row removal when using TRUNCATE. Alternatively, you can remove rows by using the DELETE statement. SQL> TRUNCATE TABLE department Table truncated.

Including Constraints

20 What Are Constraints? Constraints enforce rules at the table level. Constraints prevent the deletion of a table if there are dependencies. The following constraint types are valid in SQL: – NOT NULL – UNIQUE – PRIMARY KEY – FOREIGN KEY – CHECK Constraints enforce rules at the table level. Constraints prevent the deletion of a table if there are dependencies. The following constraint types are valid in SQL: – NOT NULL – UNIQUE – PRIMARY KEY – FOREIGN KEY – CHECK

21 Constraint Guidelines Name a constraint or the system will generate a name. Create a constraint: – At the same time as the table is created – After the table has been created Define a constraint at the column or table level. View a constraint in the data dictionary. Name a constraint or the system will generate a name. Create a constraint: – At the same time as the table is created – After the table has been created Define a constraint at the column or table level. View a constraint in the data dictionary.

22 Defining Constraints CREATE TABLE table (column datatype [DEFAULT expr] [column_constraint],... [table_constraint][,...]) CREATE TABLE emp( empno NUMERIC(4), ename VARCHAR(10),... deptno NUMERIC(7,2) NOT NULL, CONSTRAINT emp_empno_pk PRIMARY KEY (EMPNO))

23 The NOT NULL Constraint Ensures that null values are not permitted for the column EMP EMPNO ENAME JOB... COMM DEPTNO 7839KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER NOT NULL constraint (no row can contain a null value for this column) Absence of NOT NULL constraint (any row can contain null for this column) NOT NULL constraint

24 The NOT NULL Constraint Defined at the column level SQL> CREATE TABLE emp( 2 empno NUMERIC(4), 3enameVARCHAR(10) NOT NULL, 4jobVARCHAR(9), 5mgrNUMERIC(4), 6hiredateDATETIME, 7salMONEY, 8 commMONEY, 9deptnoNUMERIC(2) NOT NULL)

25 The UNIQUE Key Constraint DEPT DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON UNIQUE key constraint 50SALESDETROIT 60BOSTON Insert into Not allowed (DNAME already exists) Not allowed (DNAME  SALES already exists)Allowed

26 The UNIQUE Key Constraint Defined at either the table level or the column level SQL> CREATE TABLE dept( 2 deptno NUMERIC(2), 3dname VARCHAR(14), 4loc VARCHAR(14), 5CONSTRAINT dept_dname_uk UNIQUE(dname))

27 The PRIMARY KEY Constraint DEPT DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON PRIMARY KEY Insert into 20MARKETINGDALLAS FINANCENEW YORK Not allowed (DEPTNO20 already exists) Not allowed (DEPTNO  20 already exists) Not allowed (DEPTNO is null)

28 The PRIMARY KEY Constraint Defined at either the table level or the column level SQL> CREATE TABLE dept( 2 deptno NUMERIC(2), 3dname VARCHAR(14), 4loc VARCHAR(14), 5CONSTRAINT dept_dname_uk UNIQUE (dname), 6CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno)

29 The FOREIGN KEY Constraint DEPT DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS... PRIMARY KEY EMP EMPNO ENAME JOB... COMM DEPTNO 7839KINGPRESIDENT BLAKEMANAGER FOREIGN KEY 7571FORDMANAGER FORDMANAGER Insert into Not allowed (DEPTNO9 does not exist in the DEPT table) Not allowed (DEPTNO  9 does not exist in the DEPT table)Allowed

30 The FOREIGN KEY Constraint Defined at either the table level or the column level SQL> CREATE TABLE emp( 2 empno NUMERIC(4), 3enameVARCHAR(10) NOT NULL, 4jobVARCHAR(9), 5mgrNUMERIC(4), 6hiredateDATETIME, 7salMONEY, 8 commMONEY, 9deptnoNUMERIC(2) NOT NULL, 10CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno) 11REFERENCES dept (deptno))

31 FOREIGN KEY Constraint Keywords FOREIGN KEY Defines the column in the child table at the table constraint level REFERENCES Identifies the table and column in the parent table ON DELETE CASCADE Allows deletion in the parent table and deletion of dependent rows in the child table FOREIGN KEY Defines the column in the child table at the table constraint level REFERENCES Identifies the table and column in the parent table ON DELETE CASCADE Allows deletion in the parent table and deletion of dependent rows in the child table

32 The CHECK Constraint Defines a condition that each row must satisfy Note: Queries that refer to values in other rows are not allowed Defines a condition that each row must satisfy Note: Queries that refer to values in other rows are not allowed..., deptnoNUMERIC(2), CONSTRAINT emp_deptno_ck CHECK (DEPTNO BETWEEN 10 AND 99),...

Basics of Manipulating Data

34 Data Manipulation Language A DML statement is executed when you: – Add new rows to a table – Modify existing rows in a table – Remove existing rows from a table A transaction consists of a collection of DML statements that form a logical unit of work. A DML statement is executed when you: – Add new rows to a table – Modify existing rows in a table – Remove existing rows from a table A transaction consists of a collection of DML statements that form a logical unit of work.

35 Adding a New Row to a Table DEPT DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON New row 50 DEVELOPMENT DETROIT DEPT DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON “…insert a new row into DEPT table…” 50 DEVELOPMENT DETROIT

36 The INSERT Statement Add new rows to a table by using the INSERT statement. Only one row is inserted at a time with this syntax. Add new rows to a table by using the INSERT statement. Only one row is inserted at a time with this syntax. INSERT INTOtable [(column [, column...])] VALUES(value [, value...]) INSERT INTOtable [(column [, column...])] VALUES(value [, value...])

37 Inserting New Rows Insert a new row containing values for each column. List values in the default order of the columns in the table. Optionally list the columns in the INSERT clause. Enclose character and date values within single quotation marks. Insert a new row containing values for each column. List values in the default order of the columns in the table. Optionally list the columns in the INSERT clause. Enclose character and date values within single quotation marks. SQL> INSERT INTOdept (deptno, dname, loc) 2 VALUES(50, 'DEVELOPMENT', 'DETROIT') 1 row created.

38 Inserting Rows with Null Values Implicit method: Omit the column from the column list. SQL> INSERT INTOdept (deptno, dname ) 2 VALUES(60, 'MIS'); 1 row created. Explicit method: Specify the NULL keyword. SQL> INSERT INTOdept 2 VALUES(70, 'FINANCE', NULL); 1 row created.

39 Changing Data in a Table EMP “…update a row in EMP table…” EMP EMPNO ENAME JOB... DEPTNO 7839KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER EMPNO ENAME JOB... DEPTNO 7839KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER 20...

40 The UPDATE Statement Modify existing rows with the UPDATE statement. Update more than one row at a time, if required. Modify existing rows with the UPDATE statement. Update more than one row at a time, if required. UPDATEtable SETcolumn = value [, column = value,...] [WHERE condition] UPDATEtable SETcolumn = value [, column = value,...] [WHERE condition]

41 Updating Rows in a Table Specific row or rows are modified when you specify the WHERE clause. All rows in the table are modified if you omit the WHERE clause. Specific row or rows are modified when you specify the WHERE clause. All rows in the table are modified if you omit the WHERE clause. SQL> UPDATE emp 2 SET deptno = 20 3 WHERE empno = row updated. SQL> UPDATE employee 2 SET deptno = rows updated. SQL> UPDATE employee 2 SET deptno = rows updated.

42 “…delete a row from DEPT table…” Removing a Row from a Table DEPT DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON 50 DEVELOPMENT DETROIT 60MIS... DEPT DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON 60MIS...

43 The DELETE Statement You can remove existing rows from a table by using the DELETE statement. DELETE [FROM] table [WHERE condition]; DELETE [FROM] table [WHERE condition];

44 Specific rows are deleted when you specify the WHERE clause. All rows in the table are deleted if you omit the WHERE clause. Specific rows are deleted when you specify the WHERE clause. All rows in the table are deleted if you omit the WHERE clause. Deleting Rows from a Table SQL> DELETE FROMdepartment 2 WHERE dname = 'DEVELOPMENT' 1 row deleted. SQL> DELETE FROMdepartment 2 WHERE dname = 'DEVELOPMENT' 1 row deleted. SQL> DELETE FROMdepartment 4 rows deleted. SQL> DELETE FROMdepartment 4 rows deleted.

45 Deleting Rows: Integrity Constraint Error SQL> DELETE FROMdept 2 WHEREdeptno = 10 SQL> DELETE FROMdept 2 WHEREdeptno = 10 DELETE FROM dept * ERROR at line 1: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found DELETE FROM dept * ERROR at line 1: integrity constraint (USR.EMP_DEPTNO_FK) violated - child record found You cannot delete a row that contains a primary key that is used as a foreign key in another table. You cannot delete a row that contains a primary key that is used as a foreign key in another table.