Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
46 views18 pages

Practical Sheet 02

The document discusses the tee command in Linux/Unix systems and provides steps to use it. It then discusses SQL constraints such as NOT NULL, UNIQUE, PRIMARY KEY etc and provides examples of creating tables with different constraints. It also discusses the SELECT statement in SQL for retrieving data from tables and examples of using different clauses like WHERE, DISTINCT etc.

Uploaded by

darkk0462
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)
46 views18 pages

Practical Sheet 02

The document discusses the tee command in Linux/Unix systems and provides steps to use it. It then discusses SQL constraints such as NOT NULL, UNIQUE, PRIMARY KEY etc and provides examples of creating tables with different constraints. It also discusses the SELECT statement in SQL for retrieving data from tables and examples of using different clauses like WHERE, DISTINCT etc.

Uploaded by

darkk0462
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/ 18

Faculty of Applied Sciences - Rajarata University of Sri Lanka

ICT 1407/COM 1302 – Database Management Systems

Practical Sheet 02

TEE Command
The tee command is normally used to split the output of a program so that it can be both
displayed and saved in a file.

The command can be used to capture intermediate output before the data is altered by
another command or program.

The tee command reads standard input, then writes its content to standard output.

Steps
1. Open the command prompt using ‘Run as Administrator’.
2. Enter a copy of the link to your MySQL Bin Directory in the Command Prompt
cd <path to your MySQL Bin Directory>
3. Log in to MySQL by typing (consider your username as root)
mysql -u root -p
4. Give your password
5. You will see mysql> in your command prompt. Then type tee command, with the text file
name and the extension..
tee text_file_name.txt

1. Constraints

SQL constraints are used to specify rules for the data in a table. Some of the constraints
used in MySQL are as follows.

● NOT NULL - Ensures that a column cannot have a NULL value


● UNIQUE - Ensures that all values in a column are different
● PRIMARY KEY - A combination of NOT NULL and UNIQUE. Uniquely identifies each row
in a table
● FOREIGN KEY - Prevents actions that would destroy links between tables
● CHECK - Ensures that the values in a column satisfies a specific condition
● DEFAULT - Sets a default value for a column if no value is specified

Example of Constraints

Create a database named Company, use it and create the tables below.

NOT NULL, PRIMARY KEY,CHECK, DEFAULT

CREATE TABLE EMPLOYEE(

Fname VARCHAR(15) NOT NULL,

Minit CHAR,

Lname VARCHAR(15) NOT NULL,

Ssn CHAR(9) NOT NULL,

Bdate DATE,

Address VARCHAR(30) DEFAULT 'Colombo',

Sex CHAR,

Age INT,

Salary DECIMAL(10,2),

Super_ssn CHAR(9),

Dno INT NOT NULL,

PRIMARY KEY (Ssn),

CHECK (Age>=18));

FOREIGN KEY, UNIQUE

CREATE TABLE DEPARTMENT

( Dname VARCHAR(15) NOT NULL,


Dnumber INT NOT NULL,

Mgr_ssn CHAR(9) NOT NULL,

Mgr_start_date DATE,

PRIMARY KEY (Dnumber),

UNIQUE (Dname),

FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn) );

Query 1 to Validate Examples

INSERT INTO EMPLOYEE(

Fname, Minit, Lname, Ssn, Bdate, Address, Sex,Age,Salary, Super_ssn, Dno)

VALUES

('Jennifer','S','Wallace','987654321','1941-06-29','291 Berry, Bellaire,


TX','F',17,43000,'888665555',4);

Query 2 to Validate Examples

INSERT INTO EMPLOYEE(

Fname, Minit, Lname, Ssn, Bdate, Sex,Age,Salary, Super_ssn, Dno)

VALUES

('Jennifer','S','Wallace','987654321','1941-06-29','F',20,43000,'888665555',4);

Activity
Create the below tables and insert data to the respective tables.

EMPLOYEE

Fnam Minit Lnam Ssn Bdate Address Sex Salary Super_ssn Dno
e e

John B Smith 12345 1955- 731 M 30000 33344555 5


6789 01-09 Fondren,
Houston,
TX
Frankli T Wong 33344 1955- 638 Voss, M 40000 88866555 5
n 555 12-08 TX

Alicia J Zelaya 99988 1968- 3321 F 25000 987654321 4


7777 01-19 Castle,
Houston,
TX

Jennif S Wallac 98765 1941- 291 F 43000 888665555 4


er e 4321 06-29 Berry,
Bellaire,
TX

Rame K Naray 66688 1962- 975 Fire M 38000 333445555 5


sh an 4444 09-15 Oak,
Humble,
TX

Joyce A Englis 45345 1972- 5631 F 25000 333445555 5


h 3453 07-31 Rice,
Houston,
TX

Ahma V Jabber 98798 1969- 980 F 25000 987654321 4


d 7987 03-29 Dallas,
Houston,
TX

James E Borg 88866 1937- 450 M 55000 987987987 1


555 11-10 Stone,
Houston,
TX

PROJECTS

Pname Pnumber Plocation Dnum

ProductX 1 Bellaire 5

ProductY 2 Sugarland' 5

ProductZ 3 Houston 5

Computerization 10 Stafford 4
Reorganization 20 Houston 1

Newbenefits 30 Stafford 4

DEPARTMENT

Dname Dnumber Mgr_ssn Mgr_start_date

Research 5 333445555 1988-05-22

Administration 4 987654321 1995-01-01

Headquarters 1 888665555 1981-06-19

WORKS_ON

Essn Pno Hours

12345789 1 32.5

12345789 2 7.5

666884444 3 40.0

453453453 1 20.0

453453453 2 20.0

33344555 2 10.0

33344555 3 10.0

33344555 10 10.0

33344555 20 10.0

999887777 30 30.0

999887777 10 10.0

987987987 10 35.0

987987987 30 5.0

987654321 30 20.0

987654321 20 15.0
2. Select

The SQL SELECT statement returns a result set of records, from one or more tables.

The SELECT-FROM-WHERE Structure of Basic SQL Queries

SELECT <attribute list>

FROM <table list>

WHERE <condition>;

where

● <attribute list> is a list of attribute names whose values are to be retrieved


by the query.
● <table list> is a list of the relation names required to process the query.
● <condition> is a conditional (Boolean) expression that identifies the tuples
to be retrieved by the query.

SELECT * Example

SELECT * FROM EMPLOYEE;

SELECT Column Example

SELECT Fname, Address FROM EMPLOYEE;

SELECT Distinct Example

SELECT DISTINCT Sex FROM EMPLOYEE;

WHERE Clause Example

SELECT * FROM EMPLOYEE

WHERE Address = '291 Berry, Bellaire, TX';

Operators in the WHERE clause

The following operators can be used in the WHERE clause:

= Equal
> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some


versions of SQL this operator
may be written as !=

BETWEEN Between a certain range

LIKE Search for a pattern

1. Retrieve the birth date and address of the employee(s) whose name is ‘John B. Smith’.

SELECT Bdate, Address

FROM EMPLOYEE

WHERE Fname = 'John' AND Minit = 'B' AND Lname = 'Smith';

Retrieve Data from Multiple Tables

2. Retrieve the name and address of all employees who work for the ‘Research’ department.

Q1

SELECT Fname, Lname, Address

FROM EMPLOYEE, DEPARTMENT

WHERE Dname = 'Research' AND Dnumber = Dno;


Ambiguous Attribute Names, Aliasing, Renaming, and Tuple Variables

In SQL, the same name can be used for two (or more) attributes as long as the attributes are in
different tables.

If this is the case, and a multi-table query refers to two or more attributes with the same name,
we must qualify the attribute name with the relation name to prevent ambiguity.

This is done by prefixing the relation name to the attribute name and separating the two by a
period.

To prevent ambiguity, Q1 should be rephrased as below.

SELECT Fname, EMPLOYEE.LName, Address

FROM EMPLOYEE, DEPARTMENT

WHERE DEPARTMENT.DName = 'Research'

AND DEPARTMENT.Dnumber = EMPLOYEE.Dno;

Fully qualified attribute names can be used for clarity even if there is no ambiguity in attribute
names.

Q1 can be rewritten as below with fully qualified attribute names.

SELECT EMPLOYEE.Fname, EMPLOYEE.LName, EMPLOYEE.Address

FROM EMPLOYEE, DEPARTMENT

WHERE DEPARTMENT.DName = 'Research'

AND DEPARTMENT.Dnumber = EMPLOYEE.Dno;

We can also rename the table names to shorter names by creating an alias for each table name
to avoid repeated typing of long table names.

SELECT E.Fname, E.LName, E.Address

FROM EMPLOYEE AS E, DEPARTMENT AS D

WHERE D.Dname = 'Research'

AND D.Dnumber = E.Dno;


Activity

Unspecified WHERE Clause

1. Select all EMPLOYEE Ssns

SELECT Ssn FROM EMPLOYEE;

2. Select all combinations of EMPLOYEE Ssn and DEPARTMENT Dname in the


database.

SELECT Ssn, Dname FROM EMPLOYEE, DEPARTMENT;

Use of the Asterisk

3. Retrieve all the attributes of an EMPLOYEE who works in DEPARTMENT number


5.

SELECT * FROM EMPLOYEE WHERE Dno = 5;

4. Retrieve all the attributes of an EMPLOYEE and the attributes of the


DEPARTMENT in which he or she works for every employee of the ‘Research’
department.

SELECT * FROM EMPLOYEE, DEPARTMENT

WHERE Dname = 'Research' AND Dno = Dnumber;

Tables as Sets in SQL

SQL usually treats a table not as a set but rather as a multiset; duplicate tuples can appear
more than once in a table, and in the result of a query.

SQL does not automatically eliminate duplicate tuples in the results of queries.

5. Retrieve the salary of every employee

SELECT ALL Salary FROM EMPLOYEE;

6. Select all distinct salary values


SELECT DISTINCT Salary FROM EMPLOYEE;

7. Make a list of all project numbers for projects that involve an employee whose last name
is ‘Smith’, either as a worker or as a manager of the department that controls the project.

( SELECT DISTINCT Pnumber

FROM PROJECT, DEPARTMENT, EMPLOYEE

WHERE Dnum = Dnumber AND Mgr_ssn = Ssn AND Lname = 'Smith')

UNION

( SELECT DISTINCT Pnumber

FROM PROJECT, WORKS_ON, EMPLOYEE

WHERE Pnumber = Pno AND Essn = Ssn AND Lname = 'Smith' );

Substring Pattern Matching and Arithmetic Operators

8. Retrieve all employees whose address is in Houston, Texas.

SELECT Fname, Lname

FROM EMPLOYEE

WHERE Address LIKE '%Houston,TX%';

9. Show the resulting salaries if every employee working on the ‘ProductX’ project is given a
10% raise.

SELECT E.Fname, E.Lname, 1.1 * E.Salary AS Increased_sal

FROM EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P

WHERE E.Ssn = W.Essn

AND W.Pno = P.Pnumber

AND P.Pname = 'ProductX';

10. Retrieve all employees in department 5 whose salary is between $30,000 and $40,000.
SELECT *

FROM EMPLOYEE

WHERE (Salary BETWEEN 30000 AND 40000) AND Dno = 5;

Ordering of Query Results

11. Retrieve a list of employees and the projects they are working on, ordered by
department and, within each department, ordered alphabetically by last name, then
first name.

SELECT D.Dname, E.Lname, E.Fname, P.Pname

FROM DEPARTMENT AS D, EMPLOYEE AS E, WORKS_ON AS W,


PROJECT AS P

WHERE D.Dnumber = E.Dno

AND E.Ssn = W.Essn

AND W.Pno = P.Pnumber

ORDER BY D.Dname, E.Lname, E.Fname;

The default order is in ascending order of values.

We can specify the keyword DESC if we want to see the result in a descending order of values.

The keyword ASC can be used to specify ascending order explicitly.

Comparisons Involving NULL

SQL has various rules for dealing with NULL values.

NULL is used to represent a missing value. But it usually has one of three different interpretations.

● Unknown value.
○ A person’s date of birth is not known, so it is represented by NULL in the database.
An example of the other case of unknown would be NULL for a person’s home
phone because it is not known whether or not the person has a home phone.
● Unavailable or withheld value.
○ A person has a home phone but does not want it to be listed, so it is withheld and
represented as NULL in the database.
● Not applicable attribute.
○ The attribute LastCollegeDegree would be NULL for a person who has no college
degrees because it does not apply to that person.

Nested Queries, Tuples, and Set/Multiset Comparisons

Some queries require that existing values in the database be fetched and then used in a
comparison condition.

Such queries can be conveniently formulated by using nested queries, which are complete select-
from-where blocks within another SQL query.

That other query is called the outer query.

These nested queries can also appear in the WHERE clause or the FROM clause or the SELECT
clause or other SQL clauses as needed.

Retrieve the name of each employee who has a dependent with the same first name and is the
same sex as the employee.

SELECT E.Fname, E.Lname

FROM EMPLOYEE AS E

WHERE E.Ssn IN ( SELECT D.Essn

FROM DEPENDENT AS D

WHERE E.Fname = D.Dependent_name

AND E.Sex = D.Sex );

Correlated Nested Queries

Whenever a condition in the WHERE clause of a nested query references some attribute
of a relation declared in the outer query, the two queries are said to be correlated.

Whenever a condition in the WHERE clause of a nested query references some attribute
of a relation declared in the outer query, the two queries are said to be correlated.

The above query can also be written as follows:

SELECT E.Fname, E.Lname


FROM EMPLOYEE AS E, DEPENDENT AS D

WHERE E.Ssn = D.Essn

AND E.Sex = D.Sex

AND E.Fname = D.Dependent_name;

The EXISTS and UNIQUE Functions in SQL

EXISTS and UNIQUE are Boolean functions that return TRUE or FALSE; hence, they
can be used in a WHERE clause condition.

The EXISTS function in SQL is used to check whether the result of a nested query is
empty (contains no tuples) or not.

The result of EXISTS is a Boolean value TRUE if the nested query result contains at least
one tuple, or FALSE if the nested query result contains no tuples.

Q14 can be written as follows:

Q16: SELECT E.Fname, E.Lname

FROM EMPLOYEE AS E

WHERE EXISTS

( SELECT *

FROM DEPENDENT AS D

WHERE E.Ssn = D.Essn

AND E.Sex = D.Sex

AND E.Fname = D.Dependent_name);

3. Retrieve the names of employees who have no dependents.

Q17:SELECT Fname, Lname

FROM EMPLOYEE

WHERE NOT EXISTS ( SELECT *


FROM DEPENDENT

WHERE Ssn = Essn );

Explicit Sets

We have seen several queries with a nested query in the WHERE clause.

It is also possible to use an explicit set of values in the WHERE clause, rather than a
nested query.

Such a set is enclosed in parentheses in SQL.

4. Retrieve the Social Security numbers of all employees who work on project
numbers 1, 2, or 3.

Q18:SELECT DISTINCT Essn

FROM WORKS_ON

WHERE Pno IN (1, 2, 3);

Renaming in SQL

In SQL, it is possible to rename any attribute that appears in the result of a query by
adding the qualifier AS followed by the desired new name.

Q19: SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name

FROM EMPLOYEE AS E, EMPLOYEE AS S

WHERE E.Super_ssn = S.Ssn;

Joined Tables in SQL and Outer Joins

The concept of a joined table was incorporated into SQL to permit users to specify a table resulting
from a join operation in the FROM clause of a query.

This construct may be easier to comprehend than mixing together all the select and join conditions
in the WHERE clause.
For example, consider the query, which retrieves the name and address of every employee who
works for the ‘Research’ department.

Q20: SELECT Fname, Lname, Address


FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = ‘Research’;

Inner join
The default type of join in a joined table is called an inner join, where a tuple is included in the
result only if a matching tuple exists in the other relation.

Left outer join


Every tuple in the left table must appear in the result; if it does not have a matching tuple, it is
padded with NULL values for the attributes of the right table.

SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name


FROM (EMPLOYEE AS E
LEFT OUTER JOIN EMPLOYEE AS S
ON E.Super_ssn = S.Ssn);

Right outer join


every tuple in the right table must appear in the result; if it does not have a matching tuple, it is
padded with NULL values for the attributes of the left table), and FULL OUTER JOIN.

Aggregate Functions in SQL

Aggregate functions are used to summarize information from multiple tuples into a single-tuple
summary.
Grouping is used to create subgroups of tuples before summarization.
Grouping and aggregation are required in many database applications.

A number of built-in aggregate functions exist:


COUNT, SUM, MAX, MIN, AVG

5. Find the sum of the salaries of all employees, the maximum salary, the minimum salary,
and the average salary.
Q20: SELECT SUM (Salary) AS Total_Sal,
MAX (Salary) AS Highest_Sal,
MIN (Salary) AS Lowest_Sal,
AVG (Salary) AS Average_Sal
FROM EMPLOYEE;

6. Find the sum of the salaries of all employees of the ‘Research’ department, as well as the
maximum salary, the minimum salary, and the average salary in this department.

Q21: SELECT SUM (Salary),


MAX (Salary), MIN (Salary),
AVG (Salary)
FROM (EMPLOYEE JOIN DEPARTMENT ON Dno = Dnumber)
WHERE Dname = ‘Research’;

7. Retrieve the total number of employees in the company (Q22) and the number of
employees in the ‘Research’ department (Q23).

Q22: SELECT COUNT (*) FROM EMPLOYEE;

Q23: SELECT COUNT (*)


FROM EMPLOYEE, DEPARTMENT
WHERE DNO = DNUMBER AND DNAME = ‘Research’;

8. Count the number of distinct salary values in the database.


Q24: SELECT COUNT (DISTINCT Salary) FROM EMPLOYEE;

Grouping: The GROUP BY and HAVING Clauses


In many cases we want to apply the aggregate functions to subgroups of tuples in a
relation, where the subgroups are based on some attribute values.
For example, we may want to find the average salary of employees in each department
or the number of employees who work on each project.

9. For each department, retrieve the department number, the number of employees
in the department, and their average salary.
Q25: SELECT Dno, COUNT (*), AVG (Salary)
FROM EMPLOYEE
GROUP BY Dno;

10. For each project, retrieve the project number, the project name, and the number
of employees who work on that project.
Q26: SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname;\

HAVING clause
SQL provides a HAVING clause, which can appear in conjunction with a GROUP BY
clause, for this purpose.
HAVING provides a condition on the summary information regarding the group of tuples
associated with each value of the grouping attributes.
Only the groups that satisfy the condition are retrieved in the result of the query.

11. For each project on which more than two employees work, retrieve the project
number, the project name, and the number of employees who work on the project.
Q27: SELECT Pnumber, Pname, COUNT (*)
FROM PROJECT, WORKS_ON
WHERE Pnumber = Pno
GROUP BY Pnumber, Pname
HAVING COUNT (*) > 2;

Summary

SELECT <attribute and function list>


FROM <table list>
[ WHERE <condition>]
[ GROUP BY <grouping attribute(s)>]
[ HAVING <group condition>]
[ ORDER BY <attribute list>];

You might also like