SQL Practical
SQL Practical
Introduction to databases
Overview of database
What a database is How it fits into the broader information management picture What the different parts of a database are and THEN finally we will move to SQL . . .
What is a database?
Managing as re-organising
We often need to access and re-sort data for various uses. These may include:
Creating mailing lists Writing management reports Generating lists of selected news stories Identifying various client needs
Managing as re-processing
The processing power of a database allows it to:
y Sort y Match y Link y Aggregate y Skip fields y Calculate y Arrange
Databases everywhere!
Because of the versatility of databases, we find them powering all sorts of projects:
y A web site that is capturing registered users y A client tracking application for social service organisations y A medical record system for a health care facility y Your personal address book in your e-mail client y A collection of word processed documents y A system that issues airline reservations
Fields
Database storage units Generic elements of content
Records
A simple table showing fields (columns) and records(rows):
Queries
Queries are the information retrieval requests you make to the database Your queries are all about the information you are trying to gather
Reports
If the query is a question... ...then the report is its answer Reports can be tailored to the needs of the data-user, making the information they extract much more useful Now with this knowledge about databases, lets proceed to explore SQL..........
Objectives of SQL
A database language should allow a user to :
Create the database and relation structures Perform basic DBM tasks like
insertion Modification Deletion
A database language must do all these tasks with minimum user effort , syntax should be easy to learn and it should be portable.
Components of SQL
As a language, SQL has two major components:
DDL (Data Definition Language) for defining the database structure and controlling access to the data. DML (Data Manipulation Language) for retrieving and updating data.
Advantages of SQL
SQL is a non-procedural language you specify what information you require, rather than how to get it. SQL is free-format it means that parts of the statements do not have to be typed at particular locations on the screen. SQL can be used by a range of users including DBA (database Administrator), management personnel, application developers and many other types of end-users.
Advantages of SQL
The command structure consists of standard English words like CREATE TABLE, INSERT, SELECT. For Example:
CREATE TABLE staff( staffno VARCHAR(5), sname VARCHAR(15), salary DECIMAL(7,2)); INSERT INTO staff VALUES ( SM100 , Suman , 30000); SELECT staffno, sname, salary FROM staff WHERE salary > 20000;
Upper-case letters are used for Reserved words. Lower-case letters for user-defined words.
Data Manipulation
The SQL DML statements are :
SELECT -- query tables and views in the database INSERT -- add rows to tables UPDATE -- modify columns in table rows DELETE -- remove rows from tables
The WHERE clause is optional; if missing, all table rows are shown. All the three components of SELECT statement must appear in same order.
SELECT Clause
SELECT has the following general format: SELECT [ALL|DISTINCT] select-list
select-list is a list of column names separated by commas. ALL and DISTINCT specifiers are optional. DISTINCT specifies that duplicate rows are discarded. A duplicate row is when each corresponding select-list column has the same value. The default is ALL, which retains duplicate rows.
FROM Clause
The FROM clause always follows the SELECT clause. It lists the tables accessed by the query. For example, SELECT staffno FROM staff; A special select list consisting of a single '*' requests all columns in all tables in the FROM clause. For example, SELECT * FROM staff;
WHERE clause
It is optional. When specified, it always follows the FROM clause. The WHERE clause filters rows from the FROM clause tables. Omitting the WHERE clause specifies that all rows are used.
WHERE clause
Following the WHERE keyword is a logical expression, also known as a predicate. The predicate evaluates to a SQL logical value -true, false or unknown. The most basic predicate is a comparison: example WHERE color = 'Red' This predicate returns:
true -- if the color column contains the string value 'Red', false -- if the color column does not contains value Red unknown -- if the color column contains null.
Comparison Operators
= - it compares two values for equality. > - greater than < - less than >= - greater than or equal to <= - less than or equal to <> - not equal to For example: SELECT * FROM staff WHERE salary >= 20000;
Exercise
Retrieve all columns, all rows.
1. Display the details of all employees 2. Display the details of all departments.
Exercise
Use of DISTINCT clause.
1. Display all jobs in the organization. 2. Display numbers of all departments where employees are working.
BETWEEN Operator
The BETWEEN operator tests whether a value is between two other values. (both values inclusive) BETWEEN comparisons have the following format: value-1 [NOT] BETWEEN value-2 AND value-3 For example : SELECT * FROM emp WHERE sal BETWEEN 5000 and 15000;
IN operator
The IN operator tests whether a value matches any value in a list of values. IN comparisons have the following general format: value-1 [NOT] IN ( value-2 [, value-3] ... ) This comparison tests if value-1 matches value-2 or matches value-3, and so on. For example, SELECT name FROM emp WHERE deptno IN (10,40);
LIKE Operator
The SQL LIKE clause is very useful when you want to specify a search condition within your SQL WHERE clause, based on a part of a column contents. For example if you want to select all customers having FirstName starting with 'J SELECT * FROM Customers WHERE FirstName LIKE 'J% ;
LIKE Operator
The '%' is a so called wildcard character and represents any string in our pattern. Another wildcard character is '_' representing any single character. Example: SELECT * FROM emp WHERE hiredate LIKE %82 ;
The SQL OR statement will return all rows satisfying any of the conditions listed in the WHERE clause.
SELECT * FROM Customers WHERE FirstName = 'James' OR FirstName = 'Paula ;
Aggregate functions
The SQL COUNT aggregate function is used to count the number of rows in a database table.
SELECT COUNT(LastName) AS NumberOfCustomers FROM Customers ;
This will give total No. of Customers . The SQL MAX aggregate function allows us to select the highest (maximum) value for a certain column.
SELECT MAX(DOB) AS MaxDOB FROM Customers ;
Aggregate functions
The SQL MIN aggregate function allows us to select the lowest (minimum) value for a certain column.
SELECT MIN(DOB) AS MinDOB FROM Customers ;
The SQL AVG aggregate function selects the average value for certain table column.
SELECT AVG(SaleAmount) AS AvgSaleAmount FROM Sales ;
Aggregate functions
The SQL SUM aggregate function allows selecting the total for a numeric column.
SELECT SUM(SaleAmount) FROM Sales WHERE CustomerID = 3 ;
GROUP BY Clause
The SQL GROUP BY statement is used along with the SQL aggregate functions like SUM to provide means of grouping the result dataset by certain database table column(s).
SELECT Date, SUM(Hours) FROM EmployeeHours GROUP BY Date ; SELECT Employee, AVG(Hours) FROM EmployeeHours GROUP BY Employee ;
The first attribute in SELECT clause should always be the same attribute on which grouping is done.
HAVING Clause
The SQL HAVING clause is used to restrict conditionally the output of a SQL statement, by a SQL aggregate function used in your SELECT list of columns. You can't specify criteria in a SQL WHERE clause against a column in the SELECT list for which SQL aggregate function is used. Having clause is always computed after the groups are formed and the aggregates are fully computed
NOTE : WHERE clause is used for filtering rows and HAVING clause is used for filtering Groups.
Examples
SELECT Employee, SUM (Hours) FROM EmployeeHours GROUP BY Employee HAVING SUM (Hours) > 24 ;
ORDER BY Clause
The ORDER BY clause is optional. If used, it must be the last clause in the SELECT statement. The ORDER BY clause requests sorting for the results of a query. When the ORDER BY clause is missing, the result rows from a query have no defined order (they are unordered). Syntax is ORDER BY column-1 [ASC|DESC] [ column-2 [ASC|DESC] ] ... Example: SELECT * FROM emp ORDER BY empno DESC;
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. Example: SELECT last_name || is a || job AS "Employee Details FROM employees;
Data Types
The data types are described as follows: 1. NUMBER(p,s) - Number value having a maximum number of digits p, with s digits to the right of the decimal point. 2. VARCHAR2(s) - Variable-length character value of maximum size s. 3. DATE - Date and time value between January 1, 4712 B.C., and December 31, 9999 A.D. 4. CHAR(s) - Fixed-length character value of size s
Rules of Precedence
1. 2. 3. 4. 5. 6. 7. 8. Arithmetic operators Concatenation operator Comparison conditions IS [NOT] NULL, LIKE, [NOT] IN [NOT] BETWEEN NOT logical condition AND logical condition OR logical condition
Practice sheet 3
Create a query to display all the data from the EMP table. Separate each column by a comma. Name the column THE_OUTPUT. 2. Display the name concatenated with the job, separated by a comma and space, and name the column Employee and Title. 3. Display the employee if an employee is a president or a sales representative, and if the employee earns more than $15,000. 4. Display the last names and salaries of all employees. Order the result by department number, and then in descending order by salary. 5. Display the last name, salary, and commission for all employees who earn commissions. Sort data in descending order of salary and commissions. 6. Display the name of all employees who have an a and an e in their name. 7. Display the name, job, and salary for all employees whose job is sales representative or clerk and whose salary is not equal to 2500, 3500, or 7000. 8. Display of average salaries of those departments that have an average salary greater than 8,000. 9. Display the job and total monthly salary for each job with a total payroll exceeding 13000. Exclude sales representatives and sorts the list by the total monthly salary. 10. Displays the maximum average salary of departments. 1.
11. Display the highest, lowest, sum, and average salary of all employees. Label the columns Maximum, Minimum, Sum, and Average, respectively. 12. Write a query to display the number of people with the same job. 13. Determine the number of managers without listing them. Label the column Number of Managers.
Cartesian Product
A Cartesian product is generated if a join condition is omitted. Example : Display employee last name and department name from the EMPLOYEES and DEPARTMENTS tables. SELECT last_name, department_name dept_name FROM employees, departments;
Inner joins
This join involves primary and foreign key complements. It is also known as Equijoins or simple joins. 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;
Guidelines :
Table aliases can be up to 30 characters in length, but shorter is better. If a table alias is used for a particular table name in the FROM clause, then that table alias must be substituted for the table name throughout the SELECT statement. Table aliases should be meaningful. The table alias is valid only for the current SELECT statement.
Non-Equijoins
A non-equijoin is a join condition containing something other than an equality operator. The relationship between the EMP table and the SALGRADE table has an example of a non-equijoin. A relationship between the two tables is that the SALARY column in the EMP table must be between the values in the LOWSAL and HISAL columns of the SALGRADE table. The relationship is obtained using an operator other than equals (=). SELECT e.ename, e.sal, s.grade FROM emp e, salgrade s WHERE e.sal BETWEEN s.losal AND s.hisal;
Outer Join
The missing rows can be returned if an outer join operator is used in the join condition. The operator is a plus sign enclosed in parentheses (+), and it is placed on the side of the join that is deficient in information. This operator has the effect of creating one or more null rows, to which one or more rows from the non deficient table can be joined. Example : Display employee last names, department ID s and department names. SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id(+) = d.department_id ; Note : it will display detail of deptt that donot have any employee.
Self - Join
Sometimes you need to join a table to itself. Example : The example joins the EMPLOYEES table to itself. To simulate two tables in the FROM clause, there are two aliases, namely w and m, for the same table, EMPLOYEES. In this example, the WHERE clause contains the join that means where a worker s manager number matches the employee number for the manager. SELECT worker.last_name || works for || manager.last_name FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id ;
Practice sheet 5
1. 2. 3. 4. 5. 6. 7. Display the name and hire date of any employee in the same department as ABC. Exclude ABC. Display the employee numbers & names of all employees who earn more than the average salary. Sort the results in ascending order of salary. Display the employee numbers & names of all employees who work in a department with any employee whose name contains a u . Display the name, department number, and job of all employees whose department location is DELHI . Display the name and salary of every employee who reports to King. Display the department number, name & job for every employee in the MARKETING department. Display the names, job & department names for every employee in a location given by user at run-time. It should allow for case-insensitive searches of the department location.
DROP COLUMN clause is used to drop columns no longer needed from the table. ALTER TABLE dept80 DROP COLUMN job_id;
Dropping a Table
It removes the definition of an Oracle table. When a table is dropped, the database loses all the data in the table and all the indexes associated with it. Syntax : DROP TABLE table Any views on table remain but are invalid. Any pending transactions are committed. Only the creator of the table or a user with the DROP ANY TABLE privilege can remove a table. Example : DROP TABLE dept80; Note: The DROP TABLE statement, once executed, is irreversible.
Truncating a Table
Removes all rows from a table Releases the storage space used by that table You cannot roll back row removal when using TRUNCATE. Syntax : TRUNCATE TABLE table; If the table is the parent of a referential integrity constraint, you cannot truncate the table.Disable the constraint before issuing the TRUNCATE statement.
The DELETE statement can also remove all rows from a table, but it does not release storage space.
INSERT Statement
Add new rows to a table by using the INSERT statement. Only one row is inserted at a time Syntax : INSERT INTO table [(column [, column...])] VALUES (value [, value...]); List values in the default order of the columns in the table. Optionally, list the columns in the INSERT clause. Enclose character and date values within single quotation marks.
INSERT Statement
Methods for Inserting Null Values 1. Implicit - Omit the column from the column list. 2. Explicit - Specify the NULL keyword in the VALUES list, specify the empty string ( ) in the VALUES list for character strings and dates. Example: INSERT INTO dept (deptno, dname ) VALUES (30, Purchasing ); (LOC attribute not specified here) INSERT INTO departments VALUES (100, Finance , NULL);
Example
INSERT INTO employees (employee_id, first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_pct, manager_id, department_id) VALUES (113, Louis , Popp , LPOPP , 515.124.4567 , SYSDATE, AC_ACCOUNT , 6900, NULL, 205, 100); INSERT INTO departments (department_id, department_name, location_id) VALUES (&department_id, &department_name ,&location);
UPDATE Statement
Modify existing rows with the UPDATE statement. Update more than one row at a time, if required. Syntax : UPDATE table SET column = value [, column = value, ...] [WHERE condition] Example : UPDATE employees SET department_id = 70 WHERE employee_id = 113; All rows in the table are modified if you omit the WHERE clause.
DELETE Statement
You can remove existing rows by using the DELETE statement. Syntax: DELETE [FROM] table [WHERE condition]; Example: DELETE FROM departments WHERE department_name = Finance ;
All rows in the table are deleted if you omit the WHERE clause. The DELETE statement does not ask for confirmation. However, the delete operation is not made permanent until the data transaction is committed. Therefore, you can undo the operation with the ROLLBACK statement if you make a mistake.
Constraints
The Oracle Server uses constraints to prevent invalid data entry into tables. You can use constraints to do the following: Enforce rules on the data in a table whenever a row is inserted, updated, or deleted from that table. The constraint must be satisfied for the operation to succeed. Prevent the deletion of a table if there are dependencies from other tables Data Integrity Constraints are : 1. NOT NULL - Specifies that the column cannot contain a null value 2. UNIQUE - Specifies a column or combination of columns whose values must be unique for all rows in the table 3. PRIMARY KEY - Uniquely identifies each row of the table 4. FOREIGN KEY - Establishes and enforces a foreign key relationship between the column and a column of the referenced table 5. CHECK - Specifies a condition that must be true
Defining Constraints
Syntax : CREATE TABLE table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]); Example : CREATE TABLE employees( employee_id NUMBER(6), first_name VARCHAR2(20), ... job_id VARCHAR2(10) NOT NULL, CONSTRAINT emp_emp_id_pk PRIMARY KEY (EMPLOYEE_ID));
Examples
ALTER TABLE employees DISABLE CONSTRAINT emp_emp_id_pk CASCADE; ALTER TABLE employees ENABLE CONSTRAINT emp_emp_id_pk;
Practice sheet 5
1. 2. 3. 4. 5. 6. 7. Display the name and hire date of any employee in the same department as ABC. Exclude ABC. Display the employee numbers & names of all employees who earn more than the average salary. Sort the results in ascending order of salary. Display the employee numbers & names of all employees who work in a department with any employee whose name contains a u . Display the name, department number, and job of all employees whose department location is DELHI . Display the name and salary of every employee who reports to King. Display the department number, name & job for every employee in the MARKETING department. Display the names, job & department names for every employee in a location given by user at run-time. It should allow for case-insensitive searches of the department location.