Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1

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

3 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

4 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

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

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

7 Creating and Modifying Tables

8 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

9 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

10 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][,...])

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

12 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

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

14 13 Adding a Column DEPT30 EMPNO ENAME ANNSAL HIREDATE ------ ------------------ 7698BLAKE 3420001-MAY-81 7654MARTIN 1500028-SEP-81 7499ALLEN 1920020-FEB-81 7844TURNER 1800008-SEP-81... “…add a new column into DEPT30 table…” DEPT30 EMPNO ENAME ANNSAL HIREDATE ------ ------------------ 7698BLAKE 3420001-MAY-81 7654MARTIN 1500028-SEP-81 7499ALLEN 1920020-FEB-81 7844TURNER 1800008-SEP-81... JOB New column

15 14 Adding a Column You use the ADD clause to add columns. EMPNO ENAME ANNSAL HIREDATE JOB --------- ---------- --------- --------- ---- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81... 6 rows selected. EMPNO ENAME ANNSAL HIREDATE JOB --------- ---------- --------- --------- ---- 7698 BLAKE 34200 01-MAY-81 7654 MARTIN 15000 28-SEP-81 7499 ALLEN 19200 20-FEB-81 7844 TURNER 18000 08-SEP-81... 6 rows selected. SQL> ALTER TABLE dept30 2 ADD (job VARCHAR(9)) Table altered. The new column becomes the last column.

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

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

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

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

20 Including Constraints

21 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

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

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

24 23 The NOT NULL Constraint Ensures that null values are not permitted for the column EMP EMPNO ENAME JOB... COMM DEPTNO 7839KINGPRESIDENT 10 7698BLAKEMANAGER 30 7782CLARKMANAGER 10 7566JONESMANAGER 20... 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

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

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

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

28 27 The PRIMARY KEY Constraint DEPT DEPTNO DNAME LOC ------ ------------------ 10ACCOUNTINGNEW 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)

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

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

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

32 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

33 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),...

34 Basics of Manipulating Data

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

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

37 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...])

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

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

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

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

42 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 = 7782 1 row updated. SQL> UPDATE employee 2 SET deptno = 20 14 rows updated. SQL> UPDATE employee 2 SET deptno = 20 14 rows updated.

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

44 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];

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

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


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

Similar presentations


Ads by Google