Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

SQL 2

The document outlines the basics of SQL including DDL, DML, aggregate functions, joins, cursors, triggers, indexing and PL/SQL. It also provides examples of questions that could be asked and sample SQL queries.

Uploaded by

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

SQL 2

The document outlines the basics of SQL including DDL, DML, aggregate functions, joins, cursors, triggers, indexing and PL/SQL. It also provides examples of questions that could be asked and sample SQL queries.

Uploaded by

Prem Prakash
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 123

Outlines

Basics of sql
DDL statements
DML statements
Aggregate functions
SQL clauses
Joins
Cursor, Trigger and indexing
PL\SQL
Outcomes
Understand the basics of sql.
Apply the concepts of sql to solve various
queries..
Learn the basic of PL\SQL.
Apply cursor, trigger and indexes in database.
Apply the concepts of procedural language
concepts to create procedure, function etc.
Types of Questions asked from SQL
1. What is DDL and DML. Name some command?
2. How char is different from varchar?
3. Tell me the difference between float and double.
4. What is BLOB and CLOB with their uses?
5. How we can find thee minimum salary from any relation?
6. How we can find four maximum salary?
7. How to find max and min salary from a relation?
8. What is the need of trigger.?
9. What is the difference between function and stored procedure?
10. How many max tables allows in join operation?
11. How many max columns are possible in any relation?
12. How many max rows\ tuples are possible in any relation?
13. What is the need of cursor and how many types of cursor and their uses?
14. What is indexing and how to apply indexing in a database?
15. Questions based on aggregate functions.
16. Question based on group by and ordered by.
17. How to find distinct value?
18. How to find duplicate tuple?
19. How many triggers allowed in mysql table?
20. How many rows will return from dual table.?
21. Write an SQL query to find names of employee start with ‘A’?
22. Write a SQL query to make a column as unique?
23. How many tables can be joined in SQL Server?
24. How many columns can exist together per table?
25. What is SQL Profiler?
26. Explain what is meant by replication of database?
27. What are Denormalization and Normalization?
28. Differentiate between DROP, DELETE, And TRUNCATE Command.
29. What is the difference between SQL, MySQL, and PL/SQL?
30. What Clauses are used in SQL?
31. Write an SQL query to fetch “FIRST_NAME” from Worker table in upper case.
32. Write an SQL query to print the first three characters of FIRST_NAME from Worker
table.
33. How many triggers allowed in mysql table?
34. SQL Query to find Max Salary from each department.
35. SQL Query to find second highest salary of Employee.
SQL
DDL( Data Definition Language)
• CREATE – is used to create the database or its objects (like table, index, function,
views, store procedure and triggers).
• DROP – is used to delete objects from the database.
• ALTER-is used to alter the structure of the database.
• TRUNCATE–is used to remove all records from a table, including all spaces
allocated for the records are removed.
• COMMENT –is used to add comments to the data dictionary.
• RENAME –is used to rename an object existing in the database.

DML( Data Manipulation Language)


• SELECT – is used to retrieve data from the a database.
• INSERT – is used to insert data into a table.
• UPDATE – is used to update existing data within a table.
• DELETE – is used to delete records from a database table.
SQL DDL COMMANDS
SQL PRIMARY KEY Constraint
• The PRIMARY KEY constraint uniquely identifies each record in a table.
• Primary keys must contain UNIQUE values, and cannot contain NULL values.
• A table can have only ONE primary key; and in the table, this primary key can consist of single
or multiple columns (fields).
SQL DML COMMANDS
SQL Operators
SQL Queries
1. Write a query to display all customers with a grade above 100.
2. Write a query statement to display all customers in New York who have a grade
value above 100.
3. Write a SQL statement to display all customers, who are either belongs to the city
New York or had a grade above 100.
4. Write a SQL query to display those customers who are neither belongs to the city
New York nor grade value is more than 100.
5. Write a SQL statement to display all the information of all salesmen.
6. Write a query to display three numbers in three columns.
7. Write a SQL statement to display names and city of salesman, who belongs to the
city of Paris.
8. Write a query to display the sum of two numbers 10 and 15 from RDMS sever.
9. Write a query to display the result of an arithmetic expression 10 + 15 - 5 * 2
10. Write a query to display the columns in a specific order like order date, salesman
id, order number and purchase amount from for all the orders.
Aggregate functions in SQL
In database management an aggregate function is a function where the
values of multiple rows are grouped together as input on certain criteria to
form a single value of more significant meaning.
Various Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
Count():

Count(*): Returns total number of records .i.e 6.


Count(salary): Return number of Non Null values over the column salary. i.e 5.
Count(Distinct Salary): Return number of distinct Non Null values over the column
salary .i.e 4
Sum():

• sum(salary): Sum all Non Null values of Column salary i.e., 310
sum(Distinct salary): Sum of all distinct Non-Null values i.e., 250.

Avg():

• Avg(salary) = Sum(salary) / count(salary) = 310/5


Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 250/4

Min():

• Min(salary): Minimum value in the salary column except NULL i.e., 40.

Max():

• Max(salary): Maximum value in the salary i.e., 80.


SQL SUB Queries
In SQL a Subquery can be simply defined as a query within another query. In other
words we can say that a Subquery is a query that is embedded in WHERE clause of
another SQL query.
Important rules for Subqueries:
 We can place the Subquery in a number of SQL
clauses: WHERE clause, HAVING clause, FROM clause.
Sub queries can be used with SELECT, UPDATE, INSERT, DELETE statements along
with expression operator. It could be equality operator or comparison operator
such as =, >, =, <= and Like operator.
 A subquery is a query within another query. The outer query is called as main
query and inner query is called as subquery.
 The subquery generally executes first, and its output is used to complete the query
condition for the main or outer query.
 Subquery must be enclosed in parentheses.
 Subqueries are on the right side of the comparison operator.
 ORDER BY command cannot be used in a Subquery. GROUPBY command can be
used to perform same function as ORDER BY command.
 Use single-row operators with singlerow Subqueries. Use multiple-row operators
with multiple-row Subqueries.
Sample Queries
To display NAME, LOCATION, PHONE_NUMBER of the students from DATABASE table
whose section is A.
Select NAME, LOCATION, PHONE_NUMBER
from DATABASE
WHERE ROLL_NO IN (SELECT ROLL_NO from STUDENT where SECTION=’A’);
Student

Marks
SQL Exercises based on Multiple Tables
1. Write a query to find those customers with their name and those
salesmen with their name and city that lives in the same city.
2. Write a SQL statement to find the names of all customers along with the
salesmen who works for them.
3. Write a SQL statement to display all those orders by the customers not
located in the same cities where their salesmen live.
4. Write a SQL statement that finds out each order number followed by
the name of the customers who made the order.
5. Write a SQL statement that sorts out the customer and their grade who
made an order. Each of the customers must have a grade and served by
at least a salesman, who belongs to a city.
6. Write a query that produces all customers with their name, city,
salesman and commission, who served by a salesman and the salesman
works at a rate of the commission within 12% to 14%.
7. Write a SQL statement that produces all orders with the order number,
customer name, commission rate and earned commission amount for
those customers who carry their grade is 200 or more and served by an
existing salesman.
SQL Exercises based on SUBQUERIES
1. Write a query to display all the orders from the orders table issued by the
salesman 'Paul Adam'.
2. Write a query to display all the orders for the salesman who belongs to the
city London.
3. Write a query to find all the orders issued against the salesman who may
works for customer whose id is 3007.
4. Write a query to display all the orders which values are greater than the
average order value for 10th October 2012.
5. Write a query to find all orders attributed to a salesman in New york.
6. Write a query to display the commission of all the salesmen servicing
customers in Paris.
7. Write a query to display all the customers whose id is 2001 bellow the
salesman ID of Mc Lyon.
8. Write a query to count the customers with grades above New York's average.
9. Write a query to display all customers with orders on October 5, 2012.
10. Write a query to display all the customers with orders issued on date 17th
August, 2012.
SQL Exercises - Aggregate Functions and Group by statements
1. Write a SQL statement to find the total purchase amount of all orders.
2. Write a SQL statement to find the average purchase amount of all orders.
3. Write a SQL statement to find the number of salesmen currently listing for all of
their customers.
4. Write a SQL statement know how many customer have listed their names.
5. Write a SQL statement find the number of customers who gets at least a gradation
for his/her performance.
6. Write a SQL statement to get the maximum purchase amount of all the orders.
7. Write a SQL statement to get the minimum purchase amount of all the orders.
8. Write a SQL statement which selects the highest grade for each of the cities of the
customers.
9. Write a SQL statement to find the highest purchase amount with their ID, for only
those customers whose ID is within the range 3002 and 3007.
10. Write a SQL statement that counts all orders for a date August 17th, 2012.
11. Write a query that counts the number of salesmen with their order date and ID
registering orders for each day.
12. Write a SQL query to calculate the average price of all the products.
13. Write a SQL statement to find the highest purchase amount on a date '2012-08-17'
for each salesman with their ID.
SQL Exercises-JOINS

1. Write a SQL statement to prepare a list with salesman name, customer name and
their cities for the salesmen and customer who belongs to the same city.
2. Write a SQL statement to make a list with order no, purchase amount, customer
name and their cities for those orders which order amount between 500 and
2000.
3. Write a SQL statement to know which salesman is working for which customer.
4. Write a SQL statement to find the list of customers who appointed a salesman
for their jobs who gets a commission from the company is more than 12%.
5. Write a SQL statement to find the list of customers who appointed a salesman
for their jobs who does not live in the same city where their customer lives, and
gets a commission is above 12%
6. Write a SQL statement to find the details of a order i.e. order number, order
date, amount of order, which customer gives the order and which salesman
works for that customer and how much commission he gets for an order.
7. Write a SQL statement to make a list in ascending order for the customer who
works either through a salesman or by own.
8. Write a SQL statement to make a list in ascending order for the salesmen who
works either for one or more customer or not yet join under any of the
customers.
TRIGGERS
TRIGGERS are stored programs that are fired by Oracle engine automatically
when DML Statements like insert, update, delete are executed on the table or
some events occur. The code to be executed in case of a trigger can be defined
as per the requirement. You can choose the event upon which the trigger needs
to be fired and the timing of the execution. The purpose of trigger is to maintain
the integrity of information on the database.
Benefits of Triggers
• Generating some derived column values automatically
• Enforcing referential integrity
• Event logging and storing information on table access
• Auditing
• Synchronous replication of tables
• Imposing security authorizations
• Preventing invalid transactions
Types of Triggers in Oracle
Triggers can be classified based on the following parameters.
Classification based on the timing
– BEFORE Trigger: It fires before the specified event has occurred.
– AFTER Trigger: It fires after the specified event has occurred.
– INSTEAD OF Trigger: A special type. You will learn more about the
further topics. (only for DML )
Classification based on the level
– STATEMENT level Trigger: It fires one time for the specified event
statement.
– ROW level Trigger: It fires for each record that got affected in the
specified event. (only for DML)
Classification based on the Event
– DML Trigger: It fires when the DML event is specified
(INSERT/UPDATE/DELETE)
– DDL Trigger: It fires when the DDL event is specified (CREATE/ALTER)
– DATABASE Trigger: It fires when the database event is specified
(LOGON/LOGOFF/STARTUP/SHUTDOWN)
So each trigger is the combination of above parameters.
How to Create Trigger
Cursor in SQL
Cursor is a Temporary Memory or Temporary Work Station. It is Allocated by
Database Server at the Time of Performing DML operations on Table by User.
Cursors are used to store Database Tables. There are 2 types of Cursors:
Implicit Cursors, and Explicit Cursors. These are explained as following below.
• Implicit Cursors:
Implicit Cursors are also known as Default Cursors of SQL SERVER. These
Cursors are allocated by SQL SERVER when the user performs DML
operations.
• Explicit Cursors :
Explicit Cursors are Created by Users whenever the user requires them.
Explicit Cursors are used for Fetching data from Table in Row-By-Row
Manner.
How to create Explicit Cursor:
Indexing in Database
Indexing is a procedure that returns your requested data faster from the defined
table. Without indexing, the SQL server has to scan the whole table for your
data.
By indexing, SQL server do the exact same thing when you searched for a
content in a book by checking the index page. In the same way table’s index
allows us to locate the exact data without scanning the whole table. There are
two types of indexing in SQL.
1. Clustered index
2. Non-clustered index
1.Clustered –
Clustered index is the type of indexing that established a physical sorting order of
rows. Suppose you have a table Student_info which contains ROLL_NO as a
primary key than Clustered index which is self created on that primary key will
sort the Student_info table as per ROLL_NO. Clustered index is like Dictionary, in
the dictionary sorting order is alphabetical there is no separate index page.
2. Non-clustered:
The Non-Clustered index is an index structure separate from the data stored in a
table that reorders one or more selected columns. The non-clustered index is
created to improve the performance of frequently used queries not covered by
clustered index. It’s like a textbook, the index page is created separately at the
beginning of that book.

Clustered vs Non-Clustered index:


• In a table there can be only one clustered index or one or more than one non
clustered index.
• In Clustered index there is no separate index storage but in Non Clustered
index there is separate index storage for the index.
• Clustered index is slower than Non Clustered index.
Creating Procedure and Functions in Oracle

PL/SQL supports the two type of programming:


Procedure
Procedures are usually used to perform any specific task and functions are used to
compute a value.
The basic syntax for the creating procedure is:
CREATE OR REPLACE PRODURE procedure _name (arguments)AS/IS
Procedure body;
The body of procedure is block of statements with declarative executable and
exception sections.
The declarative section is located between the IS /AS keyword and BEGIN keyword.
The executable section is located between BEGIN and EXCEPTION keywords or
between the BEGIN and END keywords if there is no EXCEPTION handling section.
If EXCEPTION handling is present, it is located between exception and END keywords.
Steps for Creating Procedure:
CREATE OR REPLACE PRODURE procedure _name
(parameter list)AS/IS
(Declarative section)
BEGIN
(Executable section )
EXCEPTION
(Error handling or exception section).
End the procedure name
To execute the procedure we have to write a block of
statement: Begin
Procedurename(data);
End;
/
create or replace procedure addnewstud(
p_rollnostud.rollno%type,
p_firstnamestud.firstname%type,
p_lastnamestud.firstname%type) as begin
insert into
stud(rollno,firstname,lastname)values(p_rollno
,p_firstname,p_lastname);
endaddnewstud;
/
output:Procedure created.
beginaddnewstud(2,'rohini','narwade'); end;
/
Function
Steps for Creating function:
CREATE OR REPLACE FUNCTION function _name (parameter
list)AS/IS
Return datatype is/as
(local declaration)
BEGIN
(Exception section)
EXCEPTION
(Error handling or exception section).
End Function name;
A function has two parts, namely function specification and
function body. The function specification begins with the
keyword function and end with return clause. The function
bodies begins with the keyword is/as and end with keyword
end
create or replace function studentn( p_rollnostud.rollno%type)
returnboolean as v_firstname varchar2(20);
v_returnboolean;
begin

selectfirstname into v_firstname from stud where rollno=p_rollno;


if (firstname='seema')
then
v_return =true; else
v_return =false;
end if;
endstudentn;

You might also like