Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s.

Similar presentations


Presentation on theme: "1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s."— Presentation transcript:

1 1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s sub language.

2 2 SQL….Con’t Consist of 3 Sub languages: – DDL (Data Definition Language). Create Table. Drop Table. Alter Table. – DML (Data Manipulation Language). Insert. Update. Delete. Select. – DCL (Data Control Language).

3 3 DDL (Data Definition Language) Available Data Types: – Integer/ Int. – Single / Float. – Counter / autoincrement – Text/ String / char. – Long char / memo. – Date / Time / Datetime. – Currency. – Long binary / OLEObject. – Boolean.

4 4 DML (Data Manipulation Language) DML in SQL is used to deal with the data only and it is not concerned with the structure of the database. Commands that will be considered in DML are: – Insert Into. – Delete. – Update. – Select.

5 5 DML (Insert Into) Insert Into command is used to insert data inside tables. Syntax is: Insert into table_name [(field_name,…)] values (value1, value2,….) - If you didn’t specify the field names, then you must include values for each field in the table.

6 6 DML (Insert Into) E.g. Given this table: (Books table) To Insert a new row inside this table, this command should be written: Insert Into Books (ISBN, Title, Price,pub_date) values (“1-000-0010-8”,”Access SQL”,150,”01/01/2005”) OR Insert Into Books values (“1-000-0010-8”,”Access SQL”,150,”01/01/2005”) Pub_datePriceTitleISBN

7 7 DML (Insert Into) In the previous example, if specific fields need to be added within the row (Not the entire record) so field names should be specified in the Insert Into Command. E.g. Insert a new record inside the books table by adding ISBN, Title and the price only. Insert Into Books (ISBN, Title, Price) values (“1-023-0010-8”,”Database Systems”,200)

8 8 DML (Delete) Delete command is used to delete records from tables. Syntax is : Delete from table_name where criteria; criteria : is used to determine which rows to delete.

9 9 DML (Delete) AddressStnameStno ADAli AhmadKIC-9870 ADSaeed Moh’dKIC-5643 DubNaser HasanKIC-2341 Delete from Students; This command will delete the whole records Students Table AddressStnameStno

10 10 DML (Delete) AddressStnameStno ADAli AhmadKIC-9870 ADSaeed Moh’dKIC-5643 DubNaser HasanKIC-2341 Students Table Delete from Students where Address = “AD”; This Command will delete all the students whose Address is AD. AddressStnameStno DubNaser HasanKIC-2341

11 11 DML (Update) Update command is used to update a specific data inside the tables. Syntax is : Update table_name set new_value_expression,… where criteria; where clause: is used to restrict updating a specific rows.

12 12 DML (Update) Pub_datePriceTitleISBN 2/1/2004120DataBase Design 1-002-032-1 3/6/2004150Networking1-412-002-6 1/8/2005110C++1-0302-046-7 Update Books set price = 200; This command without any criteria (condition) will update all the books’ price to 200 Books Table

13 13 All The prices is updated to 200 Pub_datePriceTitleISBN 2/1/2004200DataBase Design1-002-032-1 3/6/2004200Networking1-412-002-6 1/8/2005200C++1-0302-046-7 DML (Update)

14 14 DML (Update) Pub_datePriceTitleISBN 2/1/2004120DataBase Design 1-002-032-1 3/6/2004150Networking1-412-002-6 1/8/2005110C++1-0302-046-7 Update Books set price = 200 where ISBN=“1-002-032-1”; This command will update the price to 200 for the book whose ISBN = 1-002-032-1 Books Table

15 15 DML (Update) Pub_datePriceTitleISBN 2/1/2004200DataBase Design 1-002-032-1 3/6/2004150Networking1-412-002-6 1/8/2005110C++1-0302-046-7

16 16 Capabilities of SQL SELECT Statements Selection Projection Table 1 Table 2 Table 1 Join

17 17 Basic SELECT Statement SELECT*|{[DISTINCT] column|expression [alias],...} FROMtable; SELECT*|{[DISTINCT] column|expression [alias],...} FROMtable; SELECT identifies what columns FROM identifies which table

18 18 SELECT * FROM departments; Selecting All Columns

19 19 Selecting Specific Columns SELECT department_id, location_id FROM departments;

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

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

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

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

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

25 25 Limiting Rows Using a Selection “retrieve all employees in department 90” EMPLOYEES …

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

27 27 Using the WHERE Clause SELECT employee_id, last_name, job_id, department_id FROM employees WHERE department_id = 90 ;

28 28 Character Strings and Dates Character strings and date values are enclosed in double quotation marks. SELECT last_name, job_id, department_id FROM employees WHERE last_name = “Ahmad”;

29 29 Comparison Conditions Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to

30 30 SELECT last_name, salary FROM employees WHERE salary <= 3000; Using Comparison Conditions

31 31 Other Comparison Conditions Operator BETWEEN...AND... IN(set) LIKE IS NULL Meaning Between two values (inclusive), Match any of a list of values Match a character pattern Is a null value

32 32 Using the BETWEEN Condition Use the BETWEEN condition to display rows based on a range of values. SELECT last_name, salary FROM employees WHERE salary BETWEEN 2500 AND 3500; Lower limitUpper limit

33 33 SELECT employee_id, last_name, salary, manager_id FROM employees WHERE manager_id IN (100, 101, 201); Using the IN Condition Use the IN membership condition to test for values in a list.

34 34 Using the LIKE Condition Use the LIKE condition to perform wildcard searches of valid search string values. Search conditions can contain either literal characters or numbers: – * denotes zero or many characters. SELECTfirst_name FROM employees WHEREfirst_name LIKE 'S*';

35 35 Using the NULL Conditions Test for nulls with the IS NULL operator. SELECT last_name, manager_id FROM employees WHERE manager_id IS NULL;

36 36 Logical Conditions Operator AND OR NOT Meaning Returns TRUE if both component conditions are true Returns TRUE if either component condition is true Returns TRUE if the following condition is false

37 37 Using the AND Operator AND requires both conditions to be true. SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >=10000 AND job_id LIKE ‘*MAN*';

38 38 Using the OR Operator SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary >= 10000 OR job_id LIKE ‘*MAN*'; OR requires either conditions to be true.

39 39 SELECT last_name, job_id FROM employees WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP'); Using the NOT Operator

40 40 SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date ; ORDER BY Clause Sort rows with the ORDER BY clause – ASC: ascending order, default – DESC: descending order The ORDER BY clause comes last in the SELECT statement. …

41 41 Sorting in Descending Order SELECT last_name, job_id, department_id, hire_date FROM employees ORDER BY hire_date DESC ; …

42 42 The order of ORDER BY list is the order of sort. You can sort by a column that is not in the SELECT list. SELECT last_name, department_id, salary FROM employees ORDER BY department_id, salary DESC; Sorting by Multiple Columns …

43 43 Summary SELECT *|{[DISTINCT] column|expression [alias],...} FROM table [WHERE condition(s)] [ORDER BY {column, expr, alias} [ASC|DESC]]; Use the WHERE clause to restrict rows of output –Use the comparison conditions –Use the BETWEEN, IN, LIKE, and NULL conditions –Apply the logical AND, OR, and NOT operators Use the ORDER BY clause to sort rows of output

44 44 Obtaining Data from Multiple Tables EMPLOYEESDEPARTMENTS … …

45 45 Joining Tables Use a join to query data from more than one table. Write the join condition in the WHERE clause. Prefix the column name with the table name when the same column name appears in more than one table. SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2; SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2;

46 46 What is an Equijoin (Inner Join)? EMPLOYEES DEPARTMENTS Foreign keyPrimary key … …

47 47 SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id, departments.location_id FROM employees, departments WHERE employees.department_id = departments.department_id; Retrieving Records with Equijoins …

48 48 SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e, departments d WHERE e.department_id = d.department_id; Using Table Aliases Simplify queries by using table aliases. Improve performance by using table prefixes.

49 49 Joining More than Two Tables EMPLOYEESLOCATIONSDEPARTMENTS To join n tables together, you need a minimum of n-1 join conditions. For example, to join three tables, a minimum of two joins is required. …

50 50 Non-Equijoins EMPLOYEESJOB_GRADES Salary in the EMPLOYEES table must be between lowest salary and highest salary in the JOB_GRADES table. …

51 51 Retrieving Records with Non-Equijoins SELECT e.last_name, e.salary, j.grade_level FROM employees e, job_grades j WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal; …

52 52 What Are Group Functions? Group functions operate on sets of rows to give one result per group. EMPLOYEES The maximum salary in the EMPLOYEES table. …

53 53 Types of Group Functions AVG COUNT MAX MIN SUM

54 54 SELECT[column,] group_function(column),... FROMtable [WHEREcondition] [GROUP BYcolumn] [ORDER BYcolumn]; Group Functions Syntax

55 55 SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM employees WHERE job_id = ‘ Rep1'; Using the AVG and SUM Functions You can use AVG and SUM for numeric data.

56 56 Using the MIN and MAX Functions You can use MIN and MAX for any data type. SELECT MIN(hire_date), MAX(hire_date) FROM employees;

57 57 SELECT COUNT(*) FROM employees WHERE department_id = 50; Using the COUNT Function COUNT(*) returns the number of rows in a table.

58 58 Creating Groups of Data EMPLOYEES The average salary in EMPLOYEES table for each department. 4400 … 9500 3500 6400 10033

59 59 SELECTcolumn, group_function(column) FROMtable [WHEREcondition] [GROUP BYgroup_by_expression] [ORDER BYcolumn]; Creating Groups of Data: The GROUP BY Clause Syntax Divide rows in a table into smaller groups by using the GROUP BY clause.

60 60 SELECT department_id, AVG(salary) FROM employees GROUP BY department_id ; Using the GROUP BY Clause All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.

61 61 Grouping by More Than One Column EMPLOYEES “Add up the salaries in the EMPLOYEES table for each job, grouped by department. …

62 62 SELECT department_id, job_id, SUM(salary) FROM employees GROUP BY department_id, job_id ; Using the GROUP BY Clause on Multiple Columns

63 63 Illegal Queries Using Group Functions You cannot use the WHERE clause to restrict groups. You use the HAVING clause to restrict groups. You cannot use group functions in the WHERE clause. SELECT department_id, AVG(salary) FROM employees WHERE AVG(salary) > 8000 GROUP BY department_id; SELECT department_id, AVG(salary) FROM employees WHERE AVG(salary) > 8000 GROUP BY department_id; WHERE AVG(salary) > 8000 * ERROR at line 3: ORA-00934: group function is not allowed here WHERE AVG(salary) > 8000 * ERROR at line 3: ORA-00934: group function is not allowed here

64 64 SELECTcolumn, group_function FROMtable [WHEREcondition] [GROUP BYgroup_by_expression] [HAVINGgroup_condition] [ORDER BYcolumn]; Excluding Group Results: The HAVING Clause Use the HAVING clause to restrict groups: 1.Rows are grouped. 2.The group function is applied. 3.Groups matching the HAVING clause are displayed.

65 65 Using the HAVING Clause SELECT department_id, MAX(salary) FROM employees GROUP BY department_id HAVING MAX(salary)>10000 ;

66 66 SELECT job_id, SUM(salary) PAYROLL FROM employees WHERE job_id NOT LIKE '%REP%' GROUP BY job_id HAVING SUM(salary) > 13000 ORDER BY SUM(salary); Using the HAVING Clause

67 67 DDL…Cont’d Constraints on tables (Fields): – Unique. – Not Null. – Check. – Primary key. – Foreign key.

68 68 DDL (Creating Tables) Create table table_name (Column name1 DataType (size), Column name2 DataType (size),.. Multicolumn constraint );

69 69 DDL (Creating Tables) E.g. Create these two tables using SQL Language? Dept_tbl (Deptno, Dname, Location) Employees (eno, ename, DOB, salary, dno)

70 70 DDL (Creating Tables) Solu n : Create table Dept_tbl ( deptno Integer(2), dname text(10), location text(15), constraint dept_pk primary key (deptno)); Dept_tbl table: locationdnameDeptno

71 71 DDL (Creating Tables) Create table employees ( eno integer(4), ename text(20), DOB date, salary float (6,2), dno integer(2), constraint emp_pk primary key (eno), constraint emp_dept_fk foreign key (dno) references dept_tbl (deptno) on update cascade on delete cascade);

72 72 DDL (Dropping Tables) To drop ( delete) the structure of any table in SQL, this command is used: Drop table table_name (cascade / restrict) e.g. Drop table employees cascade.

73 73 DDL (Altering Tables) To add, modify, delete specific fields from an existing table, this command is used: Alter table table_name add column colname datatype (size) | drop column colname | add constraint …….. | drop constraint …….. | modify colname new_DataType;

74 74 DDL (Altering Tables) dnoSalaryDOBenameEno Employees table before modifying it : E.g. Modify the employees table as illustrated below: -Add 2 fields (Certification and Major). -Modify the (eno) field to accept numbers of 5 digits. -Modify the table so that it will not accept salaries < 2000.

75 75 DDL (Altering Tables) - Alter table employees add column major text (10); - Alter table employees add column certification text (5); - Alter table employees modify eno integer(5); - Alter table employees add constraint chk_sal check (salary >=2000);


Download ppt "1 SQL SQL (Structured Query Language) : is a database language that is used to create, modify and update database design and data. Good Example of DBMS’s."

Similar presentations


Ads by Google