Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL – Structured Query Language

Similar presentations


Presentation on theme: "SQL – Structured Query Language"— Presentation transcript:

1 SQL – Structured Query Language

2 Relational Database Operators
Relational algebra determines table manipulations Key operators SELECT PROJECT JOIN Other operators UNION INTERSECT DIFFERENCE PRODUCT DIVIDE

3 Union Combines all rows Figure 2.5

4 Intersect Yields rows that appear in both tables Figure 2.6

5 Difference Yields rows not found in other tables Figure 2.7

6 Product Yields all possible pairs from two tables Figure 2.8

7 Select Yields a subset of rows based on specified criterion Figure 2.9

8 Project Yields all values for selected attributes Figure 2.10

9 Join Information from two or more tables is combined Figure 2.11

10 Natural Join Process Links tables by selecting rows with common values in common attribute(s) Three-stage process Product creates one table Select yields appropriate rows Project yields single copy of each attribute to eliminate duplicate columns

11 Other Joins EquiJOIN Links tables based on equality condition that compares specified columns of tables Does not eliminate duplicate columns Join criteria must be explicitly defined Theta JOIN EquiJOIN that compares specified columns of each table using operator other than equality one Outer JOIN Matched pairs are retained Unmatched values in other tables left null Right and left

12 Divide Requires user of single-column table and two-column table
Figure 2.17

13 Data Dictionary and System Catalog
Provides detailed account of all tables found within database Metadata Attribute names and characteristics System catalog Detailed data dictionary System-created database Stores database characteristics and contents Tables can be queried just like any other tables Automatically produces database documentation

14 Introduction to SQL Ideal database language
Create database and table structures Perform basic data management chores (add, delete, and modify) Perform complex queries to transform data into useful information SQL is the ideal DB language Data definition language (DDL) Data manipulation language (DML)

15 DDL vs. DML examples Name DDL: Data Definition Language
DML: Date Manipulation Language Purpose Defines Structure of Database and Database Objects Manipulates the Data housed in the tables Add Create table: creates a new table Insert Into: adds a new record to a table Change Alter table: modifies the tables structure (add a column, change a datatype, add constraint, etc.) Update: changes the values of an attribute in a record Remove Drop table: deletes the table from the database Delete: deletes a record from a table

16 Most Common Data Types Data Type Data Type Description CHAR(n)
fixed length column can contain any printable characters. If the data entered into CHAR field < length of field, field is padded with spaces. maximum length of CHAR column = 200. e.g: a state abbreviation - CHAR(2) since it is always 2 characters long. VARCHAR2(n) variable length column with a fixed length. If the length of the data is less than the maximum length of the field, then the field is not padded with spaces. maximum length of the column = 2000. e.g: a customer’s first name - VARCHAR2(35) since name length is variable. NUMBER Integer and real values occupying up to 40 spaces. INTEGER Same as number, but no decimals. DATE contains a date and time between the 1st of January 4712 BC to the 31st of December 4712 AD. standard date format: DD-MMM-YY (i.e. 01-JAN-99) Any other format will require input mask.

17 Creating Table Structure
CREATE TABLE <table name> (<attribute1 name and attribute1 characteristics, attribute2 name and attribute2 characteristics, attribute3 name and attribute3 characteristics, primary key designation, foreign key designation and foreign key requirement>); Null vs. Not Null (can the field be left blank when data entered NOTE: null <> 0 Check constraints – show acceptable values for attribute and/or default value. Data types and size Column Names

18 Drop – table or column Delete table from database:
Drop table <tablename> cascade constraints e.g. drop table student cascade constaints Delete column from database Alter table <tablename> drop column <column name> e.g. alter table student drop column student_lastname

19 Using Domains Domain is set of permissible values for a column
Definition requires: Name Data type Default value Domain constraint or condition CREATE DOMAIN <domain_name> AS DATA_TYPE [DEFAULT <default_value>] [CHECK (<condition>)]

20 SQL Integrity Constraints and Data Anomolies
Entity integrity - enforced automatically with PRIMARY KEY constraint Referential integrity - enforced FOREIGN KEY constraint Other specifications to ensure conditions met: ON DELETE RESTRICT ON UPDATE CASCADE

21 Data Anomalies, Redundacy, and constraints
Modification Insertion Deletion ON UPDATE CASCADE PRIMARY KEY constraint ON DELETE RESTRICT

22 Alter, Add, and Modify ALTER - changes table structure
ADD - adds column MODIFY - changes column characteristics ALTER TABLE <table name> ADD (<column name> <new column characteristics>); ALTER TABLE <table name> MODIFY (<column name> <new column characteristics>);

23 Data Manipulation Commands
Common SQL DML Commands Table 5.3

24 Enters data into a table
Data Entry and Saving Enters data into a table Saves changes to disk INSERT INTO <table name> VALUES (attribute 1 value, attribute 2 value, … etc.); COMMIT <table names> ;

25 Listing Table Contents and Other Commands
Allows table contents to be listed UPDATE command makes data entry corrections ROLLBACK command restores database back to previous condition if COMMIT hasn’t been used DELETE command removes table row SELECT <attribute names> FROM <table names>;

26 Queries Creating partial listings of table contents
SELECT <column(s)> FROM <table name> WHERE <conditions>; Table 5.4 Mathematical Operators

27 Examples Mathematical operators
Mathematical operators on character attributes Mathematical operators on dates SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE FROM PRODUCT WHERE V_CODE <> 21344; SELECT P_CODE,P_DESCRIPT,P_ONHAND,P_MIN,P_PRICE FROM PRODUCT WHERE P_CODE < ‘1558-QWI’; SELECT P_DESCRIPT,P_ONHAND,P_MIN,P_PRICE,PINDATE FROM PRODUCT WHERE P_INDATE >= ‘01/20/2002’;

28 Computed Columns New columns can be created through valid computations or formulas Formulas may contain mathematical operators May contain attributes of any tables specified in FROM clause Alias is alternate name given to table or column in SQL statement SELECT P_DESCRIPT,P_ONHAND,P_PRICE,P_ONHAND*P_PRICE AS TOTVALUE FROM PRODUCT;

29 Operators SELECT * FROM PRODUCT WHERE V_CODE = OR V_CODE = 24288; Logical: AND, OR, NOT Rules of precedence Conditions within parenthesis executed first Boolean algebra Special BETWEEN - defines limits IS NULL - checks for nulls LIKE - checks for similar string IN - checks for value in a set EXISTS - opposite of IS NULL

30 Drop column and update Dropping a column
Update (add new data to a column) ALTER TABLE VENDOR DROP COLUMN V_ORDER; UPDATE PRODUCT SET P_SALECODE = ‘2’ WHERE P_CODE = ‘1546-QQ2’; Table 5.5

31 Arithmetic Operators – Rules of Precedence
Arithmetic operators and rules of precedence Table 5.5

32 Advanced Data Management Commands (con’t.)
Copying parts of tables Deleting a table from database Primary and foreign key designation INSERT INTO <receiving table> <receiving table’s column names> SELECT <column names of the columns to be copied> FROM <contributing table name>; DROP TABLE PART; ALTER TABLE LINE ADD PRIMARY KEY (INV_NUMBER, LINE_NUMBER) ADD FOREIGN KEY (INV_NUMBER) REFERENCES INVOICE ADD FOREIGN KEY (PROD_CODE) REFERENCES PRODUCT;

33 Aggregate Function Operations Count, Max and Min
SELECT COUNT(DISTINCT V_CODE) FROM PRODUCT; SELECT COUNT(DISTINCT V_CODE) FROM PRODUCT WHERE P_PRICE <= 10.00; SELECT MIN(P_PRICE) FROM PRODUCT; SELECT P_CODE, P_DESCRIPT, P_PRICE FROM PRODUCT WHERE P_PRICE = MAX(P_PRICE);

34 Aggregate Function Operaters Sum/ Avg
SELECT SUM(P_ONHAND * P_PRICE) FROM PRODUCT; SELECT P_DESCRIPT, P_ONHAND, P_PRICE, V_CODE FROM PRODUCT WHERE P_PRICE > (SELECT AVG(P_PRICE) FROM PRODUCT) ORDER BY P_PRICE DESC;

35 Order by ORDER BY <attributes> ORDER BY <attributes> DESC
Ordering a listing Results ascending by default Descending order uses DESC Cascading order sequence ORDER BY <attributes> ORDER BY <attributes> DESC ORDER BY <attribute 1, attribute 2, ...>

36 Distinct SELECT DISTINCT V_CODE FROM PRODUCT;
Listing unique values DISTINCT clause produces list of different values SELECT DISTINCT V_CODE FROM PRODUCT;

37 Group by/ Having Grouping data Creates frequency distributions
Only valid when used with SQL arithmetic functions HAVING clause operates like WHERE for grouping output SELECT P_SALECODE, MIN(P_PRICE) FROM PRODUCT_2 GROUP BY P_SALECODE; SELECT V_CODE,COUNT(DISTINCT(P_CODE)),AVG(P_PRICE) FROM PRODUCT_2 GROUP BY V_CODE HAVING AVG(P_PRICE) < 10;

38 Joins Joining database tables Data retrieved from more than one table
SELECT PRODUCT.P_DESCRIPT, PRODUCT.P_PRICE, VENDOR.V_NAME, VENDOR.V_CONTACT, VENDOR.V_AREACODE, VENDOR.V_PHONE FROM PRODUCT, VENDOR WHERE PRODUCT.V_CODE = VENDOR.V_CODE;


Download ppt "SQL – Structured Query Language"

Similar presentations


Ads by Google