Upload
bernice-bell
View
218
Download
6
Embed Size (px)
Citation preview
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 11
Structured Query Structured Query LanguageLanguage
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 22
SStructuredtructured Q Queryuery L Languageanguage: : IntroIntro
What is SQL?► Relational model’s standard language
• all RDBMS software support SQL• many software vendors have developed extensions to basic SQL
there are small differences across RDBMS implementations of SQL
► Non-procedural language• user specifies what must be done, not how it is to be done
SQL programmers do not need to know the step-by-step task execution details.
What can SQL do?► Create database & table structures► Perform data manipulation & data administration
• add, modify, delete, retrieve data• create tables, indexes, views
► Query the database to extract useful information Why SQL?
► de facto standard for RDB• ANSI SQL (1986, 1992, 1999)
► Relatively easy to learn (vocabulary of less than 100 words)
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 33
The SQL EnvironmentThe SQL Environment ODBC (Open Database Connectivity)
► A standard database access method• API for using SQL queries to access data
► Enables data access from any application regardless of DBMS• independent of programming languages, DBMS, and OS• both application and DBMS have to be ODBC-compliant
► Translates applications data queries into DBMS commands• a middle layer (database driver) between application and DBMS
Application
DBMSDatabase
SQL queries
ODBCdriver
DBMScommand
s
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 44
SQL: SQL: Command TypeCommand Type
Data Definition Language (DDL) commands► Create, alter and drop tables► Typically restricted to DB administrators
Data Manipulation Language (DML) commands► Update, insert, modify, and query the data► Core commands of SQL
Data Control Language (DCL) commands► Grant/revoke access privileges, store/remove transactions► Help the DB administrators to control the database
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 55
SQL: SQL: Creating/Deleting TablesCreating/Deleting Tables► CREATE TABLE table_name (
column_name column_characteristics, …,CONSTRAINT constraint_name PRIMARY KEY (column_name), FOREIGN KEY (column_name) REFERENCES table_name);
• define a new table and its columns• “1” side table in 1:M relationship (i.e. EMPLOYEE) should be created first• data types vary from RDBMS to RDBMS
CREATE TABLE tblPilot (Emp_Num INTEGER NOT NULL, Pil_Hrs NUMBER, Pil_License CHAR(25), Pil_Date DATE,CONSTRAINT index1 PRIMARY KEY(Emp_Num), FOREIGN KEY(Emp_Num) REFERENCES tblEmployee);
► DROP TABLE table_name;• DROP TABLE tblPilot;
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 66
SQL: SQL: Creating IndexesCreating Indexes
► CREATE INDEX index_name ON table_name(column_names)
• Create SQL indexes based on selected columns CREATE INDEX P_CODEX
ON PRODUCT(P_CODE); CREATE UNIQUE INDEX P_CODEX
ON PRODUCT(P_CODE); CREATE INDEX VENPRODX
ON PRODUCT(V_CODE, P_CODE);
► Indexes• Improve the efficiency of data search• Create indexes on fields used in search• DBMS automatically creates a unique index for primary key
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 77
SQL: SQL: Modifying Table DataModifying Table Data► INSERT INTO table_name VALUES (col1_value, col2_value, …);
• Insert a single row into table INSERT INTO tblEmployee VALUES (1, ‘Doe’, ‘John’, ‘M’);
INSERT INTO tblEmployee VALUES (2, ‘Dew’, ‘Jane’, NULL);INSERT INTO tblEmployee(Emp_Num, Emp_Fname) VALUES (3, ‘Jim’);
► INSERT INTO table_name SELECT column_names FROM table_name WHERE
condition;• Insert multiple rows into table
INSERT INTO tblEmployee (Emp_Num, Emp_Fname, Emp_Lname, Emp_Init) SELECT App_Hire, App_Fname, App_Lname, App_Init FROM tblApplicant WHERE App_Hire=4;
► UPDATE table_names SET column_name=value WHERE condition;• Change column values
UPDATE tblEMPLOYEE SET Emp_Lname=‘Dew’, Emp_Status=‘M’ WHERE Emp_Num=3;
► DELETE FROM table_name WHERE condition;• Delete table rows
DELETE FROM tblEmployee WHERE Emp_Num=3;
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 88
SQL: SQL: Altering TablesAltering Tables► ALTER TABLE table_name
ADD column_name column_characteristics;• Add column to a table
ALTER TABLE tblProduct ADD P_Salescode CHAR(1);
► ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY(column_name) REFERENCES table_name;
• Designate a foreign key to a table ALTER TABLE tblProduct
ADD CONSTRAINT pk1 FOREIGN KEY(SUP_Num) REFERENCES tblSupplier;
► ALTER TABLE table_name ALTER column_name column_characteristics;
• Change column characteristics ALTER TABLE tblProduct
ALTER P_Salescode CHAR(10);
► ALTER TABLE table_name DROP column_name;
• Drop column from a table ALTER TABLE tblProduct
DROP P_Salescode;
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 99
SQL: SQL: Copying Table DataCopying Table Data
1. Create the new table whose column characteristics match the original table
2. Copy desired table columns and rows into the new table3. Designate primary and foreign keys if needed
• CREATE TABLE tbRetiree ( Emp_Num INTEGER NOT NULL, Retire_Date DATE,CONSTRAINT pk1 PRIMARY KEY(Emp_Num));
INSERT INTO tblRetiree(Emp_Num, Retire_Date) SELECT (Emp_Num, Hire_Date+3650) FROM tblEmployee WHERE (Hire_Date + 3650) – Date() < 30;
ALTER TABLE tblRetiree ADD CONSTRAINT fk1 FOREIGN KEY (Emp_Num) REFERENCES tblEmployee;
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 1010
SQL: SQL: QueriesQueries
► SELECT column_names FROM table_name WHERE condition;
• Retrieve table rows that match the target criteria
• Examples
SELECT Emp_Num, Emp_Lname FROM tblEmployee;
SELECT * FROM tblEmployee WHERE Emp_Num=1;
SELECT P_Onhand*P_Price AS TotalValue FROM tblProduct WHERE P_Code=1;
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 1111
SQL: SQL: Where ClauseWhere Clause
Mathematical Operators► + - * / ^
Comparison Operators► = < <= > >= <> (!=)
Logical Operators► AND, OR, NOT
Special Operators► BETWEEN, IS NULL, LIKE, IN, EXISTS
Wild Cards► % (*) _ (?)
Precedence & Case Sensitivity► differs across DBMS/platform
• WHERE P_ID NOT 1234;• WHERE P_Price BETWEEN 50.00 AND 100.00;• WHERE Emp_Status IS NULL;• WHERE (Emp_Lname LIKE ‘Smith%’) AND (Emp_Status IN (‘M’,‘D’));• WHERE Emp_Status EXISTS;
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 1212
SQL: SQL: Aggregate FunctionsAggregate Functions► COUNT
• Number of rows containing not null values in the given column SELECT DISTINCT (V_code)
FROM tblProduct WHERE P_Price < 10.00;
► MIN/MAX• Minimum/maximum value in the given column
SELECT * FROM tblProduct WHERE P_Price = (SELECT MAX(P_Price) FROM tblProduct);
► SUM• Sum of all values for the given column
SELECT SUM(P_Onhand*P_Price) FROM tblProduct;
► AVG• Mean value of the given column
SELECT * FROM tblProduct WHERE P_Price > (SELECT AVG(P_Price) FROM tblProduct);
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 1313
SQL: SQL: Sorting & GroupingSorting & Grouping
► ORDER BY column_names DESC• Sort the list (result of SELECT) by column values• Must be the last clause in the command sequence
SELECT Emp_Lname, Emp_Fname, Emp_Init FROM tblEmployee ORDER BY Emp_Lname, Emp_Fname, Emp_Init;
► GROUP BY column_names HAVING condition;
• Aggregate column values by group column values• Must be used with aggregate function• HAVING condition is applied to the output of GROUP BY
SELECT SUM(P_Onhand*P_Price) FROM tblProduct GROUP BY V_Code HAVING AVG(P_Price) > 1;
► SELECT DISTINCT column_name FROM table_name;• List only the unique column values
SELECT DISTINCT V_code FROM tblProduct;
S511 Session 10, IU-SLISS511 Session 10, IU-SLIS 1414
SQL: SQL: Joining TablesJoining Tables
Natural Join► SELECT column_names
FROM table1_name INNER JOIN table2_name ON table1.column = table2.column;
SELECT tblProduct.P_Code, tblProduct.P_Price, tblVendor.V_Name FROM tblProduct INNER JOIN tblVendor ON tblProduct.V_Code = tblVendor.V_Code;
Left Outer Join► SELECT column_names
FROM table1_name LEFT JOIN table2_name ON table1.column = table2.column;
Right Outer Join► SELECT column_names
FROM table1_name RIGHT JOIN table2_name ON table1.column = table2.column;