Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structured Query Language (SQL)

Similar presentations


Presentation on theme: "Structured Query Language (SQL)"— Presentation transcript:

1 Structured Query Language (SQL)

2 SQL Non-Procedural Structured Query Language.(4GL) Data Sub language.
Developed by IBM in the late 1970’s. In 1986, the ANSI made SQL as standard for all RDBMS. SQL does not support any programming language constructs like if…else OR do…while. SQL can be embedded in other programming languages like C, COBOL. Ltitl/Trng/Sql/V1.0

3 Features of SQL SQL is a non-procedural language.
SQL is used for all types of Database activities by all ranges of users including, System administrators. Database administrators. Application Programmers End users. Ltitl/Trng/Sql/V1.0

4 Data Definition Language (DDL) Data Manipulation Language (DML)
DBMS LANGUAGES Data Definition Language (DDL) Creating & Altering the structure of the database. Data Manipulation Language (DML) Insert, Update & Delete. Data Control Language (DCL) Controlling access to the database(Grant,Revoke) Ltitl/Trng/Sql/V1.0

5 Transaction Control … COMMIT, ROLLBACK
Data Retrieval … SELECT Ltitl/Trng/Sql/V1.0

6 DATA TYPES SUPPORTED IN SQL
Ltitl/Trng/Sql/V1.0

7 Tables used : Ltitl/Trng/Sql/V1.0

8 Data Retrieval Using SQL*PLUS
SQL*PLUS provides a query capability in the form of SELECT statement. One can view the current information in the tables by using this statement. Ltitl/Trng/Sql/V1.0

9 5 parts of basic SQL query
SELECT – list the columns you want … (more than one table, use table.field) FROM – list of tables used WHERE – selection/join criteria (opt) GROUP BY – how to summarize (opt) ORDER BY – sorting order (opt) Ltitl/Trng/Sql/V1.0

10 SELECT Command Displaying some OR all the columns from a table.
SELECT <col1, col2, … .> OR <*> FROM <table_name> ; Ltitl/Trng/Sql/V1.0

11 List the Department table. 1.
SELECT * FROM Dept ; Ltitl/Trng/Sql/V1.0

12 List the Department table. List the Department table
A Better Way! 2. List the Department table. List the Department table SELECT Deptcode, Deptname, Deptmanager, Deptbudget FROM Dept ; Ltitl/Trng/Sql/V1.0

13 SELECT Deptmanager, Deptname FROM Dept ;
Only Some Columns 3. List all department managers with the names of their department SELECT Deptmanager, Deptname FROM Dept ; Ltitl/Trng/Sql/V1.0

14 WHERE Predicate ( = ) 4. SELECT Empname, Deptcode FROM Emp
List all employees of the Accounts department. SELECT Empname, Deptcode FROM Emp WHERE Deptcode = ‘Acct’ ; Ltitl/Trng/Sql/V1.0

15 WHERE Predicate ( < )
5. List all officers. SELECT Empname, Gradecode FROM Emp WHERE Gradecode < 10 ; Ltitl/Trng/Sql/V1.0

16 Date Comparison 6. SELECT Empname, Birthdate FROM Emp
List all young employees. SELECT Empname, Birthdate FROM Emp WHERE Birthdate > ‘01-Jan-70’ ; Ltitl/Trng/Sql/V1.0

17 SELECT DISTINCT deptcode FROM emp ;
Eliminating Redundant Data DISTINCT is an argument that provides a way for you to eliminate duplicate values. e.g. SELECT DISTINCT deptcode FROM emp ; Ltitl/Trng/Sql/V1.0

18 Use of Boolean operators
1. SELECT * FROM emp WHERE Basicpay >= AND Basicpay <= 4500 ; 2. SELECT * FROM emp WHERE Desigcode = ‘Engg’ OR Basicpay > 3000 ; 3. SELECT empname FROM emp WHERE NOT deptcode = ‘Acct’ ; Ltitl/Trng/Sql/V1.0

19 In Operator IN operator can be used to select rows that match one of the values included in the list. 1. SELECT empname FROM emp WHERE deptcode IN(‘Acct’, ‘Pers’) ; 2. SELECT empname FROM emp WHERE deptcode NOT IN(‘Acct’, ‘Pers’) ; Ltitl/Trng/Sql/V1.0

20 Between construct Defines a range that values must fall into make the predicate true. List all middle level staff List all middle level staff SELECT Empname, Gradecode FROM Emp WHERE Gradecode BETWEEN 10 AND 15; Ltitl/Trng/Sql/V1.0

21 Like construct Used for pattern searching.
Pattern consists of characters to be matched & the wildcard’ characters. WildCard chars. Matches _ (under score) Any single character. % Any sequence of zero or more characters. Ltitl/Trng/Sql/V1.0

22 Like construct List all employees with UMA in their names
SELECT Empname FROM Emp WHERE Upper(Empname) LIKE ‘%UMA%’ ; Ltitl/Trng/Sql/V1.0

23 Null values List the employees who have not been assigned to any supervisor SELECT Empname, Supcode FROM Emp WHERE Supcode IS NULL ; Ltitl/Trng/Sql/V1.0

24 Compound Predicate - Interval
List the female employees who have just completed 5 years SELECT Empname, Sex, Joindate FROM Emp WHERE Sex = “F” AND Joindate BETWEEN(sysdate - 5*365) AND (sysdate - 6*365) ; Ltitl/Trng/Sql/V1.0

25 Predicate using OR List employees who are either 50 years or more or have more than 20 years experience. SELECT EmpName FROM Emp WHERE BirthDate < (sysdate - 50*365) OR JoinDate < (sysdate - 20*365) ; Ltitl/Trng/Sql/V1.0

26 Parentheses in Predicate
List foremen who are either 50 years or more or have more than 20 years experience. SELECT EmpName FROM Emp WHERE DesigCode = ‘FRMN’ AND ((BirthDate < (sysdate - 50*365) OR JoinDate < (sysdate - 20*365)); Ltitl/Trng/Sql/V1.0

27 Expressions in SELECT List
List 1% of take-home pay of all employees. SELECT Empcode, (Basic + Allow -Deduct ) * 0.01 FROM Salary WHERE SalMonth = ‘1-Mar-97’; Ltitl/Trng/Sql/V1.0

28 EMPCODE (BASIC+ALLOW-DEDUCT) * 0.01
17 rows selected. Ltitl/Trng/Sql/V1.0

29 Aliasing List the present age of all the employees. SELECT EmpName,
TRUNC(SYSDATE - BirthDate) / 365) AGE FROM Emp ; Ltitl/Trng/Sql/V1.0

30 Ltitl/Trng/Sql/V1.0

31 For getting the resultant rows in a specified order.
Order By For getting the resultant rows in a specified order. Ascending order is default. List all employees ordered by age SELECT EmpName, TRUNC(SYSDATE - BirthDate)/365 AGE FROM Emp ORDER BY BirthDate ; Ltitl/Trng/Sql/V1.0

32 Ltitl/Trng/Sql/V1.0

33 Sorting Ascending / Descending
List middle level staff according to seniority List middle level staff according to seniority SELECT EmpName, GradeCode, GradeLevel FROM Emp WHERE GradeCode BETWEEN 10 AND 25 ORDER BY GradeCode, GradeLevel DESC ; Ltitl/Trng/Sql/V1.0

34 Ltitl/Trng/Sql/V1.0

35 Sorting by Result of Expression
List all according to age and seniority List middle level staff according to seniority SELECT EmpName, TRUNC(SYSDATE - BirthDate/365) AGE, GradeCode, GradeLevel FROM Emp ORDER BY 2 DESC, GradeCode, GradeLevel DESC ; Ltitl/Trng/Sql/V1.0

36 Ltitl/Trng/Sql/V1.0

37 AGGREGATE Functions Act on a group or set of rows and return one row of summary information per set. SUM Computes the total value of the group. AVG Computes the average value of the group. MIN Computes the minimum value of the group. MAX Computes the maximum value of the group COUNT Counts the no. of NON-NULL values for the specified group. COUNT(*) Counts the no. of rows including those having NULLvalues for the given condition. Ltitl/Trng/Sql/V1.0

38 AGGREGATE Functions Count employees reporting to Singh.
SELECT COUNT(*) FROM Emp WHERE Supcode = ‘7844’ ; Ltitl/Trng/Sql/V1.0

39 GROUP BY - Aggregate Functions
The grouping of rows is achieved by using the GROUP BY clause. Allows you to define a subset of the values in a particular field in terms of another field, and apply an aggregate functions to the subset. Enables you to combine fields and aggregate functions in a single SELECT statement Ltitl/Trng/Sql/V1.0

40 GROUP BY - Aggregate Functions
List the number of staff reporting to each supervisor. SELECT Supcode, COUNT(*) FROM Emp GROUP BY Supcode ORDER BY Supcode ; Ltitl/Trng/Sql/V1.0

41 GROUP BY - Sum SELECT EmpCode, SUM(Basic + Allow - Deduct) PAY
List the total take-home pay during for all employees. SELECT EmpCode, SUM(Basic + Allow - Deduct) PAY FROM Salary WHERE SalMonth BETWEEN ‘1-Apr-96’ AND ‘31-Mar-97’ GROUP BY EmpCode ORDER BY EmpCode ; Ltitl/Trng/Sql/V1.0

42 Ltitl/Trng/Sql/V1.0

43 GROUP BY - Max & Min List the maximum & minimum salaries in grades.
SELECT GradeCode, MAX(Basic), MIN(Basic) FROM Grade GROUP BY GradeCode ORDER BY GradeCode ; Ltitl/Trng/Sql/V1.0

44 Ltitl/Trng/Sql/V1.0

45 HAVING Defines criteria used to eliminate certain groups from the output, just as the WHERE clause does for individual rows. HAVING can take only arguments that have a single value per output group. Ltitl/Trng/Sql/V1.0

46 HAVING List the number of staff reporting to each supervisor
having more than 3 people working under them. SELECT SupCode, COUNT(*) FROM Emp GROUP BY SupCode HAVING COUNT(*) > 3 ORDER BY SupCode ; Ltitl/Trng/Sql/V1.0

47 Where - Group By - Having
List the total take-home pay during for all employees getting a total take-home-pay < Rs SELECT EmpCode, SUM(Basic + Allow - Deduct) PAY FROM Salary WHERE SalMonth BETWEEN ‘1-Apr-96’ AND ‘31-Mar-97’ GROUP BY EmpCode HAVING SUM(Basic + Allow - Deduct) ORDER BY EmpCode ; Ltitl/Trng/Sql/V1.0

48 Where - Group By - Having
List the maximum and minimum basic salary in each grade for grades with start < Rs. 4000 SELECT GradeCode, MAX(Basic), MIN(Basic) FROM Grade GROUP BY GradeCode HAVING MIN(Basic) < 4000 ORDER BY GradeCode ; Ltitl/Trng/Sql/V1.0

49 Joining Table The process of forming rows from two or more tables by comparing the contents of related cloumns is called ‘Joining Tables’. Joins are the foundation of multi-table query processing in SQL. Syntax : SELECT <col1,col2,...> FROM <table_name> WHERE <logical expr.> ; Ltitl/Trng/Sql/V1.0

50 Joining Table - Types of Joins
Equi-Join Cartesian Join Self Join Outer Join Ltitl/Trng/Sql/V1.0

51 Natural Join - Equi-Join
Check the basic salary of all employees. SELECT EmpCode, EmpName, Grade.Basic,Emp.Basic FROM EMP, GRADE WHERE Emp.GradeCode = Grade.GradeCode AND Emp.GradeLevel = Grade.GradeLevel ; Ltitl/Trng/Sql/V1.0

52 Self Join Match and retrieve rows that have a matching value in
different cloumns of the same table. List employees along with the names of their supervisors SELECT E.Empname, S.EmpName Supervisor, FROM EMP E, EMP S WHERE E.SupCode = S.EmpCode ; Ltitl/Trng/Sql/V1.0

53 Cartesian Join A cartesian product matches every row of one table to every row of the other table. e.g. SELECT EmpName, DeptName FROM EMP, DEPT WHERE DesigCode = ‘clerk’ ; Ltitl/Trng/Sql/V1.0

54 Outer Join Retrieving selected rows from one table that don’t match rows in the other table. To find department names & the employees in them, as well as those departments which do not have employees in them SELECT DeptName, EmpName FROM EMP, DEPT WHERE EMP.DeptCode(+) = DEPT.DeptCode ; Ltitl/Trng/Sql/V1.0

55 SELECT SupCode, COUNT(*) FROM EMP WHERE GradeCode < 10
List the number of officers reporting to each supervisors having more than 3 people working under them. SELECT SupCode, COUNT(*) FROM EMP WHERE GradeCode < 10 GROUP BY SupCode HAVING COUNT(*) > 3 ; Ltitl/Trng/Sql/V1.0

56 Nested Queries ( Subquery )
Placing a query inside the predicate of another query, and using the inner query’s output in the predicate’s true or false condition. Subqueries divided into two groups. 1. Single-Row Subquery Returns only one value to the outer query. 2. Multi-Row Subquery Returns multiple values to the outer query Ltitl/Trng/Sql/V1.0

57 SELECT EmpName FROM EMP WHERE DesigCode = (SELECT DesigCode FROM EMP
Single-Row Subquery To find out all the employees who have the same job as ‘scott’. SELECT EmpName FROM EMP WHERE DesigCode = (SELECT DesigCode FROM EMP WHERE EmpName = ‘scott’) ; Ltitl/Trng/Sql/V1.0

58 WHERE DeptCode = (SELECT DeptCode FROM DEPT WHERE DeptName = ‘sales’);
Single-Row Subquery To list the names of all employees working in sales dept; assuming that dept no. of sales dept is not known. SELECT EmpName FROM EMP WHERE DeptCode = (SELECT DeptCode FROM DEPT WHERE DeptName = ‘sales’); Ltitl/Trng/Sql/V1.0

59 SELECT EmpName, DesigCode, Salary FROM EMP WHERE DeptCode = 20 AND
Multi-Row Subquery List the name, job and salary of people in dept 20 who have the same job as people in dept. 30. SELECT EmpName, DesigCode, Salary FROM EMP WHERE DeptCode = 20 AND DesigCode IN (SELECT DesigCode FROM EMP WHERE DeptCode = 30) ; Ltitl/Trng/Sql/V1.0

60 Multiple levels of Nesting
Find name, job and salary of people in dept 20 who have the same job as people in the sales dept. SELECT EmpName, DesigCode, Salary FROM EMP WHERE DeptCode = 20 AND DesigCode IN (SELECT DesigCode FROM EMP WHERE DeptCode = (SELECT DeptCode FROM DEPT WHERE DeptName = ‘sales’) ; Ltitl/Trng/Sql/V1.0

61 Subqueries returning Multiple values
Find out who are the highest paid employees in each dept. SELECT DeptCode, EmpName, Salary FROM EMP WHERE (DeptCode, Salary) IN (SELECT DeptCode, MAX(Salary) GROUP BY DeptCode) ; Ltitl/Trng/Sql/V1.0

62 EXISTS Operator output or not.
Used to base a predicate on whether a subquery produces output or not. EXISTS is an operator that produces a True or False value. It takes a subquery as an argument and evaluates to True if it produces any output or false if it does not. Ltitl/Trng/Sql/V1.0

63 e.g. To list data from customer table if and only if
one or more of the customers in the customers table are located in ‘San Jose’. Select cnum, cname, city From customer Where Exists (Select * From customer Where city = ‘San Jose’) ; Ltitl/Trng/Sql/V1.0

64 EXISTS Operator SELECT * FROM DEPT A WHERE EXISTS (SELECT * FROM EMP B
To list all department details from Dept. table which has atleast one employee. SELECT * FROM DEPT A WHERE EXISTS (SELECT * FROM EMP B WHERE B.DeptCode = A.DeptCode) ; Ltitl/Trng/Sql/V1.0

65 insert into tablename [(col1, col2, …)] values (exp1, exp2, …);
Inserting rows of data insert into tablename [(col1, col2, …)] values (exp1, exp2, …); If the col names are not listed, the data is assigned to all cols in order To insert only into certain cols, name them … cols not named are given null values Ltitl/Trng/Sql/V1.0

66 INSERT one complete row
INSERT INTO HISTORY VALUES (‘7369’, ‘01-Aug-96’, ‘SLMN’, ‘12’, 5000) ; Ltitl/Trng/Sql/V1.0

67 INSERT one partial row INSERT INTO EMP (EmpCode, EmpName, Basic)
Employ Hussein as a temporary employee. INSERT INTO EMP (EmpCode, EmpName, Basic) VALUES (‘9123’, ‘Hussein’, 250) ; Ltitl/Trng/Sql/V1.0

68 INSERT thru Subquery INSERT INTO SALARY
Update the SALARY table for the month. INSERT INTO SALARY SELECT EmpCode, trunc(Sysdate, mon), Basic, Basic*1.5, Basic*0.3 FROM EMP ; Ltitl/Trng/Sql/V1.0

69 Delete one row DELETE FROM EMP WHERE EmpCode = ‘7934’ ;
Delete employee record of Kaul. DELETE FROM EMP WHERE EmpCode = ‘7934’ ; Ltitl/Trng/Sql/V1.0

70 Bulk Delete DELETE FROM EMP WHERE DeptCode = ‘FLNG’ ;
Delete all employee records of Filing Department. DELETE FROM EMP WHERE DeptCode = ‘FLNG’ ; Ltitl/Trng/Sql/V1.0

71 Delete entire Table DELETE FROM SALARY ;
Delete the entire SALARY Table. DELETE FROM SALARY ; Ltitl/Trng/Sql/V1.0

72 Update one Row UPDTAE EMP SET GradeCode = ‘4’, DesigCode = ‘MNGR’,
Promote Gupta as Manager (Exports) UPDTAE EMP SET GradeCode = ‘4’, DesigCode = ‘MNGR’, Basic = 15000 WHERE EmpCode = ‘7654’ ; Ltitl/Trng/Sql/V1.0

73 Bulk Update UPDTAE DEPT SET DeptBudget = DeptBudget * 1.25
Raise the budget by 25% for all the departments except Facilities department. UPDTAE DEPT SET DeptBudget = DeptBudget * 1.25 WHERE DeptCode != ‘FACL’ ; Ltitl/Trng/Sql/V1.0

74 CREATE TABLE tablename (colname datatype [default value] [colconstrt]
Creating a table with SQL CREATE TABLE tablename (colname datatype [default value] [colconstrt] … tblconstraint, …, tblconstraint) [TABLESPACE tablespacename]; Only one primary key per table (mult cols OK) Ltitl/Trng/Sql/V1.0

75 default 50 – use 50 if no value is given Column constraints:
Constraint examples default 50 – use 50 if no value is given Column constraints: …not null (default is to allow nulls) …check condition …unique …primary key …references tblname [colname] Ltitl/Trng/Sql/V1.0

76 (p is precision, s is scale) VARCHAR2(p) – variable length string
Common datatypes (p is precision, s is scale) VARCHAR2(p) – variable length string …… p can be 1 to 4000 NUMBER(p,s) - p is # of digits …… s is # of decimal digits (like Fortran) DATE time, many possible formats … from 1/1/4712 BC to 12/31/4712 AD Ltitl/Trng/Sql/V1.0

77 CHAR(p) – older fixed length format
… p from 1 to 255, pads with blanks LONG – variable length text string to 2G … use is limited in queries LOB – replacing LONG, up to 4G (video) …”Large Object Block” Ltitl/Trng/Sql/V1.0

78 DDL for Table Dept Create table dept
( Deptcode char(4) constraint dept_pk primary key, Deptname char(25) not null, Deptmanager char(6), Deptbudget number not null ); Ltitl/Trng/Sql/V1.0

79 DDL for Table Emp Create table emp
( Empcode char(6) constraint emp_pk primary key, Empname char(20) not null, Deptcode char(4) constraint emp_dept_rc references dept(deptcode) , Birthdate date not null, Joindate date not null, Sex char(1) not null check(sex in(‘M’, ‘F’)), Desigcode char(4) not null constraint emp_desig_rc references desig(desigcode) Ltitl/Trng/Sql/V1.0

80 Contd... Supcode char(6) constraint emp_sup_rc references emp(empcode), Gradecode number(2), Basic number(5)) ; Ltitl/Trng/Sql/V1.0

81 DDL for Table Grade Create table grade ( Gradecode number(2) not null,
Gradelevel number not null, Basic number(5) not null, constraint grade_pk primary key(Gradecode, Gradelevel) ; Ltitl/Trng/Sql/V1.0

82 … (ROLLBACK cannot restore this) DROP removes the table definition
To remove a table DROP TABLE tablename … (ROLLBACK cannot restore this) DROP removes the table definition DELETE just removes the rows it leaves the table Ltitl/Trng/Sql/V1.0

83 Alter table Best to get your tables correct the first time
But if alteration is needed, you can: … add a new column … change a column’s definition Ltitl/Trng/Sql/V1.0

84 alter table customers add (fax char(12),
Example adding new columns alter table customers add (fax char(12), ctype char(1) check(ctype in (‘I’,’B’))); Cannot add a new column as not null … it starts out all null (empty)! Ltitl/Trng/Sql/V1.0

85 Alter table customers modify ( street varchar2(50));
Example modifying a column Alter table customers modify ( street varchar2(50)); Can increase (not decrease) width Restrictions also exist on changes to: … datatypes and constraints (cur violated) Ltitl/Trng/Sql/V1.0

86 Views - Creation View can be used as if it is a table.
View is a logical table based on one or more tables. View can be used as if it is a table. View does not contain data of their own. Whenever a view is accessed, the query is evaluated. Thus view is dynamic. Any changes made in the view affect the tables on which the view is based. View helps to hide the ownership details of a table and complexity of query used to retrieve data, from the user. Ltitl/Trng/Sql/V1.0

87 Views - Creation Create a view for Employee-Age.
CREATE VIEW EMPAGE (EmpCode, Age) AS (SELECT EmpCode, TRUNC((SYSDATE - BirthDate)/365) FROM EMP) ; Ltitl/Trng/Sql/V1.0

88 Views - Creation Create a view for Employee-Pay.
CREATE VIEW EMPPAY (EmpCode, NetPay, SalMonth) AS (SELECT EmpCode, (Basic + Allow - Deduct), SalMonth FROM SALARY) ; Ltitl/Trng/Sql/V1.0

89 Use of Views List employees who are older than their supervisors.
SELECT E.EmpCode, EmpName FROM EMP E, EMPAGE A WHERE E.EmpCode = A.EmpCode AND age > (SELECT Age FROM EMPAGE WHERE E.SupCode = EmpCode ) ; Ltitl/Trng/Sql/V1.0

90 Commit Makes permanent all changes made since last Commit or since the beginning of the user’s session. Syntax : COMMIT [work] ; work - is optional & only provided for readability. Ltitl/Trng/Sql/V1.0

91 RollBack Syntax : ROLLBACK [work] ;
RollBack undoes all the changes that has been done since the last commit or last Rollback or the named savepoint. Syntax : ROLLBACK [work] ; ROLLBACK TO Savepoint <savepoint_name> ; Ltitl/Trng/Sql/V1.0

92 Savepoint Savepoint <savepoint_name> ;
Savepoint helps in breaking a transaction into parts. Useful if only a part of changes made are to be discarded. If the name of an existing savepoint is reused, the old savepoint is erased. Commit or Rollback without any parameters will erase all savepoints. Rollback To Savepoint will undo all changes made after the Savepoint. Ltitl/Trng/Sql/V1.0


Download ppt "Structured Query Language (SQL)"

Similar presentations


Ads by Google