0% found this document useful (0 votes)
148 views28 pages

Lab Manual 2

The document discusses SQL commands like CREATE, ALTER, DROP, INSERT, UPDATE, DELETE and TRUNCATE. It provides examples of creating a table and inserting, updating, deleting and retrieving data from the table. It also discusses different types of SQL statements and basic SQL concepts.

Uploaded by

maheen.ehsaan.19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views28 pages

Lab Manual 2

The document discusses SQL commands like CREATE, ALTER, DROP, INSERT, UPDATE, DELETE and TRUNCATE. It provides examples of creating a table and inserting, updating, deleting and retrieving data from the table. It also discusses different types of SQL statements and basic SQL concepts.

Uploaded by

maheen.ehsaan.19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

LAB MANUAL

DATABASE
SYSTEM LAB
Hina Farooq
Course Title: Database System Lab
SQL
SQL, or Structured Query Language, is a standardized language for managing relational
databases. It includes commands for querying, updating, and controlling access to data. With its
concise syntax and powerful capabilities, SQL is essential for database management,
development, and analysis.
Experiment No: 1

Title: Implementation of DDL commands of SQL with suitable examples


• Create table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
BirthDate DATE,
HireDate DATE NOT NULL,
Salary DECIMAL(10, 2)
);

• Alter table
ALTER TABLE Employees ADD Email VARCHAR(100);

• Drop Table

1
DROP TABLE Employees;

DATA TYPES:

1. CHAR (Size)

2. VARCHAR (Size) / VARCHAR2 (Size)

3. NUMBER (P, S)

4. DATE

5. LONG
6. RAW
SQL language is sub-divided into several language elements, including:

▪ Clauses, which are in some cases optional, constituent components of statements and

queries.

▪ Expressions, which can produce either scalar values or tables consisting of columns and

rows of data.

▪ Predicates which specify conditions that can be evaluated to SQL three-valued logic

(3VL) Boolean truth values and which are used to limit the effects of statements and

queries, or to change program flow.

▪ Queries which retrieve data based on specific criteria.

▪ Statements which may have a persistent effect on schemas and data, or which may control

transactions, program flow, connections, sessions, or diagnostics.

▪ SQL statements also include the semicolon (";") statement terminator. Though not

required on every platform, it is defined as a standard part of the SQL grammar.

2
▪ Insignificant white space is generally ignored in SQL statements and queries, making it

easier to format SQL code for readability.

There are types of SQL statements. They are:

1. DATA DEFINITION LANGUAGE (DDL)

2. DATA MANIPULATION LANGUAGE (DML)

3. DATA Query LANGUAGE (DQL)

4. TRANSATIONAL CONTROL LANGUAGE (TCL)

5. DATA CONTROL LANGUAGE (DCL)

1. DATA DEFINITION LANGUAGE (DDL)

1. CREATE:

Syntax:
CREATE TABLE table_name (
column1 datatype constraints,
column2 datatype constraints,
...
columnN datatype constraints
);

Example:
CREATE TABLE Products (
ProductID INT PRIMARY KEY AUTO_INCREMENT,
ProductName VARCHAR(100) NOT NULL,
Category VARCHAR(50),

3
Price DECIMAL(8, 2) CHECK (Price > 0),
Stock INT DEFAULT 0
);

2. ALTER:
3. Syntax:
ALTER TABLE table_name ADD column_name datatype;

Example: ALTER TABLE Employees ADD Email VARCHAR(100);

4. DROP TABLE:
Syntax:
DROP TABLE table_name;

Example:
DROP TABLE Employees;

LAB PRACTICE ASSIGNMENT:

1. Create a table EMPLOYEE with following schema:

(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)


2. Add a new column; HIREDATE to the existing relation.
3. Change the datatype of JOB_ID from char to varchar2.
4. Change the name of column/field Emp_no to E_no.

4
5. Modify the column width of the job field of emp table

Solution
1. CREATE TABLE EMPLOYEE (

Emp_no INT PRIMARY KEY,


E_name VARCHAR(100),
E_address VARCHAR(255),
E_ph_no VARCHAR(15),
Dept_no INT,
Dept_name VARCHAR(100),
Job_id CHAR(10),
Salary DECIMAL(10, 2)
);
2. ALTER TABLE EMPLOYEE ADD HIREDATE DATE;
3. ALTER TABLE EMPLOYEE MODIFY Job_id VARCHAR2(10);
4. ALTER TABLE EMPLOYEE RENAME COLUMN Emp_no TO E_no;
5. ALTER TABLE EMPLOYEE MODIFY Job_id VARCHAR2(20);

Experiment No:2

Title : Implementation of DML commands of SQL with suitable examples


• Insert table
INSERT INTO employees (id, name, department, salary)
VALUES (101, 'John Doe', 'IT', 50000);

• Update table
UPDATE employees
SET salary = 55000
WHERE id = 101;

5
• Delete Table
DELETE FROM employees
WHERE id = 101;

Theory :

DATA MANIPULATION LANGUAGE (DML):


1. INSERT INTO:
a) Inserting a single record
Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example:
INSERT INTO employees (id, first_name, last_name, email)
VALUES (11, 'Maheen', 'Hamid', '[email protected]');

b) Inserting multiple records


Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES
(value1a, value2a, value3a, ...),
(value1b, value2b, value3b, ...),
Example:
INSERT INTO employees (id, first_name, last_name, email)
VALUES
(1, ‘Maheen', 'Hamid', '[email protected]'),

6
(2, 'Preehan', 'Malik', '[email protected]'),
(3, 'Seerat', 'Akbar', '[email protected]');

2. UPDATE-SET-WHERE:
Example:
UPDATE employees
SET email=’[email protected]'
WHERE id = 1;
3. DELETE-FROM:
Syntax:
DELETE FROM table_name
WHERE condition;
Example:
DELETE FROM employees
WHERE id = 1

4. TRUNCATE: This command will remove the data permanently. But structure will not be removed.

Syntax:
TRUNCATE TABLE <Table name>
Example
TRUNCATE TABLE student;

Difference between Truncate & Delete:-

Purpose:
DELETE: Removes specific rows based on a condition.
TRUNCATE: Removes all rows from a table.
Condition:
DELETE: Can use a WHERE clause to specify rows
TRUNCATE: Does not allow a WHERE clause.

7
Logging:
DELETE: Logs each row deletion, can be rolled back.
TRUNCATE: Minimally logs page deallocations, generally cannot be rolled back.
Performance:
DELETE: Slower for large datasets.
TRUNCATE: Faster due to page-level deallocation.
Triggers:
DELETE: Activates AFTER DELETE triggers.
TRUNCATE: Does not activate triggers.
Identity Reset:
DELETE: Does not reset identity columns.
TRUNCATE: Resets identity columns to the seed value.
Foreign Key Constraints:
DELETE: Can be used on tables with foreign keys.
TRUNCATE: Cannot be used if the table is referenced by foreign keys.

To Retrieve data from one or more tables.

1. SELECT FROM: To display all fields for all records.


Syntax:
SELECT * FROM relation_name;
Example :
SQL> select * from dept;
DEPTNO DNAME LOC
-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

2. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
selected set of records of a relation.

Syntax:
SELECT a set of fields FROM relation_name WHERE condition;
Example:

8
SQL> select * FROM dept WHERE deptno<=20;
DEPTNO DNAME LOC
------ ----------- ------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS

LAB PRACTICE ASSIGNMENT:


Create a table EMPLOYEE with following schema:
(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id , Salary)

Write SQL queries for following question:


1. Insert aleast 5 rows in the table.
2. Display all the information of EMP table.
3. Display the record of each employee who works in department D10.
4. Update the city of Emp_no-12 with current city as Nagpur.
5. Display the details of Employee who works in department MECH.
6. Delete the email_id of employee James.
7. Display the complete record of employees working in SALES Department.

Solution
1. CREATE TABLE EMPLOYEE (
Emp_no INT PRIMARY KEY,
E_name VARCHAR(50),
E_address VARCHAR(100),
E_ph_no VARCHAR(15),
Dept_no VARCHAR(10),
Dept_name VARCHAR(50),
Job_id INT,

9
Salary DECIMAL(10, 2)
);
2. INSERT INTO EMPLOYEE (Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,
Job_id, Salary)
VALUES
(1, 'John Doe', '123 Elm St, CityA', '123-456-7890', 'D10', 'SALES', 101, 50000.00),
(2, 'Jane Smith', '456 Oak St, CityB', '234-567-8901', 'D20', 'HR', 102, 55000.00),
(3, 'Emily Johnson', '789 Pine St, CityC', '345-678-9012', 'D10', 'SALES', 103, 60000.00),
(4, 'Michael Brown', '321 Birch St, CityD', '456-789-0123', 'D30', 'MECH', 104, 65000.00),
(5, 'James Wilson', '654 Maple St, CityE', '567-890-1234', 'D40', 'IT', 105, 70000.00);
3. SELECT * FROM EMPLOYEE;
4. SELECT * FROM EMPLOYEE WHERE Dept_no = 'D10';
5. UPDATE EMPLOYEE
SET E_address = 'Nagpur'
WHERE Emp_no = 12;
6. SELECT * FROM EMPLOYEE WHERE Dept_name = 'MECH';
7. DELETE FROM EMPLOYEE
WHERE E_name = 'James Wilson';
8. SELECT * FROM EMPLOYEE WHERE Dept_name = 'SALES';

Experiment No: 3

Title: Implementation of different types of functions with suitable examples.


▪ Number Function
SELECT ROUND(123.456, 2) AS rounded_number; -- Result: 123.46
SELECT CEIL(123.456) AS ceil_number; -- Result: 124

10
SELECT FLOOR(123.456) AS floor_number; -- Result: 123
▪ Aggregate Function
SELECT SUM(Salary) AS total_salary FROM EMPLOYEE;
SELECT AVG(Salary) AS average_salary FROM EMPLOYEE;
SELECT MAX(Salary) AS highest_salary FROM EMPLOYEE;
SELECT MIN(Salary) AS lowest_salary FROM EMPLOYEE;
SELECT COUNT(*) AS total_employees FROM EMPLOYEE;
▪ Character Function
SELECT UPPER(E_name) AS upper_name FROM EMPLOYEE;
SELECT LOWER(E_name) AS lower_name FROM EMPLOYEE;
SELECT SUBSTRING(E_name, 1, 3) AS substring_name FROM EMPLOYEE;
SELECT LENGTH(E_name) AS name_length FROM EMPLOYEE;
▪ Conversion Function
SELECT CAST(Salary AS VARCHAR(20)) AS salary_string FROM EMPLOYEE;
SELECT CONVERT(INT, '123') AS converted_number;
▪ ▪ Date Function
SELECT GETDATE() AS current_date_time;
SELECT DATEADD(DAY, 10, GETDATE()) AS date_plus_10_days;
SELECT DATEDIFF(DAY, '2023-01-01', GETDATE()) AS days_since_new_year;
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS formatted_date;

Objective:
NUMBER FUNCTION:

Aggregative operators: In addition to simply retrieving data, we often want to perform some
computation or summarization. SQL allows the use of arithmetic expressions. We now consider
a powerful class of constructs for computing aggregate values such as MIN and SUM.

1. Count:
Syntax:
SELECT COUNT(column_name) AS count_alias
FROM table_name
WHERE condition;
Example:

11
SELECT COUNT(Emp_no) AS total_employees

FROM EMPLOYEE

WHERE Dept_name = 'SALES';

2. SUM:
Syntax:
SELECT SUM(column_name) AS sum_alias
FROM table_name
WHERE condition;
Example:
SELECT SUM(Salary) AS total_salary
FROM EMPLOYEE;
3. AVG:
Syntax:
SELECT AVG(column_name) AS avg_alias
FROM table_name
WHERE condition;
Example:
SELECT AVG(Salary) AS average_salary
FROM EMPLOYEE;

4. MAX:
Syntax:
SELECT MAX(column_name) AS max_alias
FROM table_name
WHERE condition;
Example:
SELECT MAX(Salary) AS highest_salary
FROM EMPLOYEE;

12
5. MIN:
Syntax:
SELECT MIN(column_name) AS min_alias
FROM table_name
WHERE condition;
Example:
SELECT MIN(Salary) AS lowest_salary
FROM EMPLOYEE;

LAB PRACTICE ASSIGNMENT:

Create a table EMPLOYEE with following schema:

(Emp_no, E_name, E_address, E_ph_no, Dept_no, Dept_name,Job_id, Designation ,


Salary)

Write SQL statements for the following query.


1. List the E_no, E_name, Salary of all employees working for MANAGER.

2. Display all the details of the employee whose salary is more than the Sal of any IT
PROFF..

3. List the employees in the ascending order of Designations of those joined after 1981.

4. List the employees along with their Experience and Daily Salary.

5. List the employees who are either ‘CLERK’ or ‘ANALYST’ .

6. List the employees who joined on 1-MAY-81, 3-DEC-81, 17-DEC-81,19-JAN-80 .

7. List the employees who are working for the Deptno 10 or20.

8. List the Enames those are starting with ‘S’ .

9. Dislay the name as well as the first five characters of name(s) starting with ‘H’

10. List all the emps except ‘PRESIDENT’ & ‘MGR” in asc order of Salaries.

13
Solution
1. CREATE TABLE EMPLOYEE (
Emp_no INT PRIMARY KEY,
E_name VARCHAR(50),
E_address VARCHAR(100),
E_ph_no VARCHAR(15),
Dept_no INT,
Dept_name VARCHAR(50),
Job_id INT,
Designation VARCHAR(50),
Salary DECIMAL(10, 2),
Joining_date DATE
);

2. SELECT Emp_no, E_name, Salary


FROM EMPLOYEE
WHERE Designation = 'MANAGER';

3. SELECT *
FROM EMPLOYEE
WHERE Salary > (SELECT MAX(Salary) FROM EMPLOYEE WHERE Designation = 'IT
PROF');

4. SELECT *
FROM EMPLOYEE
WHERE Joining_date > '1981-01-01'
ORDER BY Designation ASC;

5. SELECT Emp_no, E_name, DATEDIFF(CURDATE(), Joining_date) AS Experience, Salary /


30 AS Daily_Salary
FROM EMPLOYEE;

6. SELECT *
FROM EMPLOYEE
WHERE Designation IN ('CLERK', 'ANALYST');

7. SELECT *
FROM EMPLOYEE
WHERE Joining_date IN ('1981-05-01', '1981-12-03', '1981-12-17', '1980-01-19');

8. SELECT *
FROM EMPLOYEE
WHERE Dept_no IN (10, 20);

14
9. SELECT E_name
FROM EMPLOYEE
WHERE E_name LIKE 'S%';

10. SELECT E_name, LEFT(E_name, 5) AS First_Five_Characters


FROM EMPLOYEE
WHERE E_name LIKE 'H%';

11. SELECT *
FROM EMPLOYEE
WHERE Designation NOT IN ('PRESIDENT', 'MGR')
ORDER BY Salary ASC;

Experiment No: 4

Title : Implementation of different types of operators in SQL.

1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on numeric values.

Addition (+): Adds two values.


Subtraction (-): Subtracts one value from another.
Multiplication (*): Multiplies two values.
Division (/): Divides one value by another.
Modulus (%): Returns the remainder of a division operation.

2. Logical Operators
Logical operators are used to combine multiple conditions.

AND: Returns true if all conditions separated by AND are true.


OR: Returns true if any condition separated by OR is true.
NOT: Reverses the result of the following condition.

15
3. Comparison Operators
Comparison operators are used to compare values.

Equal to (=): Checks if two values are equal.


Not equal to (!= or <>): Checks if two values are not equal.
Greater than (>): Checks if one value is greater than another.
Less than (<): Checks if one value is less than another.
Greater than or equal to (>=): Checks if one value is greater than or equal to another.
• Less than or equal to (<=): Checks if one value is less than or equal to another.

4. Special Operators
Special operators are used for special purposes like pattern matching and checking for NULL
values.

LIKE: Used to search for a specified pattern in a column.


IN: Specifies multiple values for a WHERE clause.
BETWEEN: Specifies a range of values.
• IS NULL: Checks if a value is NULL.

LAB PRACTICE ASSIGNMENT:


1. Display all the dept numbers available with the dept and emp tables avoiding duplicates.

SELECT DISTINCT Dept_no FROM (

SELECT Dept_no FROM dept


UNION
SELECT Dept_no FROM emp
) AS dept_numbers;

2. Display all the dept numbers available with the dept and emp tables.
SELECT Dept_no FROM dept
UNION
SELECT Dept_no FROM emp;
3. Display all the dept numbers available in emp and not in dept tables and vice versa.

16
SELECT DISTINCT Dept_no FROM emp
WHERE Dept_no NOT IN (SELECT Dept_no FROM dept)

UNION

SELECT DISTINCT Dept_no FROM dept


WHERE Dept_no NOT IN (SELECT Dept_no FROM emp);

Experiment No: 5

Title : Implementation of different types of Joins


• Inner Join
Syntax
SELECT table1.column1, table1.column2, table2.column1, ...
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
Example
SELECT employees.EmployeeID, employees.LastName,
departments.DepartmentName
FROM employees
INNER JOIN departments ON employees.DepartmentID =
departments.DepartmentID;

• Outer Join
Syntax
SELECT columns
FROM table1
FULL JOIN table2 ON table1.column_name = table2.column_name;
Example
SELECT employees.EmployeeID, employees.LastName,
departments.DepartmentName
FROM employees
FULL JOIN departments ON employees.DepartmentID = departments.DepartmentID;

17
• Natural Join.
Syntax
SELECT columns
FROM table1
NATURAL JOIN table2;
Example
SELECT employees.EmployeeID, employees.LastName,
departments.DepartmentName
FROM employees
NATURAL JOIN departments;

Left outer join

Syntax

SELECT columns

FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;

Right outer join

SELECT columns

FROM table1

RIGHT JOIN table2 ON table1.column_name = table2.column_name;

Full outer join

SELECT columns

FROM table1

FULL JOIN table2 ON table1.column_name = table2.column_name;

18
LAB PRACTICE ASSIGNMENT:
Consider the following schema:
Sailors (sid, sname, rating, age)
Boats (bid, bname, color)
Reserves (sid, bid, day(date))
1. Find all information of sailors who have reserved boat number 101.
2. Find the name of boat reserved by Bob.
3. Find the names of sailors who have reserved a red boat, and list in the order of age.
4. Find the names of sailors who have reserved at least one boat.
5. Find the ids and names of sailors who have reserved two different boats on the
same day.

6. Find the ids of sailors who have reserved a red boat or a green boat.
7. Find the name and the age of the youngest sailor.
8. Count the number of different sailor names.
9. Find the average age of sailors for each rating level.
10. Find the average age of sailors for each rating level that has at least two sailors.

Solution
1. SELECT *
FROM Sailors
WHERE sid IN (SELECT sid FROM Reserves WHERE bid = 101);
2. SELECT bname
FROM Boats
WHERE bid = (SELECT bid FROM Reserves WHERE sid = (SELECT sid FROM Sailors
WHERE sname = 'Bob'));
3. SELECT sname
FROM Sailors
WHERE sid IN (SELECT sid FROM Reserves WHERE bid IN (SELECT bid FROM Boats
WHERE color = 'red'))
ORDER BY age;

19
4. SELECT DISTINCT sname
FROM Sailors
WHERE sid IN (SELECT sid FROM Reserves);
5. SELECT s.sid, s.sname
FROM Sailors s
JOIN Reserves r1 ON s.sid = r1.sid
JOIN Reserves r2 ON r1.sid = r2.sid
WHERE r1.day = r2.day AND r1.bid <> r2.bid;
6. SELECT DISTINCT sid
FROM Reserves
WHERE bid IN (SELECT bid FROM Boats WHERE color IN ('red', 'green'));
7. SELECT sname, age
FROM Sailors
WHERE age = (SELECT MIN(age) FROM Sailors);
8. SELECT COUNT(DISTINCT sname) AS num_sailors
FROM Sailors;
9. SELECT rating, AVG(age) AS avg_age
FROM Sailors
GROUP BY rating;
10. SELECT rating, AVG(age) AS avg_age
FROM Sailors
GROUP BY rating
HAVING COUNT(*) >= 2;

20
Experiment No: 6

Title : Study & Implementation of


• Group by & Having Clause

GROUP BY is used to group rows based on one or more columns.

Syntax
SELECT column1, column2, aggregate_function(column3)
FROM table_name
GROUP BY column1, column2;

Example

SELECT CustomerID, COUNT(*) AS NumOrders, SUM(TotalAmount) AS TotalSpent


FROM Orders
GROUP BY CustomerID;

HAVING is used to filter the grouped results based on specified conditions.

Syntax

SELECT column1, column2, aggregate_function(column3)

FROM table_name

GROUP BY column1, column2

HAVING condition;

Example

SELECT CustomerID, COUNT(*) AS NumOrders, SUM(TotalAmount) AS TotalSpent

FROM Orders

GROUP BY CustomerID

HAVING COUNT(*) > 1;

21
• Order by Clause

ORDER BY is used to sort the result set based on one or more columns.
Syntax
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC|DESC, column2 ASC|DESC;
Example
SELECT CustomerID, COUNT(*) AS NumOrders, SUM(TotalAmount) AS TotalSpent
FROM Orders
GROUP BY CustomerID
ORDER BY TotalSpent DESC;

LAB PRACTICE ASSIGNMENT:

Create a relation and implement the following queries.

1. Display total salary spent for each job category.

2. Display lowest paid employee details under each manager.

3. Display number of employees working in each department and their


department name.

4. Display the details of employees sorting the salary in increasing order.

5. Show the record of employee earning salary greater than 16000 in each
department.

6. Write queries to implement and practice the above clause.

Solution
1. SELECT Job_id, SUM(Salary) AS TotalSalary
FROM EMPLOYEE
GROUP BY Job_id;

22
2. SELECT ManagerID, MIN(Salary) AS LowestSalary
FROM EMPLOYEE
GROUP BY ManagerID;
3. SELECT Dept_no, COUNT(*) AS NumEmployees, Dept_name
FROM EMPLOYEE
GROUP BY Dept_no, Dept_name;
4. SELECT *
FROM EMPLOYEE
ORDER BY Salary ASC;
5. SELECT *
FROM EMPLOYEE
WHERE Salary > 16000
ORDER BY Dept_no;

Experiment No: 8

Title : • Study & Implementation of different types of constraints

Theory:
CONSTRAINTS:
Constraints are used to specify rules for the data in a table. If there is any violation between the
constraint and the data action, the action is aborted by the constraint. It can be specified when
the table is created (using CREATE TABLE statement) or after the table is created (using
ALTER TABLE statement).

1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record is to be
accepted for storage in the table.
Syntax:
CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );
Example:

23
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));

2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated
across the column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due to a
null).
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….); Example:
CREATE TABLE student (sno NUMBER (3), name CHAR(10),class

CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));

4. PRIMARY KEY: A field which is used to identify a record uniquely. A column or


combination of columns can be created as primary key, which can be used as a reference from
other tables. A table contains primary key is known as Master Table.
It must uniquely identify each record in a table.
It must contain unique values.
It cannot be a null field.
It cannot be multi port field.
It should contain a minimum no. of fields necessary to be called unique.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY,
….);

24
Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname
CHAR(10));

5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To
reference any primary key column from other table this constraint can be used. The table in
which the foreign key is defined is called a detail table. The table that defines the primary key
and is referenced by the foreign key is called the master table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size)
FOREIGN KEY(column_name) REFERENCES table_name); Example:
CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY, subname
CHAR(10),fcode NUMBER(3), FOREIGN KEY(fcode) REFERENCE faculty );

LAB PRACTICE ASSIGNMENT:

1. Create a table called EMP with the following structure.

Name Type

EMPNO NUMBER (6)


ENAME VARCHAR2 (20)
JOB VARCHAR2 (10)
DEPTNO NUMBER (3) SAL
NUMBER (7,2)
Allow NULL for all columns except ename and job.
2. Add constraints to check, while entering the empno value (i.e) empno > 100.
3. Define the field DEPTNO as unique.
4. Create a primary key constraint for the table(EMPNO).
5. Write queries to implement and practice constraints.

Soultion
1. CREATE TABLE EMP (

25
EMPNO NUMBER(6) CONSTRAINT chk_empno CHECK (EMPNO > 100),
ENAME VARCHAR2(20) NOT NULL,
JOB VARCHAR2(10) NOT NULL,
DEPTNO NUMBER(3),
SAL NUMBER(7,2),
CONSTRAINT uk_deptno UNIQUE (DEPTNO),
CONSTRAINT pk_emp PRIMARY KEY (EMPNO)
);
2. INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (101, 'John',
'Manager', 10, 5000);
INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (102, 'Alice',
'Analyst', 20, 4000);
3. INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (99, 'Bob', 'Clerk',
30, 3000); -- This should fail
4. INSERT INTO EMP (EMPNO, ENAME, JOB, DEPTNO, SAL) VALUES (103, 'Emily',
'Clerk', 10, 3500); -- This should fail
5.

VIVA-VOCE

1. Define DCL?

DCL stands for Data Control Language, which is a component of SQL (Structured Query
Language). DCL is used to control access to data stored in a database and manage
permissions. The primary commands in DCL are:

2. List the DCL commands used in data bases

GRANT: This command is used to provide specific privileges to users or roles. For
example, granting a user permission to access certain data or perform specific actions
like SELECT, INSERT, UPDATE, or DELETE.

GRANT SELECT, INSERT ON table_name TO user_name;

REVOKE: This command is used to remove previously granted privileges from users or
roles.

26
REVOKE SELECT, INSERT ON table_name FROM user_name;

3. Write the syntax for grant command

GRANT privilege_list

ON object_name

TO user_or_role

[WITH GRANT OPTION];

4. What are TCL commands?

Transaction Control Language (TCL) commands in SQL are crucial for managing
database transactions, ensuring data integrity and consistency. The primary TCL
commands are COMMIT, ROLLBACK, SAVEPOINT, RELEASE SAVEPOINT, and SET
TRANSACTION. COMMIT saves all changes made during the current transaction
permanently, while ROLLBACK undoes changes, reverting the database to the last
committed state. SAVEPOINT allows setting a point within a transaction to which one can
rollback, and RELEASE SAVEPOINT deletes a specified savepoint. SET TRANSACTION
defines transaction properties like the isolation level

5. What are single row functions?

A single row function or scalar function returns only one value for every row queries
in table. Single row function can appear in a select command and can also be
included in a where clause. The single row function can be broadly classified as,
* Date Function * Conversion Function
* Numeric Function * Miscellaneous Function
*Character Function
6. List some character functions
1)Upper 2)Lower 3)Intcap 4)Length 5)Trim 6)Replace 7)Ascii 8)Substr
7. What is a view?
A view is a logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or changed.
8. List any two advantages of view?
1. Hides data complexity.
2. Simplifies the usage by combining multiple tables into a single table

9. List the set operations of SQL?


1) Union 2) Intersect operation 3) The except operation (minus)

27
10. What is the use of sub Queries?

A sub Queries is a select-from-where expression that is nested with in another Queries.


Uses
A common use of sub Queries is to perform tests for set membership, make set
comparisons and determine set cardinality

28

You might also like