Dbms Lab Task Dist
Dbms Lab Task Dist
Some Commands:
CREATE : to create objects in database
ALTER : alters the structure of database
DROP : delete objects from database
RENAME : rename an objects
Declarative DMLs are usually easier to learn and use than procedural DMLs. However, since
a user does not have to specify how to get the data, the database system has to figure out an
efficient means of accessing data.
Some Commands :
Example of SQL query that finds the names of all instructors in the History department :
Page No-2
DBMS Lab Manual
DDL DML
It stands for Data Definition Language. It stands for Data Manipulation Language.
It is used to create database schema and can be It is used to add, retrieve, or update the data.
used to define some constraints as well.
It basically defines the column (Attributes) of the It adds or updates the row of the table. These
table. rows are called tuples.
It doesn’t have any further classification. It is further classified into Procedural and Non-
Procedural DML.
Basic commands present in DDL are CREATE, BASIC commands present in DML
DROP, RENAME, ALTER, etc. are UPDATE, INSERT, MERGE etc.
DDL does not use WHERE clause in its statement. While DML uses WHERE clause in its statement.
DDL is used to define the structure of a database. DML is used to manipulate the data within the
database.
DDL is used to create and modify database objects DML is used to perform operations on the data
like tables, indexes, views, and constraints. within those database objects.
DDL statements are typically executed less DML statements are frequently executed to
frequently than DML statement manipulate and query data.
DDL statements are typically executed by database DML statements are typically executed by
administrators. application developers or end-users.
DDL statements are not used to manipulate data DML statements are used to manipulate data
directly. directly.
The database’s contents are not altered by DDL DML commands alter the database’s contents.
commands.
Examples of DDL commands: CREATE TABLE, Examples of DML commands: SELECT, INSERT,
ALTER TABLE, DROP TABLE, TRUNCATE UPDATE, DELETE, and MERGE.
TABLE, and RENAME TABLE.
Data types
String Data Types
Data type Description Max size Storage
varchar(n) Variable width character string 8,000 characters 2 bytes + number of chars
varchar(max) Variable width character string 1,073,741,824 chars 2 bytes + number of chars
text Variable width character string 2GB of text data 4 bytes + number of chars
Page No-3
DBMS Lab Manual
Numeric Data Types
Data type Description Storage
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308.The n 4 or 8 bytes
parameter indicates whether the field should hold 4 or 8 bytes. float (24)
holds a 4-byte field and float (53) holds an 8-byte field. Default value of n
is 53.
Note: the date types are chosen for a column when you create a new table in your database!
Page No-4
DBMS Lab Manual
Other Data Types
Data type Description
Page No-5
DBMS Lab Manual
ALTER TABLE Statement
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
To add a column in a table, use the following syntax:
ALTER TABLE table_name ADD column_name datatype
LAB TASK: 1
1. Create a database named ‘ADVANCED’ and create tables as following schema:
Student (SID,Name,RN,Batch)
Teacher (TID,Name, Faculty)
2. Insert any five records in each table
3. Display all records.
4. Display only ID and Name from student table.
5. Display Name and faculty from Teacher table.
6. Remove ‘RN’ attribute from student relation.
7. Add ‘salary’ attribute to teacher relation.
8. Copy ID and name attribute to new relation ‘info_student’.
9. Delete all contents from info_student relation
10. Delete table name info_student.
11. Delete database that you created in Lab1.
Page No-6
DBMS Lab Manual
Lab 2 Constraints, Integrity and Where clause
SQL Constraints:
Constraints are the rules enforced on data columns on table. These 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
database.
Constraints could be column level or table level. Column level constraints are applied only to
one column, whereas table level constraints are applied to the whole table.
Following are commonly used constraints available in SQL:
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/record in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.
INDEX: Use to create and retrieve data from the database very quickly.
NOT NULL Constraint:
By default, a column can hold NULL values. If you do not want a column to have a NULL value,
then you need to define such constraint on this column specifying that NULL is now not allowed
for that column.
A NULL is not the same as no data, rather, it represents unknown data.
create table Student (sid int not null, Name varchar(20) not null,
RN int not null, Batch varchar(10) not null primary key (sid)
);
DEFAULT Constraint:
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
create table teachers (tid int not null, Name varchar(20) not null,
salary decimal(10,2) DEFAULT 35000,
faculty varchar(20) not null primary key (tid)
);
Drop Default Constraint.
To drop DEFAULT constraint, use the following
Alter table column salary drop default;
UNIQUE Constraint:
The UNIQUE Constraint prevents two records from having identical values in a particular
column. In the CUSTOMERS table, for example, you might want to prevent two or more people
from having identical age.
create table Student (sid int not null, Name varchar(20) not null,
RN int not null unique, Batch varchar(10) not null primary key (sid)
);
You can also use following syntax, which supports naming the constraint in multiple columns as
well
Alter table student add constraint myconstraint unique (rn, name);
Page No-7
DBMS Lab Manual
Drop a unique constraint:
To drop a unique constraint. Using following SQL command:
Alter table student drop constraint myconstraint;
PRIMARY Key:
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When
multiple fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having the
same value of that field(s). Note: You would use these concepts while creating database tables.
Create Primary Key: syntax:
create table customers (cid int not null, name varchar (20) not null,
age int not null, address char (25), salary decimal (18,2),
primary key(cid) );
For defining a primary key constraint on multiple columns, use the following syntax:
create table customers (cid int not null, name varchar (20) not null,
age int not null, address char (25), salary decimal (18,2),
primary key(cid, name) );
To create a Primary Key constraint on the CID and Name columns when the CUSTOMERS
table already exists, use the following command:
Alter table customers add constraint PKCustid primary key (cid, name);
Delete Primary key:
Alter table table name Drop constraint constraint_name;
FOREIGN Key:
A foreign key is a key used to link two tables together. This is sometimes called a referencing
key. Foreign Key is a column or a combination of columns whose values match a Primary Key in
a different table. The relationship between 2 tables matches the Primary Key in one of the tables
with a Foreign Key in the second table. If a table has a primary key defined on any field(s), then
you cannot have two records having the same value of that field(s).
Example: Consider the structure of the two tables as follows:
Customers table:
create table customers (cid int not null, name varchar (20) not null,
age int not null, address char (25), salary decimal (18,2),
primary key(cid));
Order Table
Create table orders
(OID int not null, date datetime, customers_id int references Customers
(CID), amount decimal (18,2), primary key (OID)
);
Foreign key assign by
ALTER TABLE Orders
ADD FOREIGN KEY (OID) REFERENCES Customers(CID);
Page No-8
DBMS Lab Manual
= Equal Age=18
Page No-9
DBMS Lab Manual
LIKE Search for a pattern using Name like ‘S%’ for starting with S. eg. Shaym, Sagar, Sita,
Percentage ( % ) and Underscore Santosh, etc.
( _ ). Name like ‘%a’ for ending with a. eg. Sita, Gita, Rita,
Narendra, Dipendra, etc.
Salary like ‘2___3’ for salary start with 2 and ends with 3.
Operator Description
Page No-10
DBMS Lab Manual
AND and OR Operators
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];
The OR Operator: The OR operator is used to combine multiple conditions in an SQL
statement's WHERE clause.
Syntax:
SELECT column1, column2, columnN FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates. The BETWEEN operator is inclusive: begin and end values are included.
Example
Selects all products with a price between 10 and 20:
select * from products where price between 10 and 20;
NOT BETWEEN
To display the products outside the range of the previous example, use NOT BETWEEN:
Example
select * from products
where price not between 10 and 20;
BETWEEN with IN
The following SQL statement selects all products with a price between 10 and 20. In addition,
the CategoryID must be either 1,2, or 3:
Example
select * from products
where price between 10 and 20
and categoryid in (1,2,3);
The following SQL statement selects all products with a ProductName between Carnarvon
Tigers and Chef Anton's Cajun Seasoning:
Example
select * from products
where productname between "carnarvon tigers" and "chef anton's cajun seasoning"
order by productname;
Page No-11
DBMS Lab Manual
NOT BETWEEN Text Values
The following SQL statement selects all products with a ProductName not between Carnarvon
Tigers and Mozzarella di Giovanni:
Example
select * from products
where productname not between 'carnarvon tigers' and 'mozzarella di giovanni'
order by productname;
BETWEEN Dates
The following SQL statement selects all orders with an OrderDate between '01-July-1996' and
'31-July-1996':
Example
select * from orders
where orderdate between #07/01/1996# and #07/31/1996#;
OR:
Example
select * from orders
where orderdate between '1996-07-01' and '1996-07-31';
IN Operator
The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a
shorthand for multiple OR conditions.
Example Return all customers from 'Germany', 'France', or 'UK'
select * from customers
where country in ('germany', 'france', 'uk');
Syntax
select column_name(s)
from table_name
where column_name in (value1, value2, ...);
NOT IN
By using the NOT keyword in front of the IN operator, you return all records that are NOT any of
the values in the list.
Example Return all customers that are NOT from 'Germany', 'France', or 'UK':
select * from customers
where country not in ('germany', 'france', 'uk');
IN (SELECT)
You can also use IN with a subquery in the WHERE clause. With a subquery you can return all
records from the main query that are present in the result of the subquery.
Example
Return all customers that have an order in the Orders table:
SELECT * FROM Customers
WHERE CustomerID IN (SELECT CustomerID FROM Orders);
NOT IN (SELECT)
The result in the example above returned 74 records, that means that there are 17 customers
that haven't placed any orders. Let us check if that is correct, by using the NOT IN operator.
Page No-12
DBMS Lab Manual
Example
Return all customers that have NOT placed any orders in the Orders table:
select * from customers
where customerid not in (select customerid from orders);
The ANY operator: returns a boolean value as a result, returns TRUE if ANY of the subquery
values meet the condition, ANY means that the condition will be true if the operation is true for
any of the values in the range.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
The ALL operator: ALL means that the condition will be true only if the operation is true for all
values in the range. returns a boolean value as a result, returns TRUE if ALL of the subquery
values meet the condition, is used with SELECT, WHERE and HAVING statements
ALL Syntax With SELECT
SELECT ALL column_name(s)
FROM table_name
WHERE condition;
ALL Syntax With WHERE or HAVING
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
SQL ANY Examples
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails
table has Quantity equal to 10 (this will return TRUE because the Quantity column has some
values of 10):
Example
select productname
from products
where productid = any
(select productid
from orderdetails
where quantity = 10);
Page No-13
DBMS Lab Manual
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails
table has Quantity larger than 99 (this will return TRUE because the Quantity column has some
values larger than 99):
Example
select productname
from products
where productid = any
(select productid
from orderdetails
where quantity > 99);
The following SQL statement lists the ProductName if it finds ANY records in the OrderDetails
table has Quantity larger than 1000 (this will return FALSE because the Quantity column has no
values larger than 1000):
Example
select productname
from products
where productid = any
(select productid
from orderdetails
where quantity > 1000);
SQL ALL Examples The following SQL statement lists ALL the product names:
Example
select all productname
from products
where true;
The following SQL statement lists the ProductName if ALL the records in the OrderDetails table
has Quantity equal to 10. This will of course return FALSE because the Quantity column has
many different values (not only the value of 10):
Example
select productname
from products
where productid = all
(select productid
from orderdetails
where quantity = 10);
SQL SOME Statement:
select * from book
where price > some (select price from book where price > 400);
EXISTS Operator: The EXISTS operator is used to test for the existence of any record in a
subquery, returns TRUE if the subquery returns one or more records.
EXISTS Syntax
select column_name(s) from table_name
where exists (select column_name from table_name where condition);
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
And a selection from the "Suppliers" table:
Page No-14
DBMS Lab Manual
Supplier Supplier Name Contact Name Address City Postal Code Country
ID
2 New Orleans Cajun Shelley Burke P.O. Box 78934 New Orleans 70117 USA
Delights
3 Grandma Kelly's Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA
Homestead
4 Tokyo Traders Yoshi Nagase 9-8 Sekimai Musashino-shi Tokyo 100 Japan
SQL EXISTS Examples :The following SQL statement returns TRUE and lists the suppliers
with a product price less than 20:
Example
select suppliername from suppliers
where exists (select productname from products where products.supplierid =
suppliers.supplierid and price < 20);
The following SQL statement returns TRUE and lists the suppliers with a product price equal to
22:
Example
select suppliername from suppliers
where exists (select productname from products where products.supplierid =
suppliers.supplierid and price = 22);
SQL Expressions
An expression is a combination of one or more values, operators, and SQL functions that
evaluate to a value. SQL EXPRESSIONs are like formulas and they are written in query
language. You can also use them to query the database for specific set of data.
Syntax:
SELECT column1, column2, columnN FROM table_name
WHERE [CONDITION|EXPRESSION];
Example 1:
SELECT COUNT(*) AS "RECORDS" FROM book;
Output:
Example 2:
SELECT BID, Price,
CASE
WHEN price > 500 THEN 'The Price is greater than 500'
WHEN price = 500 THEN 'The price is 500'
ELSE 'The Price is under 500'
END AS Remarks
FROM book;
Output:
Page No-15
DBMS Lab Manual
The SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the
example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new
record.
Tip: To specify that the "Personid" column should start at value 10 and increment by 5, change
it to IDENTITY(10,5). To insert a new record into the "Persons" table, we will NOT have to
specify a value for the "Personid" column (a unique value will be added automatically):
BACKUP DATABASE Statement: The BACKUP DATABASE statement is used in SQL Server
to create a full back up of an existing SQL database.
Page No-16
DBMS Lab Manual
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath';
Example: The following SQL statement creates a full back up of the existing database "testDB"
to the D disk: Always back up the database to a different drive than the actual database. Then, if
you get a disk crash, you will not lose your backup file along with the database.
BACKUP DATABASE shyam
TO DISK = 'D:\back\testdiff.bak';
BACKUP WITH DIFFERENTIAL Statement: A differential back up only backs up the parts of
the database that have changed since the last full database backup.
Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Example: A differential back up reduces the back up time (since only the changes are backed
up).
BACKUP DATABASE shyam
TO DISK = 'D:\back\testdiff.bak'
WITH DIFFERENTIAL;
LAB TASK:2
1. Create the relations of tables as given below:
Student (sid, Name , RN , Batch)
Teacher (tid, ename, dateofjoin, salary)
Employee (eid, ename, dateofemployee, salary)
Booklist (isbn, name, publication)
Book(bid, bname, author, price)
Issues(IID,name,dateofissue)
2. Modify relation teacher and student
i. Set Tid as foreign key
ii. Set SID as primary key
iii. Delete RN attribute.
3. Set default value of ‘dateofemployee’ attribute as Jan 1, 2010.
4. Assign Bid and iid as foreign key.
5. Specify the data entry criteria on price of books must be less than 5000.
6. Ename, bname, name attribute of each relation must contain some value.
7. Insert any 4 records in each relation.
8. Display all records from all relations.
9. Display eid and ename of all employes whose salary is less than 30000.
10. Display all record of book whose price ranges from 400 to 600.
11. Display all the records from booklist relation whose publication name starts from ‘E’ eg Ekta.
12. Display all records from employee table whose name ends with ‘a’ eg Sita, Geeta etc.
13. Display sid and name from student table whose name exactly consist of 5 characters.
14. Display all records from employee table where name starts with ‘P’ and salary greater than
25000.
15. Display all records from book table where either bid lies in range 2003 to 2004 or price range in
350 to 600.
16. Display isbn number and bookname where booklist must not contain isbn no. 2003
Page No-17
DBMS Lab Manual
Lab 3 Update Query, Delete query & Sub Query
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:
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:
select * from issues;
update issues set bid=iid+100;
select * from issues;
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:
Delete from table_name where [condition];
You can combine N number of conditions using AND or OR operators.
Example:
Delete from customers where id = 6;
SQL TRUNCATE TABLE
The SQL TRUNCATE TABLE command is used to delete complete data from an existing table. You
can also use DROP TABLE command to delete complete table but it would remove complete table
structure form the database and you would need to re-create this table once again if you wish you store
some data.
Syntax:
The basic syntax of TRUNCATE TABLE is as follows:
truncate table table_name;
Example:
Truncate Table Customers
Output:
SELECT * FROM CUSTOMERS;
Page No-18
DBMS Lab Manual
iii. An ORDER BY cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the
ORDER BY in a subquery.
iv. Subqueries that return more than one row can only be used with multiple value
operators, such as the IN operator.
v. The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
vi. A subquery cannot be immediately enclosed in a set function.
vii. The BETWEEN operator cannot be used with a subquery; however, the BETWEEN
operator can be used within the subquery.
Subqueries with the SELECT Statement:
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows:
Syntax:
SELECT column_name [, column_name ] FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ] [WHERE] condition);
Example:
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS
WHERE SALARY > 4500) ;
Subqueries with the INSERT Statement:
Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can
be modified with any of the character, date or number functions.
Syntax:
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]
Example:
INSERT INTO CUSTOMERS
SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS) ;
SELECT Personid, FirstName + ' ' + LastName as Fullname , Age FROM Persons;
Lab Task 3
1. Find all the bookname, publication name and author name where publication name is “Ekta”.
2. Find the teachers name and faculty who issued book on 2080 Baishak 21.
3. Find the employee’s name whose salary is greater than 25000 and faculty is “computer”.
4. Add attribute bid on Issues relation.
5. Insert the data in bid column.
6. Find the Teacher’s name, and book name issued by the teacher whose name starts with “C”.
7. Update all salary by 10 %.
8. Update book name SQL Programming as DATABASE.
9. Update the salary of all employee by 20% whose salary is less than 26000.
10. Provide 5% increment to all salaries whose salary is greater than 20000 and 20% increment
in rest of salaries. (use CASE WHEN <CONDITION>THEN <STATEMENT> ELSE
<STATEMENT> END).
11. Delete the records from employee table whose eid is 111.
12. Use sub query to find all teachers name and faculty whose date of employee is 2016-05-25.
13. Use sub query to find all the book name and author name whose publication is “Ekta”.
Page No-20
DBMS Lab Manual
Lab 4
Introduction to Joins & Built in Functions in SQL, Group by clause, Having clause
Types of Joins
INNER JOIN: Returns records that have matching values in both tables
Syntax:
SELECT column_name(s) FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;
Example:
SELECT bname,price FROM Book INNER JOIN Booklist ON Book.bid= booklist.isbn;
Output:
LEFT JOIN: Returns all records from the left table, and the matched records from the right table
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example:
SELECT * FROM Book
left JOIN Booklist
ON book.author = booklist.publication;
Output
Page No-21
DBMS Lab Manual
RIGHT JOIN: Returns all records from the right table, and the matched records from the left
table
Syntax:
SELECT column_name(s) FROM table1 RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example:
SELECT * FROM Book right JOIN Booklist ON book.author = booklist.publication;
Output:
CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the cartesian product of the sets of records
from the two or more joined tables. Thus, it equates to an inner join where the join-condition
always evaluates to True or where the join condition is absent from the statement.
Syntax:
SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ]
Example:
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS, ORDERS;
Syntax:
SELECT column_name(s) FROM table1 CROSS JOIN table2;
Example1:
SELECT Book.bname, booklist.name FROM Book
CROSS JOIN Booklist WHERE Book.bid=booklist.isbn;
Output1:
Example2:
SELECT * FROM Book CROSS JOIN Booklist WHERE Book.bid=booklist.isbn;
Output2:
Page No-22
DBMS Lab Manual
Group By clause:
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:
Select name, sum(salary) from customers
Group by name;
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:
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:
Select * from customers Order by name desc;
TOP Clause
The SQL TOP clause is used to fetch a TOP N number or X percent records from a table.Note:
All the databases do not support TOP clause. For example MySQL supports LIMIT clause to
fetch limited number of records and Oracle uses ROWNUM to fetch limited number of records.
Syntax:
Select top number|percent column_name(s)
From table_name where [condition]
Example:
Select top 3 * from customers;
HAVING CLAUSE
The HAVING clause enables you to specify conditions that filter which group results appear in the final
results. The WHERE clause places conditions on the selected columns, whereas the HAVING clause
places conditions on groups created by the GROUP BY clause. The HAVING clause must follow the
GROUP BY clause in a query and must also precedes the ORDER BY clause if used. The following is
the syntax of the SELECT statement, including the HAVING clause:
Syntax:
select column1, column2 from table1, table2
where [ conditions ]
group by column1, column2
having [ conditions ] order by column1, column2
Example: display record for which similar age count would be more than or equal to 2:
select * from customers
Page No-23
DBMS Lab Manual
group by age
having count(age) >= 2;
Built-in functions
SQL has many built-in functions for performing processing on string or numeric data. Following
is the list of all useful SQL built-in functions:
COUNT Function - The SQL COUNT aggregate function is used to count the number of rows in
a database table.
MAX Function - The SQL MAX aggregate function allows us to select the highest (maximum)
value for a certain column.
MIN Function - The SQL MIN aggregate function allows us to select the lowest (minimum) value
for a certain column.
AVG Function - The SQL AVG aggregate function selects the average value for certain table
column.
SUM Function - The SQL SUM aggregate function allows selecting the total for a numeric
column.
SQRT Functions - This is used to generate a square root of a given number.
RAND Function - This is used to generate a random number using SQL command.
CONCAT Function - This is used to concatenate any string inside any SQL command.
Numeric Functions - Complete list of SQL functions required to manipulate numbers in SQL.
String Functions - Complete list of SQL functions required to manipulate strings in SQL.
COUNT Function :COUNT function is the simplest function and very useful in counting the
number of records , which are expected to be returned by a SELECT statement.
Example:
select count(*) from employee ;
Similarly, if you want to count the number of records for Nepal, then it can be done as follows:
select count(*) from employee where country= ‘nepal’;
MAX Function : MAX function is used to find out the record with maximum value among a
record set.
Example:
select * from Persons
output:
MIN Function : MIN function is used to find out the record with minimum value among a record
set.
select min(age) as MinimumAge from Persons;
AVG Function :AVG function is used to find out the average of a field in various records.
select avg(age)as Average_Age from Persons;
Page No-24
DBMS Lab Manual
SUM Function :SUM function is used to find out the sum of a field in various records.
select sum(age)as Sum_Of_Age from Persons;
SQRT Function :SQRT function is used to find out the square root of any number. You can Use
SELECT statement to find out square root of any number.
select sqrt(25) as SQRT_of_25;
ABS(X)
The ABS() function returns the absolute value of X.
select abs(-25) as 'Absolute_of_-25';
Lab Task: 4
1. Sort the employee records in descending order.
2. Sort name and publication name in ascending order.
3. Display top three records from teachers relation.
4. Display the sum of salaries of all employees.
5. Display the minimum salary of employee.
6. Display the average price of book written by same author.
7. Display publication name and number of books published by it from book list relation
publication wise.
8. Display the bid and bname of books whose price is greater than average prices of book.
9. Find the bid, bname and author in ascending order where author name is started by “s”.
10. Find the teachers name and book taken by him. The teacher’s salary who takes the book
should be the maximum salary.
11. Find the authors name who have written more than one book.
Page No-25
DBMS Lab Manual
Union & Creating Views
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order
UNION Syntax
select column_name(s) from table1
union
select column_name(s) from table2;
UNION ALL Syntax : The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL:
select column_name(s) from table1
union all
select column_name(s) from table2;
Note: The column names in the result-set are usually equal to the column names in the
first SELECT statement.
Example
select city from customers
union
select city from suppliers
order by city;
Note: If some customers or suppliers have the same city, each city will only be listed once,
because UNION selects only distinct values. Use UNION ALL to also select duplicate values!
SQL UNION ALL Example: The following SQL statement returns the cities (duplicate values
also) from both the "Customers" and the "Suppliers" table:
Example
select city from customers
union all
select city from suppliers
order by city;
SQL UNION WITH WHERE: The following SQL statement returns the German cities (only
distinct values) from both the "Customers" and the "Suppliers" table:
Example
select city, country from customers where country='germany'
union
select city, country from suppliers where country='germany'
order by city;
SQL UNION ALL With WHERE: The following SQL statement returns the German cities
(duplicate values also) from both the "Customers" and the "Suppliers" table:
Example
select city, country from customers
where country='germany' union all
select city, country from suppliers
where country='germany' order by city;
Page No-26
DBMS Lab Manual
Another UNION Example:
Example
SELECT 'Customer' AS Type, ContactName, City, Country FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country FROM Suppliers;
SQL UNION
The following SQL statement returns the only distinct values from both the tables.
SELECT 'Book' AS Type, bName, author, price FROM Book
UNION
SELECT 'Publication', Publication, name, isbn FROM Booklist;
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in very similar way as you use them
in normal SQL SELECT query.
SQL CREATE VIEW Examples-The following SQL creates a view that shows all customers
from Kathmandu:
Example
CREATE VIEW [Kathmandu Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE city = 'Kathmandu';
Page No-28
DBMS Lab Manual
Example
SELECT * FROM [Products Above Average Price];
Lab Task: 5
1. Perform join operation on teacher and employee table and display the Ename , Faculty and
salary.
2. Perform left join on table book list and book table.
3. Perform right join on booklist and book table.
4. Perform Full join on student and issues table.
5. Display those employees name and salary whose name starts with ‘s’ and whose name consist
‘a’ as sub string.
6. Display name of the employee who is also a teacher.
7. Display all employees name except the name who are teachers.
8. Create a view Employee-view which consist of eid, ename , salary as attributes.
9. Insert a new record in recently created view. And also display the contents of primary table.
10. Delete the information from view where salary are less than 29000.
Page No-29
DBMS Lab Manual
Stored Procedures &Inbuilt Functions
What is a Stored Procedure?
A stored procedure is a prepared SQL code that you can save, so the code can be reused over
and over again. So if you have an SQL query that you write over and over again, save it as a
stored procedure, and then just call it to execute it. You can also pass parameters to a stored
procedure, so that the stored procedure can act based on the parameter value(s) that is passed.
Stored Procedure Syntax
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXEC procedure_name;
We could change this stored procedure and use the ISNULL function to get around this. So if a
value is passed it will use the value to narrow the result set and if a value is not passed it will
return all records. (Note: if the City column has NULL values this will not include these values.
You will have to add additional logic for City IS NULL)
CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City =
ISNULL(@City,City) GO
Multiple Parameters
Setting up multiple parameters is very easy to do. You just need to list each parameter and the
data type separated by a comma as shown below.
CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1
nvarchar(60) = NULL
AS
SELECT *
Page No-31
DBMS Lab Manual
FROM AdventureWorks.Person.Address
WHERE City = ISNULL(@City,City)
AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1
,AddressLine1) + '%' GO
To execute this you could do any of the following:
EXEC uspGetAddress @City = 'Calgary'
--or
EXEC uspGetAddress @City = 'Calgary', @AddressLine1 = 'A'
--or
EXEC uspGetAddress @AddressLine1
= 'Acardia' -- etc...
Example:
CREATE PROCEDURE show4 @nam
varchar(30),@idi int AS
SELECT *
FROM example
WHERE name like @nam
+'%' or id=@idi GO
drop procedure
show4 show4
@nam
='s',@idi=12
Deleting a SQL Server stored procedure
Dropping Single Stored Procedure
To drop a single stored procedure you use the DROP PROCEDURE or DROP PROC
command as follows.
DROP PROCEDURE uspGetAddress
GO
-- or
DROP PROC uspGetAddress
GO
-- or
DROP PROC dbo.uspGetAddress -- also specify the schema
Dropping Multiple Stored Procedures
To drop multiple stored procedures with one command you specify each procedure separated
by a comma as shown below.
DROP PROCEDURE uspGetAddress, uspInsertAddress,
uspDeleteAddress GO
-- or
DROP PROC uspGetAddress, uspInsertAddress, uspDeleteAddress
GO
Page No-32
DBMS Lab Manual
Do not use sp_ as a prefix
One of the things you do not want to use as a standard is "sp_". This is a standard naming
convention that is used in the master database. If you do not specify the database where the
object is, SQL Server will first search the master database to see if the object exists there and
then it will search the user database. So avoid using this as a naming convention.
Standardize on a Prefix
It is a good idea to come up with a standard prefix to use for your stored procedures. As
mentioned above do not use "sp_", so here are some other options.
• usp_
• sp
• usp
• etc...
To be honest it does not really matter what you use. SQL Server will figure out that it is a
stored procedure, but it is helpful to differentiate the objects, so it is easier to manage.
So a few examples could be:
• spInsertPerson
• uspInsertPerson
• usp_InsertPerson
• InsertPerson
Again this is totally up to you, but some standard is better than none.
Page No-33
DBMS Lab Manual
Using comments in a SQL Server stored procedure
SQL Server offers two types of comments in a stored procedure; line comments and block
comments. The following examples show you how to add comments using both techniques.
Comments are displayed in green in a SQL Server query window.
Line Comments
To create line comments you just use two dashes "--" in front of the code you want to comment.
You can comment out one or multiple lines with this technique.
In this example the entire line is commented out.
-- this procedure gets a list of addresses based
-- on the city value that is passed
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City =
@City GO
This next example shows you how to put the comment on the same line.
-- this procedure gets a list of addresses based on the city value that is passed
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City -- the @City parameter value will narrow the search criteria GO
Block Comments
To create block comments the block is started with "/*" and ends with "*/". Anything within that
block will be a comment section.
/*
-this procedure gets a list of addresses based
on the city value that is passed
-this procedure is used by the HR system */
CREATE PROCEDURE uspGetAddress @City
nvarchar(30) AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City
GO
Combining Line and Block Comments
You can also use both types of comments within a stored procedure.
/*
-this procedure gets a list of addresses based
on the city value that is passed
-this procedure is used by the HR system */
CREATE PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City = @City -- the @City parameter value will narrow the search criteria GO
Page No-34
DBMS Lab Manual
Returning stored procedure parameter values to a calling stored procedure
In a previous topic we discussed how to pass parameters into a stored procedure, but another
option is to pass parameter values back out from a stored procedure. One option for this may
be that you call another stored procedure that does not return any data, but returns parameter
values to be used by the calling stored procedure.
Explanation
Setting up output paramters for a stored procedure is basically the same as setting up input
parameters, the only difference is that you use the OUTPUT clause after the parameter name
to specify that it should return a value. The output clause can be specified by either using the
keyword "OUTPUT" or just "OUT".
Simple Output
CREATE PROCEDURE uspGetAddressCount @City nvarchar(30),
@AddressCount int OUTPUT AS
SELECT @AddressCount = count(*)
FROM
AdventureWorks.Person.Address
WHERE City = @City
Or it can be done this way:
CREATE PROCEDURE uspGetAddressCount @City nvarchar(30),
@AddressCount int OUT AS
SELECT @AddressCount = count(*)
FROM AdventureWorks.Person.Address
WHERE City = @City
To call this stored procedure we would execute it as follows. First we are going to declare a
variable, execute the stored procedure and then select the returned valued.
DECLARE @AddressCount int
EXEC uspGetAddressCount @City = 'Calgary', @AddressCount = @AddressCount
OUTPUT SELECT @AddressCount
This can also be done as follows, where the stored procedure parameter names are not
passed.
DECLARE @AddressCount int
EXEC uspGetAddressCount 'Calgary', @AddressCount OUTPUT
SELECT @AddressCount
Page No-35
DBMS Lab Manual
WHERE City =
@City GO
Let's say we want to change this to do a LIKE instead of an equals.
To change the stored procedure and save the updated code you would use the ALTER
PROCEDURE command as follows.
ALTER PROCEDURE uspGetAddress @City nvarchar(30)
AS
SELECT *
FROM AdventureWorks.Person.Address
WHERE City LIKE @City +
'%' GO
Now the next time that the stored procedure is called by an end user it will use this new logic.
Sql date time functions:
• DateTime Function in SQL Server
• GETDATE()
• DATEPART()
• DATEDIFF()
• DATENAME()
• DAY()
• MONTH() YEAR()
GETDATE() is very common used method which returns exact date time from the system. It
does not accept any parameter. Just call it like simple function.
Example:
SELECT getdate()
DATEADD()
DATEADD() is used to add or subtract datetime. Its return a new datetime based on the added
or subtracted interval.
General Syntax
DATEADD(datepart, number, date)
datepart is the parameter that specifies on which part of the date to return a new value. Number
parameter is used to increment datepart.
Example:
SELECT getdate();
SELECT DATEADD(day, 5,getdate() ) AS
NewTime Output:
2015-08-12 09:18:18.080
2015-08-17 09:18:18.080
DATEPART()
DATEPART() is used when we need a part of date or time from a datetime variable. We can
use DATEPART() method only with select command.
Syntax
DATEPART(datepart, date)
Example:
SELECT DATEPART(year, GETDATE()) AS 'Year'
SELECT DATEPART(hour, GETDATE()) AS 'Hour’
Page No-36
DBMS Lab Manual
DATEDIFF()
DATEDIFF() is very common function to find out the difference between two DateTime elements.
Syntax
DATEDIFF(datepart, startdate, enddate)
Example:
SELECT DATEDIFF(day, @Date1, @Date2) AS
DifferenceOfDay
DATENAME()
DATENAME() is very common and most useful function to find out the date name from the
datetime value.
-- Get Today
SELECT DATENAME(dw, getdate()) AS 'Today Is'
-- Get Mont name
SELECT DATENAME(month, getdate()) AS
'Month'
DAY()
DAY() is used to get the day from any date time object.
Example:
SELECT DAY(getdate()) AS 'DAY'
Output :
DAY
-----------
12
MONTH()
SELECT MONTH(getdate()) AS 'Month'
YEAR()
SELECT YEAR(getdate()) AS 'Year'
String Functions
• ASCII()
• CHAR()
• LEFT()
• RIGHT()
• LTRIM()
• RTRIM()
• REPLACE()
• QUOTNAME()
• REVERSE()
• CHARINDEX()
• PATINDEX()
• LEN()
• STUFF()
• SUBSTRING()
• LOWER/UPPER()
ASCII()
Returns the ASCII code value of the leftmost character of a character expression.
Page No-37
DBMS Lab Manual
Syntax ASCII (CHARACTER_EXPRESSION)
SELECT ASCII('K'); returns 107
CHAR()
Converts an int ASCII code to a character.
Syntax
CHAR ( integer_expression )
Arguments: integer_expression: Is an integer from 0 through 255. NULL is returned if the
integer expression is not in this range.
LEFT()
Returns the left most characters of a string.
Syntax
LEFT(string, length)
string
Specifies the string from which to obtain the left-most characters.
length
Specifies the number of characters to obtain.
Example:
SELECT LEFT('kathmandu',5)
Output:
Kathm
RIGHT()
Returns the right most characters of a string.
Syntax
RIGHT(string, length)
string
Specifies the string from which to obtain the left-most characters.
length
Specifies the number of characters to obtain.
LTRIM()
Returns a character expression after it removes leading blanks.
Example :
SELECT LTRIM(' Md. Ashok’)
Output :
Md. Ashok
RTRIM()
Returns a character string after truncating all trailing blanks.
Example :
SELECT RTRIM('Md. barsha ')
Output:
Md. Barsha
REVERSE()
Returns a character expression in reverse order.
Example :
SELECT REVERSE(ename) FROM Employee;
Page No-38
DBMS Lab Manual
CHARINDEX
CharIndex returns the first occurance of a string or characters within another string. The
Format of CharIndex is given Below:
CHARINDEX ( expression1 , expression2 [ , start_location ] )
Here expression1 is the string of characters to be found within expression2. So if you want to
search ij within the word Abhijit, we will use ij as expression1 and Abhijit as expression2. start
location is an optional integer argument which identifies the position from where the string will
be searched. Now let us look into some examples :
SELECT CHARINDEX('rma', 'Ramesh Sharma', 3) AS MatchPosition;
SELECT CHARINDEX('SQL', 'Microsoft SQL Server')
OUTPUT:
11
So it will start from 1 and go on searching until it finds the total string element searched, and
returns its first position. The Result will be 0 if the searched string is not found.
EXAMPLE:
SELECT CHARINDEX('SQL', 'Microsoft SQL server has a great SQL Engine',12)
So in the above example we can have the Output as 34 as we specified the StartLocation as
12, which is greater than initial SQL position(11).
PATINDEX
As a contrast Patindex is used to search a pattern within an expression. The Difference
between CharIndex and PatIndex is the later allows WildCard Characters.
PATINDEX ('%pattern%' , expression)
Here the first argument takes a pattern with wildcard characters like '%' (meaning any string) or '_'
(meaning any character).
For Example
SELECT PATINDEX('%ani%', 'ShyamManiAcharya');
Output:
7
LEN
Len is a function which returns the length of a string. This is the most common and simplest
function that everyone use. Len Function excludes trailing blank spaces.
SELECT LEN('ABHISHEK IS WRITING THIS')
This will output 24, it is same when we write LEN('ABHISHEK IS WRITING THIS ') as LEN doesnt take
trailing spaces in count.
SUBSTRING
Substring returns the part of the string from a given character expression. The general syntax of
Substring is as follows :
LOWER / UPPER
Another simple but handy function is Lower / UPPER. The will just change case of a string
expression. For Example,
SELECT UPPER('this is Lower TEXT')
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains
rows and columns, just like a real table. The fields in a view are fields from one or more real
tables in the database. You can add SQL statements and functions to a view and present the
data as if the data were coming from one single table. A view is created with the CREATE
VIEW statement.
Syntax
create view view_name as
select column1, column2, ...
from table_name
where condition;
Example
create view [above average] as
select book.bid,book.bname, price
from book
where price > (select avg(price) from book);
Using views by
select * from [Above Average];
CREATE PROCEDURE
The CREATE PROCEDURE command is used to create a stored procedure. A stored
procedure is a prepared SQL code that you can save, so the code can be reused over and over
again.
Example
create procedure books
as
select * from book
go;
Using procedure as follows:
exec books
Page No-40