1 / 71

Lecture 1: SQL: DDL & DML

Lecture 1: SQL: DDL & DML. DCO11310 Database Systems and Design By Rose Chang. Outline of Lecture. SQL and its Origins Overview of Oracle 9i & iSQL*Plus Writing DML & DDL Write a SELECT statement that: Returns all rows and columns from a table Returns specified columns from a table

prema
Download Presentation

Lecture 1: SQL: DDL & DML

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 1: SQL: DDL & DML DCO11310 Database Systems and Design By Rose Chang

  2. Outline of Lecture • SQL and its Origins • Overview of Oracle 9i & iSQL*Plus • Writing DML & DDL • Write a SELECT statement that: • Returns all rows and columns from a table • Returns specified columns from a table • Uses column aliases to give descriptive column headings • Returns specified rows from a table • Re-order the rows

  3. SQL - Background • SQL (Sequel) most commonly used relational query and modification language • Core is equivalent to relational algebra • Wealth of additional features (e.g., aggregation, updates) • Designed at IBM Research (Systems R*) • Declarative query language • Many different standards • ANSI SQL (SQL1), SQL-92 (SQL2) • Variety of different dialects produced by DBMS vendors

  4. What is a Table? A table is like a file that stores records with a 2-Dimension Structure) Example: Staff table

  5. SQL • Components of language • Schema definition, data retrieval, data modification, constraints, views, authorization, etc. • DDL = Data Definition Language • DML = Data Manipulation Language • DCL = Data Control Language

  6. SELECT INSERT UPDATE DELETE MERGE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE Data retrieval Data manipulation language (DML) Data definition language (DDL) Transaction control Data control language (DCL) SQL Statements

  7. Oracle9i

  8. Clients Any mail client Any browser Any FTP client Internet applications SQL Business logic and data Presentation and business logic Development tools System management PL/SQL Application servers Databases Java Network services Oracle Internet Platform

  9. SQL statements iSQL*Plus Internet Browser Oracle server Query results iSQL*Plus commands Formatted report Client SQL and iSQL*Plus Interaction

  10. SQL A language ANSI standard Keyword cannot be abbreviated Statements manipulate data and table definitions in the database iSQL*Plus An environment Oracle proprietary Keywords can be abbreviated Commands do not allow manipulation of values in the database Runs on a browser Centrally loaded, does not have to be implemented on each machine SQL Statements vs. iSQL*Plus Commands SQL statements iSQL*Plus commands

  11. Oracle Naming Rules Table names and column names: • Must begin with a letter • Must be 1–30 characters long • Must contain only A–Z, a–z, 0–9, _, $, and # • Must not duplicate the name of another object owned by the same user • Must not be an Oracle server reserved word

  12. Question Which of the following is not valid table name? • Test_number • P$$#_loc • 1_copy_of_emp • Flop_Test_3

  13. SQL Data Types I • Character strings of fixed or varying length • CHAR(n): fixed length string of length n, up to 2000 bytes • VARCHAR2(n): string of UP to n characters, up to 4000 bytes • Numeric Data • Number [(precision[,mantissa])] • Precision (# digits in number) from 1…38 digits • Mantissa (# digits to right of decimal point) from 0…38 digits,

  14. SQL Data Types II • Date and Time • Default DATE: ‘DD-MON-YY’ • TIME ‘HH:MM:SS’ • 7 bytes in length • Also recognized • ROWID • BLOB • … See the Data Types List

  15. Data Type List Data Type Description VARCHAR2(size) Variable-length character data CHAR(size) Fixed-length character data NUMBER(p,s) Variable-length numeric data DATE Date and time values LONG Variable-length character data up to 2 gigabytes CLOB Character data up to 4 gigabytes RAW and LONG RAW Raw binary data BLOB Binary data up to 4 gigabytes BFILE Binary data stored in an external file; up to 4 gigabytes ROWID A 64 base number system representing the unique address of a row in its table.

  16. CREATE TABLE department (departmentno NUMBER(2), dname VARCHAR2(14), loc VARCHAR2(13)); Table created. Creating and Deleting Tables • Simple Table Declaration: CREATE TABLE • Name of the relation and parenthesized list of attribute names and their types • Table Deletion: DROP TABLE <TABLENAME>

  17. The ALTER TABLE Statement • Use the ALTER TABLE statement to add, modify, or drop columns ALTER TABLE table ADD (column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table MODIFY (column datatype [DEFAULT expr] [, column datatype]...); ALTER TABLE table DROP (column);

  18. Examples of ALTER TABLE ALTER TABLE department ADD (job_id VARCHAR2(9)); Table altered. ALTER TABLE department MODIFY (last_name VARCHAR2(30)); Table altered. ALTER TABLE department DROP COLUMN job_id; Table altered.

  19. CREATE TABLE department (departmentno NUMBER(2)NOT NULL, dname VARCHAR2(14), loc VARCHAR2(13)); Table created. Required Fields • A null value is unavailable, unassigned, unknown, or inapplicable, is not the same as zero or a blank space INSERT INTO department VALUES (100, 'Finance', NULL);

  20. Default Values • Often, do not have values for all components of a table • Any place where we declare attribute and its type, may use DEFAULT keyword followed by appropriate value • E.g.: • in CREATE TABLE statement • loc VARCHAR2(13) DEFAULT ‘?’, • ALTER TABLE department ADD phone CHAR(16) DEFAULT ‘unlisted’;

  21. 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 RENAME department TO detail_department; Table renamed.

  22. 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. TRUNCATE TABLE detail_department; Table truncated.

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

  24. 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 INTO department(department_id, department_name, manager_id, location_id) VALUES (70, 'Public Relations', 100, 1700); 1 row created.

  25. Inserting Rows with Null Values • Implicit method: Omit the column from the column list. INSERT INTO department (department_id, department_name ) VALUES (30, 'Purchasing'); 1 row created. • Explicit method: Specify the NULL keyword in the VALUES clause. INSERT INTO department VALUES (100, 'Finance', NULL, NULL); 1 row created.

  26. The UPDATE Statement Syntax • Modify existing rows with the UPDATE statement. • Update more than one row at a time, if required. UPDATE table SET column = value [, column = value, ...] [WHERE condition];

  27. Updating Rows in a Table • Specific row or rows are modified if you specify the WHERE clause. • All rows in the table are modified if you omit the WHERE clause. UPDATE employees SET department_id = 70 WHERE employee_id = 113; 1 row updated. UPDATE copy_emp SET department_id = 110; 22 rows updated.

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

  29. Deleting Rows from a Table • Specific rows are deleted if you specify the WHERE clause. • All rows in the table are deleted if you omit the WHERE clause. DELETE FROM department WHERE department_name = 'Finance'; 1 row deleted. DELETE FROM copy_emp; 22 rows deleted.

  30. Projection Selection Capabilities of SQL SELECT Statements Table 1 Table 1 Join Table 2 Table 1

  31. Basic SELECT Statement • SELECT identifies what columns • FROM identifies which table SELECT *|{[DISTINCT] column|expression [alias],...} FROM table [WHERE condition(s)] [ORDER BY {column, expr, alias} [ASC|DESC]];

  32. SELECT * FROM department; Selecting All Columns

  33. SELECT department_id, location_id FROM department; Projection Selecting Specific Columns

  34. SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90 ; Selection Selecting Specific Rows

  35. Writing SQL Statements • SQL statements are not case sensitive • SQL statements can be on one or more lines • Keywords cannot be abbreviated or splitacross lines • Clauses are usually placed on separate lines • Indents are used to enhance readability

  36. Operator + - * / Description Add Subtract Multiply Divide Arithmetic Expressions • Create expressions with number and date data by using arithmetic operators

  37. Using Arithmetic Operators SELECT last_name, salary, salary + 300 FROM employees; …

  38. _ / + * Operator Precedence • Multiplication and division take priority over addition and subtraction. • Operators of the same priority are evaluated from left to right. • Parentheses are used to force prioritized evaluation and to clarify statements.

  39. Operator Precedence SELECT last_name, salary, 12*salary+100 FROM employees; …

  40. Using Parentheses SELECT last_name, salary, 12*(salary+100) FROM employees; …

  41. SELECT last_name, 12*salary*commission_pct FROM employees; … … Null Values in Arithmetic Expressions Arithmetic expressions containing a null value evaluate to null

  42. Defining a Column Alias A column alias: • Renames a column heading • Is useful with calculations • Immediately follows the column name - there can also be the optional AS keyword between the column name and alias • Requires double quotation marks if it contains spaces or special characters or is case sensitive

  43. Using Column Aliases SELECT last_name AS name, commission_pct AS comm FROM employees; … SELECT last_name "Name", salary*12 AS "Annual Salary" FROM employees; …

  44. Concatenation Operator A concatenation operator: • Concatenates columns or character strings to other columns • Is represented by two vertical bars (||) • Creates a resultant column that is a character expression

  45. SELECT last_name||job_id AS "Employees" FROM employees; … Using the Concatenation Operator

  46. Literal Character Strings • A literal is a character, a number, or a date included in the SELECT list. • Date and character literal values must be enclosed within single quotation marks. • Each character string is output once for eachrow returned.

  47. SELECT last_name ||' is a '||job_id AS "Employee Details" FROM employees; … Using Literal Character Strings

  48. SELECT department_id FROM employees; … Duplicate Rows • The default display of queries is all rows, including duplicate rows

  49. Eliminating Duplicate Rows Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause. SELECT DISTINCT department_id FROM employees;

  50. SELECT *|{[DISTINCT] column|expression [alias],...} FROM table [WHERE condition(s)]; Limiting the Rows Selected • Restrict the rows returned by using the WHERE clause. • The WHERE clause follows the FROM clause.

More Related