0% found this document useful (0 votes)
15 views

DBMS Module 3

Uploaded by

mukulsinghal294
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

DBMS Module 3

Uploaded by

mukulsinghal294
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Module-3

SQL
Introduction to SQL

• SQL (Structured Query Language) is used to perform


operations on the records stored in the database such as
updating records, deleting records, creating and modifying
tables, views, etc.
• SQL is just a query language; it is not a database.
• To perform SQL queries, you need to install any database, for
example, Oracle, MySQL, MongoDB, PostGre SQL, SQL Server,
DB2, etc.

2
What is SQL
• SQL stands for Structured Query Language.
• It is designed for managing data in a relational database
management system (RDBMS).
• It is pronounced as S-Q-L or sometime See-Qwell.
• SQL is a database language, it is used for database creation,
deletion, fetching rows, and modifying rows, etc.
• SQL is based on relational algebra and tuple relational
calculus.
• All RDBMS like MySQL, Oracle, MS Access, Sybase, Informix,
Postgres, and SQL Server use SQL as standard database
language.

3
Why SQL is required

• To create new databases, tables and views

• To insert records in a database

• To update records in a database

• To delete records from a database

• To retrieve data from a database

4
Tables and Views

• A view is a virtual table. A view consists of rows and columns


just like a table.
• views are definitions built on top of other tables (or views),
and do not hold data themselves.
• If data is changing in the underlying table, the same change is
reflected in the view.
• A table contains data.
• The advantage of a view is that it can join data from several
tables thus creating a new view of it.

5
SQL Statements

• SELECT
• INSERT
• UPDATE Data manipulation language (DML)
• DELETE

• CREATE
• ALTER
• DROP Data definition language (DDL)
• RENAME
• TRUNCATE

• GRANT Data control language (DCL)


• REVOKE
• COMMIT
• ROLLBACK Transaction
control
• SAVEPOINT
Data Types
DDL Commands
The CREATE TABLE statement is used to create a new table in a database.
Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
• The DROP TABLE statement is used to drop an existing table in a
database.
DROP TABLE table_name;
• The TRUNCATE TABLE statement is used to delete the data inside a
table, but not the table itself.
TRUNCATE TABLE table_name;
• The ALTER TABLE statement is used to add, delete, or modify columns
in an existing table.
• The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.

• To add a column in a table, use the following syntax:


• ALTER TABLE table_name ADD column_name datatype;

• to delete a column in a table, use the following syntax (notice that


some database systems don't allow deleting a column):
• ALTER TABLE table_name DROP COLUMN column_name;

To change the data type of a column in a table, use the following


syntax:
• SQL Server / MS Access:
• ALTER TABLE table_name ALTER COLUMN column_name datatype;
• My SQL / Oracle (prior version 10G):
• ALTER TABLE table_name MODIFY COLUMN column_name datatype;

• Oracle 10G and later:


• ALTER TABLE table_name MODIFY column_name datatype;

• To RENAME a Table use the following syntax:


Syntax(Oracle,MySQL)

ALTER TABLE table_name RENAME TO new_table_name;

• Columns can be also be given new name with the use of ALTER TABLE.
Syntax(MySQL, Oracle)

ALTER TABLE table_name RENAME COLUMN old_name TO new_name;


SQL Constraints
Constraints are used to limit the type of data that can go into a
table. This ensures the accuracy and reliability of the data in the
table. If there is any violation between the constraint and the data
action, the action is aborted.

The following constraints are commonly used in SQL:


•NOT NULL - Ensures that a column cannot have a NULL value
•UNIQUE - Ensures that all values in a column are different
•PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
•FOREIGN KEY - Prevents actions that would destroy links between
tables
•CHECK - Ensures that the values in a column satisfies a specific
condition
•DEFAULT - Sets a default value for a column if no value is specified
CREATE Table with 5 integrity constraints
Create table Employee

(EID NUMBER(10) primary key,

ENAME VARCHAR2(100) not null,

SALARY NUMBER(10,2) check (salary >0),

JOB_ID VARCHAR2(3) unique,

Commission NUMBER(10,2) default 0);


12
• NOT NULL on ALTER TABLE
• ALTER TABLE Persons MODIFY Age int NOT NULL;
• UNIQUE Constraint on ALTER TABLE
• ALTER TABLE Persons ADD UNIQUE (ID);
•ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
The Human Resources (HR)Schema

DEPARTMENTS LOCATIONS
department_id location_id
department_name street_address
manager_id postal_code city
location_id state_province
country_id

JOB_HISTORY
employee_id
start_date EMPLOYEES
end_date employee_id
job_id first_name COUNTRIES
department_id last_name email country_id
phone_number country_name
hire_date region_id
job_id
salary
commission_pct
JOBS manager_id
job_id department_id
job_title REGIONS
min_salary region_id
max_salary region_name
DML Commands
• INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)] VALUES (value1, value2,
value3,...valueN);
OR
• INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
• Insert Multiple Rows
INSERT ALL
INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)

INTO table_name(column1, column2, column_n) VALUES (expr1, expr2, expr_n)


INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)

SELECT * FROM dual;


• SELECT column1, column2, columnN FROM table_name;
• SELECT * FROM table_name;
• SELECT statement with WHERE clause is as follows:
• SELECT column1, column2, columnN FROM table_name WHERE [condition]
• Example:
• SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >
2,00,000;
• AND operator with WHERE clause
• SELECT column1, column2, columnN FROM table_name WHERE [condition1]
AND [condition2]...AND [conditionN];
• Example:
• SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY >
2,00,000 AND age < 45;
• UPDATE table_name SET column1 = value1, column2 =
value2...., columnN = valueN WHERE [condition];
• Example:
• SQL> UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE
ID = 6;
• You can combine N number of conditions using AND or OR
operators.
• DELETE query with WHERE clause is as follows:
• DELETE FROM table_name WHERE [condition];
• Example: SQL> DELETE FROM CUSTOMERS WHERE ID = 6;
• Delete All Records
• DELETE FROM table_name;
Oracle View
In Oracle, view is a virtual table that does not physically exist.
It is stored in Oracle data dictionary and do not store any data.
It can be executed when called.

A view is created by a query joining one or more tables.

19
Oracle CREATE VIEW
Syntax:
CREATE VIEW view_name AS SELECT columns FROM tables
WHERE conditions;
Example:
CREATE TABLE "SUPPLIERS"
( "SUPPLIER_ID" NUMBER,
"SUPPLIER_NAME" VARCHAR2(4000),
"SUPPLIER_ADDRESS" VARCHAR2(4000)
);

20
Cont..
CREATE TABLE "ORDERS"
( "ORDER_NO." NUMBER,
"QUANTITY" NUMBER,
"PRICE" NUMBER
);
Input the records…………….Then…………….
Create View Query:
CREATE VIEW sup_orders AS
SELECT suppliers.supplier_id, orders.quantity, orders.price
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = supplier_id
WHERE suppliers.supplier_name = 'VOJO';

21
Cont..
You can now check the Oracle VIEW by this query:
SELECT * FROM sup_orders;

22
Oracle Update VIEW
In Oracle, the CREATE OR REPLACE VIEW statement is used to
modify the definition of an Oracle VIEW without dropping it.
Syntax:

CREATE OR REPLACE VIEW view_name AS


SELECT columns
FROM table
WHERE conditions;

23
Cont..
Example:
Execute the following query to update the definition of Oracle VIEW called
sup_orders without dropping it.

CREATE or REPLACE VIEW sup_orders AS


SELECT suppliers.supplier_id, orders.quantity, orders.price
FROM suppliers
INNER JOIN orders
ON suppliers.supplier_id = supplier_id
WHERE suppliers.supplier_name = 'HCL';

You can now check the Oracle VIEW by this query:


SELECT * FROM sup_orders;
24
Oracle DROP VIEW
The DROP VIEW statement is used to remove or delete the
VIEW completely.
Syntax:

DROP VIEW view_name;

Example:

DROP VIEW sup_orders;

25
Joins
• The basic syntax of INNER JOIN is as follows:
• SELECT table1.column1, table2.column2... FROM table1 INNER
JOIN table2 ON table1.common_filed = table2.common_field;
• SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS
INNER JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;

• The basic syntax of LEFT JOIN is as follows:


• SELECT table1.column1, table2.column2... FROM table1 LEFT
JOIN table2 ON table1.common_filed = table2.common_field;
• SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT
JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
• The basic syntax of RIGHT JOIN is as follows:
• SELECT table1.column1, table2.column2... FROM table1 RIGHT
JOIN table2 ON table1.common_filed = table2.common_field;

• SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS


RIGHT JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;

• The basic syntax of FULL JOIN is as follows:


• SELECT table1.column1, table2.column2... FROM table1 FULL
JOIN table2 ON table1.common_filed = table2.common_field;

• SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS


FULL JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;
• The basic syntax of CROSS JOIN is as follows:
• SELECT table1.column1, table2.column2... FROM
table1, table2 [, table3 ]
• SQL> SELECT foods.item_name,foods.item_unit,
• company.company_name,company.company_city
• FROM foods
• CROSS JOIN company;
example
Oracle ORDER BY Clause
In Oracle, ORDER BY Clause is used to sort or re-arrange the
records in the result set. The ORDER BY clause is only used with
SELECT statement.
Syntax:
SELECT column-list FROM table_name [WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
SQL> SELECT * FROM CUSTOMERS ORDER BY NAME, SALARY;

30
Oracle ORDER BY Example: (sorting in descending
order)

SQL> SELECT * FROM CUSTOMERS ORDER BY NAME DESC;

31
SQL Aggregate Functions
• COUNT Function
SELECT COUNT(*) FROM Customers;
SELECT COUNT(*) FROM Customers WHERE salary>=2000;
• SUM Function
SELECT SUM(Salary) FROM Customers;
SELECT SUM(Salary) FROM Customers
WHERE salary>=2000;
• AVG function
SELECT AVG(Salary) FROM Customers;
• MAX Function
SELECT MAX(Salary) FROM Customers;
• MIN Function
SELECT MIN(Salary) FROM Customers;
Oracle GROUP BY Clause
In Oracle GROUP BY clause is used with SELECT statement
to collect data from multiple records and group the
results by one or more columns.
Syntax:-
SELECT column1, column2 FROM table_name WHERE [ conditions ]
GROUP BY column1, column2
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS GROUP BY
NAME;

33
Oracle GROUP BY Example: (with COUNT function)
Customer
O/P

SELECT state, COUNT(*) AS "Number of customers"


FROM customers
WHERE salary > 10000
GROUP BY state;
34
Oracle GROUP BY Example: (with MIN function)
EMPLOYEES

SELECT department,
MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department;

35
Oracle GROUP BY Example: (with MAX function)
EMPLOYEES

SELECT department,
MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;

36
Oracle HAVING Clause
In Oracle, HAVING Clause is used with GROUP BY Clause to
restrict the groups of returned rows where condition is TRUE.
SELECT expression1, expression2, ... expression_n,
aggregate_function (aggregate_expression)
FROM tables
WHERE conditions
GROUP BY expression1, expression2, ... expression_n
HAVING having_condition;
*********************************
aggregate_function : SUM, COUNT, MIN, MAX or AVG functions.

37
Oracle HAVING Example: (with GROUP BY COUNT function)

Customer O/P

SELECT state, COUNT(*) AS "Number of customers"


FROM customers
WHERE salary > 10000
GROUP BY state
HAVING COUNT(*) >= 2;
38
Oracle HAVING Example: (with GROUP BY MIN function)

EMPLOYEES

SELECT department,
MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department
HAVING MIN(salary) < 15000; 39
Oracle HAVING Example: (with GROUP BY MAX function)

EMPLOYEES

SELECT department, MAX(salary) AS "Highest salary"


FROM employees
GROUP BY department
HAVING MAX(salary) > 30000;

40
LIKE Clause
• SQL LIKE clause is used to compare a value to similar
values using wildcard operators.
• There are two wildcards used in conjunction with the
LIKE operator:
• The percent sign (%) - The percent sign represents zero,
one, or multiple characters.
• The underscore (_) - The underscore represents a single
number or character. The symbols can be used in
combinations.
TOP Clause

• TOP clause is used to fetch a TOP N number or X percent


records from a table.
• The basic syntax of TOP clause with SELECT statement would
be as follows:
• SELECT TOP number|percent column_name(s) FROM
table_name WHERE [condition]
• SQL> SELECT TOP 3 * FROM CUSTOMERS;
• SQL> SELECT TOP 50 PERCENT * FROM Customers;

• MySQL supports the LIMIT clause to fetch the limited


number of records
• SQL> SELECT * FROM CUSTOMERS LIMIT 3;
Distinct Keyword
• SQL DISTINCT keyword is used in conjunction with SELECT
statement to eliminate all the duplicates.
• The basic syntax of the DISTINCT keyword to eliminate
duplicate records is as follows:

• SELECT DISTINCT column1, column2,.....columnN FROM


table_name WHERE [condition]

• SQL> SELECT DISTINCT SALARY FROM CUSTOMERS ORDER


BY SALARY;
Set Operations
• UNION Clause
• To use UNION, each SELECT must have the same number of
columns selected, the same number of column expressions, the
same data type, and have them in the same order.
• SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE
condition] UNION SELECT column1 [, column2 ] FROM table1 [,
table2 ] [WHERE condition]

• SQL> SELECT City FROM Customers


UNION
SELECT City FROM Suppliers
ORDER BY City;

• UNION ALL Clause:


• The UNION ALL operator is used to combine the results of two
SELECT statements including duplicate rows.
• INTERSECT Clause
• SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE
condition] INTERSECT SELECT column1 [, column2 ] FROM table1
[, table2 ] [WHERE condition]
• SQL> SELECT City FROM Customers
INTERSECT
SELECT City FROM Suppliers
ORDER BY City;

• EXCEPT Clause
• SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE
condition] EXCEPT SELECT column1 [, column2 ] FROM table1 [,
table2 ] [WHERE condition]
SQL> SELECT City FROM Customers
EXCEPT
SELECT City FROM Suppliers
ORDER BY City;
Alias

• Rename a table or a column temporarily by giving another


name known as alias.

• The basic syntax of table alias is as follows:


SELECT column1, column2.... FROM table_name AS
alias_name WHERE [condition];

• The basic syntax of column alias is as follows:


SELECT column_name AS alias_name FROM table_name
WHERE [condition];
SQL Sub Queries
• Subquery Inner query or Nested query is a query within another
SQL query and embedded within the WHERE clause.
• A subquery is used to return data that will be used in the main
query as a condition to further restrict the data to be retrieved.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and
DELETE statements along with the operators like =, >=, <=, IN,
BETWEEN, etc.
• Subqueries with the SELECT Statement:
• SQL> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID
FROM CUSTOMERS WHERE SALARY > 4500) ;
• Subqueries with the INSERT Statement:
• SQL> INSERT INTO CUSTOMERS_BKP SELECT * FROM
CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS
WHERE SALARY > 4500) ;
• Subqueries with the UPDATE Statement:
• SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE
IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );

• Subqueries with the DELETE Statement:


• SQL> DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE
FROM CUSTOMERS_BKP WHERE AGE > 27 );
• Subqueries: Guidelines
• A subquery must be enclosed in parentheses.
• A subquery must be placed on the right side of the comparison
operator.
• Subqueries cannot manipulate their results internally, therefore
ORDER BY clause cannot be added into a subquery.
• If a subquery (inner query) returns a null value to the outer query,
the outer query will not return any rows when using certain
comparison operators in a WHERE clause.
Task
• Employee table
(EMPLOYEE_ID , FIRST_NAME , LAST_NAME , EMAIL,
PHONE_NUMBER , HIRE_DATE , JOB_ID , SALARY ,
OMMISSION_PCT , MANAGER_ID , DEPARTMENT_ID )

• Queries:
1. find those employees who get higher salary than the employee
whose ID is 163.
2. find those employees whose salary matches the smallest salary
of any of the departments.
3. find those employees who report that manager whose first
name is ‘Ramesh’.
4. find the employee whose salary is 3000 and reporting person’s
ID is 121.
1. find those employees whose ID matches any of the
number 134, 159 and 183.
2. find those employees who do not work in those
departments where manager ids are in the range 100,
200.
3. find those employees who get second-highest salary.
4. find those employees who work in the same department
where ‘Clara’ works.
5. find those employees who work in a department where
the employee’s first name contains a letter 'T‘.
6. find those employees who earn more than the average
salary and work in a department with any employee
whose first name contains a character a 'J'.
Answer
1. SELECT first_name, last_name FROM employees WHERE salary >
( SELECT salary FROM employees WHERE employee_id=163 );
2. SELECT first_name, last_name, salary, department_id FROM
employees WHERE salary IN ( SELECT MIN(salary) FROM
employees GROUP BY department_id );
3. SELECT first_name, last_name, employee_id, salary FROM
employees WHERE manager_id = (SELECT employee_id FROM
employees WHERE first_name = ‘Ramesh' );
4. SELECT * FROM employees WHERE (salary,manager_id)= (SELECT
3000,121);
5. SELECT * FROM employees WHERE employee_id IN (134,159,183);
6. SELECT * FROM employees WHERE department_id NOT IN (SELECT
department_id FROM departments WHERE manager_id BETWEEN
100 AND 200);
Answer
1. SELECT * FROM employees WHERE employee_id IN (SELECT
employee_id FROM employees WHERE salary = (SELECT
MAX(salary) FROM employees WHERE salary < (SELECT
MAX(salary) FROM employees)));
2. SELECT first_name, last_name, hire_date FROM employees
WHERE department_id = ( SELECT department_id FROM
employees WHERE first_name = 'Clara') AND first_name <>
'Clara';
3. SELECT employee_id, first_name, last_name FROM employees
WHERE department_id IN ( SELECT department_id FROM
employees WHERE first_name LIKE '%T%' );
4. SELECT employee_id, first_name , salary FROM employees
WHERE salary > (SELECT AVG (salary) FROM employees ) AND
department_id IN ( SELECT department_id FROM employees
WHERE first_name LIKE '%J%');

You might also like