0% found this document useful (0 votes)
13 views15 pages

dbms unit3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views15 pages

dbms unit3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

UNIT-3

3.1 Examples of Basic SQL Queries:


SQL is a language which is used to interact with relational database management system.
Before we learn what is a SQL and what we can do with the SQL, lets learn the basics first.
What is SQL?
1. SQL stands for Structured Query Language, which is a standardised language for
interacting with RDBMS (Relational Database Management System). Some of the popular
relational database example are: MySQL, Oracle, mariaDB, postgreSQL etc.
2. SQL is used to perform C.R.U.D (Create, Retrieve, Update & Delete) operations on
relational databases.
3. SQL can also perform administrative tasks on database such as database security,
backup, user management etc.
4. We can create databases and tables inside database using SQL.
3.1.1 Types of Structured Query Language(SQL):
In the above section, we learned what we do with the database using SQL. SQL is basically
combination of four different languages, they are –
DQL (Data Query Language): DQL is used to fetch the information from the database
which is already stored there.
DDL (Data Definition Language): DDL is used to define table schemas.
DCL (Data Control Language): DCL is used for user & permission management. It controls
the access to the database.
DML (Data Manipulation Language): DML is used for inserting, updating and deleting data
from the database.
SQL CREATE Database:
The SQL CREATE DATABASE statement is used to create new SQL database.
Syntax: Basic syntax of CREATE DATABASE statement is as follows:
CREATE DATABASE DatabaseName;
Always database name should be unique within the RDBMS.
Example:
If you want to create new database <testDB>, then CREATE DATABASE statement would
be as follows:
SQL> CREATE DATABASE testDB;
Make sure you have admin privilege before creating any database. Once a database is
created, you can check it in the list of databases as follows:
SQL> SHOW DATABASES;
SQL CREATE Table:
Creating a basic table involves naming the table and defining its columns and each
column's data type.
The SQL CREATE TABLE statement is used to create a new table.
Syntax:
Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE table_name( column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
CREATE TABLE is the keyword telling the database system what you want to do. In this
case, you want to create a new table. The unique name or identifier for the table follows
the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what sort of data
type it is. The syntax becomes clearer with an example below.
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement. You can check complete details at Create Table
Using another Table.
Create Table Using another Table:
A copy of an existing table can be created using a combination of the CREATE TABLE
statement and the SELECT statement.
The new table has the same column definitions. All columns or specific columns can be
selected.
When you create a new table using existing table, new table would be populated using
existing values in the old table.
Syntax:
The basic syntax for creating a table from another table is as follows:
CREATE TABLE NEW_TABLE_NAME AS
SELECT [ column1, column2...columnN ]
FROM EXISTING_TABLE_NAME
[ WHERE ]
Here, column1, column2...are the fields of existing table and same would be used to create
fields of new table.
Example:
Following is an example, which would create a table SALARY using CUSTOMERS table and
having fields customer ID and customer SALARY:
SQL> CREATE TABLE SALARY AS SELECT ID, SALARY FROM CUSTOMERS;
This would create new table SALARY, which would have the following records:
SQL DROP or DELETE Table:
The SQL DROP TABLE statement is used to remove a table definition and all data, indexes,
triggers, constraints, and permission specifications for that table.
NOTE: You have to be careful while using this command because once a table is deleted
then all the information available in the table would also be lost forever.
Syntax:
Basic syntax of DROP TABLE statement is as follows:
DROP TABLE table_name;
Example:
Let us first verify CUSTOMERS table and then we would delete it from the database:
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
This means CUSTOMERS table is available in the database, so let us drop it as follows:
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)
Now, if you would try DESC command, then you would get error as follows:
SQL> DESC CUSTOMERS;
ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist
Here, TEST is database name which we are using for our examples.
SQL INSERT Query:
The SQL INSERT INTO Statement is used to add new rows of data to a table in the
database.
Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Here, column1, column2,...columnN are the names of the columns in the table into which
you want to insert data.
You may not need to specify the column(s) name in the SQL query if you are adding values
for all the columns of the table. But make sure the order of the values is in the same order
as the columns in the table. The SQL INSERT INTO syntax would be as follows:
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
Example:
Following statements would create six records in CUSTOMERS table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
we can create a record in CUSTOMERS table using second syntax as follows:
INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

SQL SELECT Query:


SQL SELECT Statement is used to fetch the data from a database table which returns data
in the form of result table. These result tables are called result-sets.
Syntax:
The basic syntax of SELECT statement is as follows:
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2...are the fields of a table whose values you want to fetch. If you
want to fetch all the fields available in the field, then you can use the following syntax:
SELECT * FROM table_name;
Example:
Following is an example, which would fetch ID, Name and Salary fields of the customers
available in CUSTOMERS table:
SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;
SQL WHERE Clause:
The SQL WHERE clause is used to specify a condition while fetching the data from single
table or joining with multiple tables.
If the given condition is satisfied, then only it returns specific value from the table. You
would use WHERE clause to filter the records and fetching only necessary records.
The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE,
DELETE statement, etc., which we would examine in subsequent chapters.
Syntax:
The basic syntax of SELECT statement with WHERE clause is as follows:
SELECT column1, column2, column FROM table_name
WHERE [condition]
You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT
etc. Below examples would make this concept clear.
SQL AND and OR Operators:
The SQL AND and OR operators are used to combine multiple conditions to narrow data in
an SQL statement. These two operators are called conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in
the same SQL statement.
The AND Operator:
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE
clause.
Syntax:
The basic syntax of AND operator with WHERE clause is as follows:
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];

Example:
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 AND age < 25;

SQL UPDATE Query:


The SQL UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows, otherwise all the
rows would be affected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Example:
Following is an example, which would update ADDRESS for a customer whose ID is 6:
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;

SQL DELETE Query


The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows, otherwise all the
records would be deleted.
Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.
Example:
Following is an example, which would DELETE a customer, whose ID is 6:
SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;

SQL LIKE Clause:


The 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 underscore (_)
The percent sign represents zero, one, or multiple characters. The underscore represents a
single number or character. The symbols can be used in combinations.
Syntax:
The basic syntax of % and _ is as follows:
SELECT FROM table_name
WHERE column LIKE 'XXXX%'
or
SELECT FROM table_name
WHERE column LIKE '%XXXX%'
or
SELECT FROM table_name
WHERE column LIKE 'XXXX_'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX'
or
SELECT FROM table_name
WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here, XXXX could be
any numeric or string value.
Example:
SQL> SELECT * FROM CUSTOMERS
WHERE SALARY LIKE '200%';

SQL ORDER BY Clause:


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause is as follows:
SELECT column-list FROM table_name [WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column
you are using to sort, that column should be in column-list.
Example: Following is an example, which would sort the result in descending order by
NAME:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;
SQL Group By:
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups.
The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause.
Syntax:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
Example:
SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;

SQL Distinct Keyword:


The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all
the duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While
fetching such records, it makes more sense to fetch only unique records instead of fetching
duplicate records.
Syntax:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Example:
First, let us see how the following SELECT query returns duplicate salary records:
SQL> SELECT SALARY FROM CUSTOMERS
ORDER BY SALARY;
SQL SORTING Results:
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns. Some databases sort query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause which would be used to sort result in ascending or
descending order is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column
you are using to sort, that column should be in column-list.
Example:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

3.2 Nested Queries and sub queries:


A Subquery or Inner query or a 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.
Syntax:
select columnlist
from tablename
where column operator (select column from tablename
where column operator …..));
There are a few rules that subqueries must follow:−
 Subqueries must be enclosed within parentheses.
 A subquery can have only one column in the SELECT clause, unless multiple columns
are in the main query for the subquery to compare its selected columns.
 An ORDER BY command cannot be used in a subquery, although the main query can
use an ORDER BY. The GROUP BY command can be used to perform the same
function as the ORDER BY in a subquery.
 Subqueries that return more than one row can only be used with multiple value
operators such as the IN operator.
 A subquery cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.

 A subquery can a part of column in the select statement is called SUBSET.


 A INLINE VIEW is a select statement in the FROM clause of another select statement
Example:
select * from (select deptno , count(*) emp_count
from emp
group by deptno ) emp , dept
where dept.deptno = emp.deptno;
 A subquery in the where clause of the select statement is called NESTED SUBQUERY
Example:
select *from emp
where sal > (select sal from emp where empno = 7566);
3.2.1 Types of subqueries:
I. Single row subquery: The query returns only one row from the inner select
statement. The operators used in this query are >, <, =, <=, >=.
Example:
Display the emp details whose salary is equal to minimum salary in company.
select ename,job,sal from emp
where sal = (select min(sal) from emp);
II. Multiple row subquery: The query returns more than one row from inner select
statement. The operators used in these queries are ANY, ALL, IN.
Example:
Display who are getting minimum salary of each dept
select ename, sal from emp
where sal in (select min(sal) from emp group by deptno);
III. Multiple column subquery: The query returns more than one column from the
inner select statement. The column comparison in a multiple column subquery
can be 1) pair wise comparison 2) Non-pair wise comparison.
IV. Correlated subquery: It is another way of performing queries upon the data with
simulation of joins. In this information from outer select statement participates
as the condition in the inner select statement. The operators used in these
queries are exists, not exists.
Steps to be performed in correlated subqueries:
1. First the outer query is executed.
2. Passes the qualified column value to the inner queries “where” clause.
3. Then the inner query or candidate query is executed and the result is passed
is passed to the outer query where clause.
4. Depending upon the separate values the condition is qualified for the specific
record.
Example: Display deptno, dept name there exist at least one employee in dept
select d.deptno,d.dname from dept d
where exist (select * from emp e where d.deptno = e.deptno);
Set Comparison Operators: We have seen the set comparison operators EXISTS, IN
&UNIQUE along with their negation. ALL, ANY are the arithmetic operators (<, >, <=, >=,
<>, =).
Example: Find sailors whose rating is better than some sailor called horatio
select s.sid from sailors s where s.rating > any(select s2.rating
from sailors s2 where s2.name = ‘horatio’);

3.2.3 Aggregative Operators: The aggregative functions are used in the subqueries like
max(), min(), avg()…. It is used in the in the multiple row subqueries because in these
queries returns more than one row for the outer query.

Example: Display who are getting the minimum salary of each department.
select ename, sal from emp
where sal in (select min(sal) from emp group by deptid);
NULL VALUES:
SQL provides a special column value called null to use null when the column value is
unknown or inapplicable.
Example: create table student (sid integer constraint student_sid_nn not null,
name char(20));
In the above example sid doesn’t allow the null values in the column.
Impact on SQL Constructs: Boolean expressions arise in many contexts in SQL, and the
impact of null values must be recognized. In the presence of null value any row that
evaluates to false or unknown is eliminated so that there is an impact on the nested
queries.
The arithmetic operators all return null if one of their arguments is null. The aggregate
operators discard the null values.
3.2.4 Outer Joins:

Some interesting variants of the join operation that rely on null values called outer joins.
Left Outer Join:
To retrieve the missing records from the left side table of the join condition.
Example: Display name, dept no, dept name from tables
select e.ename, d.deptno, d.dname from emp e, dept d
where e.deptno = d.deptno(+);
Right Outer Join:
To retrieve the missing records from the right side table of the join condition.
Example: Display name, dept name, dept no from tables.
select e.ename,e.deptno,d.dname from emp e, dept d
where e.deptno(+) = d.deptno;
Full Outer Join:
To retrieve the missing records from the both side table of the join condition.
3.2.5 Complex Integrity Constraints in SQL:
Constraints over single table:
Constraints can specify over a single table using table constraints by CHECK
conditional expression.
Domain Constraints and distinct types:
A user can define a new domain using the CREATE DOMAIN statement which uses CHECK
constraints.
3.2.6 Triggers:
A trigger is a procedure that is automatically invoked by the DBMS in
response to special changes to the database and DBA. A database that has a set of
associated triggers is called an ACTIVE database.
 Event: A changes to the data base that activates the trigger.
 Condition: A query or test that is run when the trigger is activated.
 Action: A procedure that is executed when the trigger is activated and the
condition is true.
A trigger can be thought of as a daemon that monitors a database and executed when the
database is modified in a way that matches the event specification
Eg: Write a trigger to display salary difference of old and new values.
set serveroutput on;
create or replace trigger emp_diff
after insert or delete or update on emp for each row
declare diff number;
begin
diff := :new.sal – :old.sal;
dbms_output.put_line(‘old salary’: || :old.sal);
dbms_output.put_line(‘new salary’: || :new.sal);
dbms_output.put_line(‘ salary difference’: || diffl);
end;

Examples of sub queries


1. Display the details of all employees
2. Display the depart information from department table
3. Display the name and job for all the employees
4. Display the name and salary for all the employees
5. Display the employee no and total salary for all the employees
6. Display the employee name and annual salary for all employees.
7. Display the names of all the employees who are working in depart number 10.
8. Display the names of all the employees who are working as clerks and drawing a
salary more than 3000.
9. Display the employee number and name who are earning comm.
10. Display the employee number and name who do not earn any comm.
11. Display the names of employees who are working as clerks, salesman or analyst and
drawing a salary more than 3000.
12. Display the names of the employees who are working in the company for the past 5
years;
13. Display the list of employees who have joined the company before 30-JUN-90 or
after 31-DEC-90.
14. List the emps who are joined in the year 1981
15. List the emps who are joined in the month of Aug 1980
16. List the emps whose annul sal ranging from 22000 and 45000
17. Display the names of employees working in depart number 10 or 20 or 40 or
employees working as CLERKS, SALESMAN or ANALYST.
18. Display the names of employees whose name starts with alphabet S.
19. Display the Employee names for employees whose name ends with Alphabet S.
20. Display the names of employees whose names have second alphabet A in their
names.
21. Select the names of the employee whose names is exactly five characters in length.
22. Display the names of the employee who are not working as MANAGERS.
23. Display the names of the employee who are not working as SALESMAN OR CLERK OR
ANALYST.
24. Display the total number of employee working in the company.
25. Display the total salary being paid to all employees.
26. Display the maximum salary and maximum salary and average salary from emp
table.
27. Display the maximum salary being paid to CLERK.
28. Display the maximum salary being paid to depart number 20.
29. Display the minimum salary being paid to any SALESMAN.
30. Display the average salary drawn by MANAGERS.
31. Display the total salary drawn by ANALYST working in depart number 30
32. Display empno,ename,deptno,sal sort the output first base on name and within
name by deptno and with in deptno by sal.
33. Display department numbers and total number of employees working in each
department.
34. Display the various jobs and total number of employees within each job group.
35. Display the depart numbers and total salary for each department.
36. Display the depart numbers and max salary for each department.
37. Display the various jobs and total salary for each job
38. Display the depart numbers with more than three employees in each dept.
39. Display the various jobs along with total salary for each of the jobs where total
salary is greater than 40000.
40. Display the various jobs along with total number of employees in each job. The
output should contain only those jobs with more than three employees.
41. Display the jobs found in department 10 and 20 Eliminate duplicate jobs.
42. Display the distinct jobs in the department 10.
43. Display those department whose name start with "S" while the location name ends
with "K".
44. Display those employees whose salary is more than 3000 after giving 20%
increment.
45. Display those employees who are not working under any manager.
46. Select count of employee in each department where count greater than 3?
47. List out employee name and salary increased by 15% and expressed as whole
number of Dollars?
48. Find out the average salary and average total remuneration for each job type
49. List the emps whose annul sal ranging from 22000 and 45000
50. List the emps who joined in January
51. select second max salary from emp

TEXT BOOK:
1. Raghurama Krishnan, Johannes Gehrke, Database Management Systems, 3rd Edition,
TATA McGraw hill.
2. Web pages

You might also like