Agenda
2
Company Confidential
Database Concepts Retrieving Data (Select statement) Restricting and Sorting Data Single-Row Functions Displaying Data from Multiple Tables Aggregating Data Using Group Functions Subqueries Manipulating Data Creating and Managing Tables Including Constraints Creating Views Controlling User Access Using SET Operators Practice Exercise
Database Concepts
Database Terminology
4
Company Confidential
Database Components
Character :
Basic unit of data, Can be a letter, number, or special symbol
Field :
A group of related characters Represents an attribute or characteristic of an entity Corresponds to a column in the physical database
Record :
A collection of fields for one specific entity Corresponds to a row in the physical
File :
A group of records about the same type of entity
5
Company Confidential
Components Example
6
Company Confidential
Database Example
7
Company Confidential
Data storage : Manage the physical structure of the database Security: Control user access and privileges Multiuser access: Manage concurrent data access Backup: Enable recovery options for database failures Data access language: Provide a language that allows database access Data integrity: Enable constraints or checks on data Data dictionary: Maintain information about database structure
8
Company Confidential
9
Company Confidential
Database Design
Systems Development Life Cycle (SDLC) Entity-Relationship Model (E-R Model) Normalization
10
Company Confidential
investigation Understanding the problem analysis Understanding the solution design Creating the logical and physical components implementation Placing completed system into
11
Company Confidential
13
Company Confidential
Relationships
The following relationships can be included in an E-R Model:
1) One-to-one
Each occurrence of data in one entity is represented by only one occurrence of data in the other entity Example: Each individual has just one Social Security Number (SSN) and each SSN is assigned to just one person
2) One-to-many
Each occurrence of data in one entity can be represented by many occurrences of the data in the other entity Example: A class has only one instructor, but each instructor can teach many classes
3) Many-to-many
Data can have multiple occurrences in both entities Example: A student can take many classes and each class is composed of many students Can not be included in the physical database
14
Company Confidential
15
Company Confidential
Primary Key
16
Company Confidential
Foreign Key
Primary Key
Database Normalization
Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process:
eliminating redundant data (for example, storing the same data in more than one table) ensuring data dependencies make sense (only storing related data in a table).
Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.
17
Company Confidential
Normalization Steps
1NF: Eliminate repeating groups, identify the primary key 2NF: Table is in 1NF and partial dependencies are eliminated 3NF: Table is in 2NF and transitive dependencies are eliminated
Relating Tables within the Database Once tables are normalized, certain tables are linked Tables are linked through a common field A common field is usually a primary key in one table and a foreign key in the other table
More than one column is required to uniquely identify a row Can lead to partial dependency - a column is only dependent on a portion of the primary key
18
Company Confidential
19
Company Confidential
20
Company Confidential
Already meet the requirements of both 1NF and 2NF Remove columns that are not fully dependent upon the primary key.
21
Company Confidential
22
Company Confidential
SQL Statements
23
Company Confidential
Summary
A DBMS is used to create and maintain a database A database is composed of a group of interrelated tables A file is a group of related records; a file is also called a table in the physical database A record is a group of related fields regarding one specific entity; a record is also called a row A record is considered unnormalized if it contains repeating groups A record is in first-normal form (1NF) if no repeating groups exist and it has a primary key Second-normal form (2NF) is achieved if the record is in 1NF and has no partial dependencies After a record is in 2NF and all transitive dependencies have been removed, then it is in third-normal form (3NF), which is generally sufficient for most databases
24
Company Confidential
Retrieving Data
(Select statement)
Select
26
Company Confidential
27
Company Confidential
28
Company Confidential
Exercise
Select all columns and all rows of a table Select specified columns Select distinct values for a particular column
29
Company Confidential
30
Company Confidential
Arithmetic Expressions
Create expressions with number and date data by using arithmetic operators.
Operator Precedence
Multiplication and division take priority over addition and subtraction. Operators of the same priority are evaluated from left to right. Parentheses are used to force prioritized evaluation and to clarify statements.
32
Company Confidential
33
Company Confidential
34
Company Confidential
35
Company Confidential
Concatenation Operator
A concatenation operator: Concatenates columns or character strings to other columns Is represented by two vertical bars (||) Creates a resultant column that is a character expression SELECT first_name||last_name AS "Employees" FROM employees;
36
Company Confidential
Displaying Table Structure DESC[RIBE] tablename Display all tables Select * from tab;
38
Company Confidential
The WHERE clause follows the FROM clause. WHERE restricts the query to rows that meet a condition condition is composed of column names, expressions, constants, and a comparison operator
40
Company Confidential
Comparison Conditions
42
Company Confidential
43
Company Confidential
WHERE salary BETWEEN 2500 AND 3500; WHERE manager_id IN (100, 101, 201); WHERE first_name LIKE _S%;
You can use the ESCAPE identifier to search for the actual % and _ symbols WHERE job_id LIKE %SA\_% ESCAPE \;
44
Company Confidential
Logical Conditions
45
Company Confidential
Rules of Precedence
46
Company Confidential
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. SELECT expr FROM table [WHERE condition(s)] [ORDER BY {column, expr} [ASC|DESC]];
47
Company Confidential
Single-Row Functions
SQL Functions
49
Company Confidential
50
Company Confidential
Single-Row Functions
51
Company Confidential
Character Functions
52
Company Confidential
Character Functions
53
Company Confidential
Character Functions
54
Company Confidential
55
Company Confidential
Character-Manipulation Functions
56
Company Confidential
Number Functions
ROUND: Rounds value to specified decimal
ROUND(45.926, 2) 45.93
57
Company Confidential
58
Company Confidential
General Functions
These functions work with any data type
NVL (expr1, expr2) NVL2 (expr1, expr2, expr3) NULLIF (expr1, expr2)
59
Company Confidential
NVL Function
Converts a null to an actual value.
Data types that can be used are date, character, and number. Data types must match:
NVL(commission_pct,0) NVL(hire_date,01-JAN-97) NVL(job_id,No Job Yet)
60
Company Confidential
NVL2 Function
NVL2(expr1, expr2, expr3)
In the syntax: expr1 is the source value or expression that may contain null expr2 is the value returned if expr1 is not null expr3 is the value returned if expr2 is null
NULLIF Function
NULLIF (expr1, expr2)
In the syntax: expr1 is the source value compared to expr2 expr2 is the source value compared with expr1. (If it is not equal to expr1, expr1 is returned.)
Conditional Expressions
Provide the use of IF-THEN-ELSE logic within a SQL statement Use two methods:
CASE expression DECODE function (specific to oracle)
63
Company Confidential
64
Company Confidential
65
Company Confidential
66
Company Confidential
SELECT last_name, job_id, salary, DECODE(job_id, IT_PROG, 1.10*salary, ST_CLERK, .15*salary, SA_REP, 1.20*salary, salary) REVISED_SALARY FROM employees;
67
Company Confidential
Cartesian Products
A Cartesian product is formed when:
A join condition is omitted A join condition is invalid All rows in the first table are joined to all rows in the second table
To avoid a Cartesian product, always include a valid join condition in a WHERE clause.
69
Company Confidential
Joining Tables
SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2; 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.
71
Company Confidential
Exercise
Join two tables and get the output from both the tables Add search condition
72
Company Confidential
73
Company Confidential
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;
74
Company Confidential
Non-Equijoins
75
Company Confidential
Outer Joins
76
Company Confidential
Self Joins
78
Company Confidential
Self Joins
SELECT worker.last_name || works for || manager.last_name FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id ;
79
Company Confidential
Exercise
1. The following SELECT statement executes successfully: SELECT last_name, job_id, salary AS Sal FROM employees;
True/False
2. The following SELECT statement executes successfully: SELECT * FROM job_grades; True/False 3. There are three coding errors in this statement. Can you identify them? SELECT employee_id, last_name sal x 12 ANNUAL SALARY FROM employees;
80
Company Confidential
Exercise.
4. Display the name and job title of all employees who do not have a manager. 5. Display the name, salary, and commission for all employees who earn commissions. Sort data in descending order of salary and commissions. 6. Display the last names of all employees where the third letter of the name is an a.
81
Company Confidential
83
Company Confidential
84
Company Confidential
Group Functions
85
Company Confidential
86
Company Confidential
87
Company Confidential
SELECT AVG(salary), MAX(salary), MIN(salary), SUM(salary) FROM employees WHERE job_id LIKE %REP%;
88
Company Confidential
89
Company Confidential
COUNT Function
The COUNT function has three formats:
COUNT(*) COUNT(expr) COUNT(DISTINCT expr)
COUNT(*) returns the number of rows in a table that satisfy the criteria of the SELECT statement, including duplicate rows and rows containing null values in any of the columns. If a WHERE clause is included in the SELECT statement, COUNT(*) returns the number of rows that satisfies the condition in the WHERE clause. COUNT(expr) returns the number of non-null values in the column identified by expr. COUNT(DISTINCT expr) returns the number of unique, non-null values in the column identified by expr.
90
Company Confidential
91
Company Confidential
92
Company Confidential
93
Company Confidential
94
Company Confidential
95
Company Confidential
96
Company Confidential
SELECT column, group_function(column) FROM table [WHERE condition] [GROUP BY group_by_expression] [ORDER BY column]; Divide rows in a table into smaller groups by using the GROUP BY clause.
97
Company Confidential
Guidelines
If you include a group function in a SELECT clause, you cannot select individual results as well, unless the individual column appears in the GROUP BY clause. You receive an error message if you fail to include the column list in the GROUP BY clause. Using a WHERE clause, you can exclude rows before dividing them into groups. You must include the columns in the GROUP BY clause. You cannot use a column alias in the GROUP BY clause. By default, rows are sorted by ascending order of the columns included in the GROUP BY list. You can override this by using the ORDER BY clause.
98
Company Confidential
99
Company Confidential
100
Company Confidential
101
Company Confidential
102
Company Confidential
106
Company Confidential
Exercise
1. Group functions work across many rows to produce one result per group.
True/False
107
Company Confidential
Exercise
4. Display the highest, lowest, sum, and average salary of all employees. Label the columns Maximum, Minimum, Sum, and Average, respectively. Round your results to the nearest whole number.
108
Company Confidential
Subqueries
110
Company Confidential
Subquery Syntax
SELECT FROM WHERE select_list table expr operator (SELECT select_list FROM table);
The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query).
111
Company Confidential
Using a Subquery
112
Company Confidential
113
Company Confidential
Types of Subqueries
114
Company Confidential
Single-Row Subqueries
Return only one row Use single-row comparison operators
115
Company Confidential
Example
Display the employees whose job ID is the same as that of employee 141.
116
Company Confidential
last_name, job_id employees job_id = (SELECT job_id FROM employees WHERE employee_id = 141);
117
Company Confidential
118
Company Confidential
119
Company Confidential
120
Company Confidential
ERROR at line 4: ORA-01427: single-row subquery returns more than one row
121
Company Confidential
122
Company Confidential
123
Company Confidential
Multiple-Row Subqueries
Return more than one row Use multiple-row comparison operators Example Find the employees who earn the same salary as the minimum salary for each department.
SELECT FROM WHERE last_name, salary, department_id employees salary IN (SELECT MIN(salary) FROM employees GROUP BY department_id);
124
Company Confidential
no rows selected
125
Company Confidential
Exercise
Write a query to display the last name and hire date of any employee in the same department as Zlotkey. Exclude Zlotkey.
126
Company Confidential
Thank You