1 sql sql (structured query language) : is a database language that is used to create, modify and...
TRANSCRIPT
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
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
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
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
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
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_date Price Title ISBN
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
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
DML (Delete)
Address Stname Stno
AD Ali Ahmad KIC-9870
AD Saeed Moh’d KIC-5643
Dub Naser Hasan KIC-2341
Delete from Students;
This command will delete the whole records
Students Table
Address Stname Stno
10
DML (Delete)
Address Stname Stno
AD Ali Ahmad KIC-9870
AD Saeed Moh’d KIC-5643
Dub Naser Hasan KIC-2341
Students Table
Delete from Students where Address = “AD;”
This Command will delete all the students whose Address is AD.
Address Stname Stno
Dub Naser Hasan KIC-2341
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
DML (Update)
Pub_date Price Title ISBN2/1/2004 120 DataBase
Design1-002-032-1
3/6/2004 150 Networking 1-412-002-6
1/8/2005 110 C++ 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
All The prices is updated to 200
Pub_date Price Title ISBN2/1/2004 200 DataBase Design 1-002-032-1
3/6/2004 200 Networking 1-412-002-6
1/8/2005 200 C++ 1-0302-046-7
DML (Update)
14
DML (Update)
Pub_date Price Title ISBN2/1/2004 120 DataBase
Design1-002-032-1
3/6/2004 150 Networking 1-412-002-6
1/8/2005 110 C++ 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
DML (Update)
Pub_date Price Title ISBN2/1/2004 200 DataBase
Design1-002-032-1
3/6/2004 150 Networking 1-412-002-6
1/8/2005 110 C++ 1-0302-046-7
17
Basic SELECT Statement
SELECT *|{[DISTINCT] column|expression [alias],...}FROM table;
SELECT *|{[DISTINCT] column|expression [alias],...}FROM table;
SELECT identifies what columns FROM identifies which table
20
Arithmetic Expressions
Create expressions with number and date data by using arithmetic operators.
Operator
+
-
*
/
Description
Add
Subtract
Multiply
Divide
23
Duplicate Rows
The default display of queries is all rows, including duplicate rows.
SELECT department_idFROM employees;
SELECT department_idFROM employees;
…
24
Eliminating Duplicate Rows
Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.
SELECT DISTINCT department_idFROM employees;
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],...}FROM table[WHERE condition(s)];
27
Using the WHERE Clause
SELECT employee_id, last_name, job_id, department_idFROM employeesWHERE department_id = 90 ;
28
Character Strings and Dates
Character strings and date values are enclosed in double quotation marks.
SELECT last_name, job_id, department_idFROM employeesWHERE last_name = “Ahmad”;
29
Comparison Conditions
Operator
=
>
>=
<
<=
<>
Meaning
Equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
Not equal to
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
Using the BETWEEN Condition
Use the BETWEEN condition to display rows based on a range of values.
SELECT last_name, salaryFROM employeesWHERE salary BETWEEN 2500 AND 3500;
Lower limit Upper limit
33
SELECT employee_id, last_name, salary, manager_idFROM employeesWHERE manager_id IN (100, 101, 201);
Using the IN Condition
Use the IN membership condition to test for values in a list.
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.
SELECT first_nameFROM employeesWHERE first_name LIKE 'S*';
35
Using the NULL Conditions
Test for nulls with the IS NULL operator.
SELECT last_name, manager_idFROM employeesWHERE manager_id IS NULL;
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
Using the AND Operator
AND requires both conditions to be true.
SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary >=10000AND job_id LIKE ‘*MAN*';
38
Using the OR Operator
SELECT employee_id, last_name, job_id, salaryFROM employeesWHERE salary >= 10000OR job_id LIKE ‘*MAN*';
OR requires either conditions to be true.
39
SELECT last_name, job_idFROM employeesWHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP');
Using the NOT Operator
40
SELECT last_name, job_id, department_id, hire_dateFROM employeesORDER 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
Sorting in Descending OrderSELECT last_name, job_id, department_id, hire_dateFROM employeesORDER BY hire_date DESC ;
…
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, salaryFROM employeesORDER BY department_id, salary DESC;
Sorting by Multiple Columns
…
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
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.
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;
47
SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id, departments.location_idFROM employees, departmentsWHERE employees.department_id = departments.department_id;
Retrieving Records with Equijoins
…
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
Joining More than Two TablesEMPLOYEES LOCATIONS DEPARTMENTS
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
Non-EquijoinsEMPLOYEES JOB_GRADES
Salary in the EMPLOYEES table must be between lowest salary and highest salary in the JOB_GRADEStable.
…
51
Retrieving Records with Non-EquijoinsSELECT e.last_name, e.salary, j.grade_levelFROM employees e, job_grades jWHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal;
…
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.
…
54
SELECT [column,] group_function(column), ...FROM table[WHERE condition][GROUP BY column][ORDER BY column];
Group Functions Syntax
55
SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary)FROM employeesWHERE job_id = ‘ Rep1';
Using the AVG and SUM Functions
You can use AVG and SUM for numeric data.
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
SELECT COUNT(*)FROM employeesWHERE department_id = 50;
Using the COUNT Function
COUNT(*) returns the number of rows in a table.
58
Creating Groups of Data
EMPLOYEES
The averagesalary
in EMPLOYEES
table for each
department.
4400
…
9500
3500
6400
10033
59
SELECT column, group_function(column)FROM table[WHERE condition][GROUP BY group_by_expression][ORDER BY column];
Creating Groups of Data: The GROUP BY Clause Syntax
Divide rows in a table into smaller groups by using the
GROUP BY clause.
60
SELECT department_id, AVG(salary)FROM employeesGROUP 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
Grouping by More Than One Column EMPLOYEES
“Add up the salaries in
the EMPLOYEES table
for each job, grouped by department.
…
62
SELECT department_id, job_id, SUM(salary)FROM employeesGROUP BY department_id, job_id ;
Using the GROUP BY Clause on Multiple Columns
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 employeesWHERE AVG(salary) > 8000GROUP BY department_id;
SELECT department_id, AVG(salary)FROM employeesWHERE AVG(salary) > 8000GROUP 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
SELECT column, group_functionFROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column];
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
Using the HAVING Clause
SELECT department_id, MAX(salary)FROM employeesGROUP BY department_idHAVING MAX(salary)>10000 ;
66
SELECT job_id, SUM(salary) PAYROLLFROM employeesWHERE job_id NOT LIKE '%REP%'GROUP BY job_idHAVING SUM(salary) > 13000ORDER BY SUM(salary);
Using the HAVING Clause
67
DDL…Cont’d
Constraints on tables (Fields):– Unique.– Not Null.– Check.– Primary key.– Foreign key.
68
DDL (Creating Tables)
Create table table_name
(Column name1 DataType (size),
Column name2 DataType (size),
.
.
Multicolumn constraint
);
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
DDL (Creating Tables)
Solun:Create table Dept_tbl (
deptno Integer(2),
dname text(10),
location text(15),
constraint dept_pk primary key (deptno));
Dept_tbl table:
location dname Deptno
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
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
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
DDL (Altering Tables)
dno Salary DOB ename Eno
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.