Dbms Lab Assignment
Dbms Lab Assignment
(DBMS)
LABORATORY WORKBOOK
Date ______________________
Signature___________________
CONTENTS
S. No Object of Experiments Remarks Date Signature
___________________
Lab Instructor Signature
File System & File Handling Experiment
01
Objective
The Purpose of this Lab is to get familiar with the File System & File Handling
Theory
File System
A file system is the methods and data structures that an operating system uses to keep track of files on a
disk or partition; that is, the way the files are organized on the disk. The word is also used to refer to a
partition or disk that is used to store the files or the type of the file system. Thus, one might say ``I have
two file systems'' meaning one has two partitions on which one stores files, or that one is using the
``extended file system'', meaning the type of the file system.
The difference between a disk or partition and the file system it contains is important. A few programs
(including, reasonably enough, programs that create file systems) operate directly on the raw sectors of a
disk or partition; if there is an existing file system there it will be destroyed or seriously corrupted. Most
programs operate on a file system, and therefore won't work on a partition that doesn't contain one (or that
contains one of the wrong type).
Before a partition or disk can be used as a file system, it needs to be initialized, and the bookkeeping data
structures need to be written to the disk. This process is called making a file system.
Block Size
The block size specifies size that the file system will use to read and write data. Larger block sizes will
help improve disk I/O performance when using large files, such as databases. This happens because the
disk can read or write data for a longer period of time before having to search for the next block.
On the downside, if you are going to have a lot of smaller files on that file system, like the /etc, there the
potential for a lot of wasted disk space.
For example, if you set your block size to 4096, or 4K, and you create a file that is 256 bytes in size, it
will still consume 4K of space on your hard drive. For one file that may seem trivial, but when your file
system contains hundreds or thousands of files, this can add up.
Block size can also effect the maximum supported file size on some file systems. This is because many
modern file system are limited not by block size or file size, but by the number of blocks. Therefore, you
would be using a "block size * max # of blocks = max block size" formula.
Go to > Computer, right-click on the drive you wish to examine, and select > Properties from the menu.
The > General tab shows the > File system.
LAB # 02
The Purpose of this Lab is to get familiar with the Relational DBMS
Architecture & its Concepts
___________________
Lab Instructor Signature
02
Objective
The Purpose of this Lab is to get familiar with the Relational DBMS Architecture & its Concepts
Theory
RDBMS: Overview
• Entities: Things in the real world that you store information about in a database.
• Tables typically store data representing one type of entity
.
• Example:
– A bank database has a customer table specifically for customer information.
– The customer table can contain entities/columns such as the customer name,
account number, and contact information.
• Relationships: Links between entities that have something to do with each other.
• Example:
– The bank customer name has a relationship to the customer account number and
contact information.
There can also be relationships between separate tables (for example, customer to accounts).
You cannot literally store things in a database, nor any relationships they might have. What you can store
in a database is data. Storing information about things such as customers, bank accounts and currencies in
our database, means that you store data in your database that represents these real-world things.
In relational databases, one table is typically used to store data that represents entities of one particular
kind. As in the bank example, the customers table is used to store items of data, each of which represents
exactly one entity of the "customer" kind.
Relationship Categories
Relationships can be categorized according to how many entities can possibly be involved at either end of
the relationship.
In the slide example of a one-to-one relationship, a car has one engine, and the engine can belong to only
one car. There is a one-to-one relationship between the car and the engine. Often these types of
relationships are put in the same table, but not always.
In the slide example of a one-to-many relationship, an individual customer of a bank can have more than
one account. Note that this allows for customers to have zero, one, or more bank accounts. The word
many refer to the maximum number of possible bank accounts for each customer. Alternatively, a bank
account is tied to a single customer only. That is why this is a one-to-many relationship.
There is a many-to-many relationship between students and courses. A student can attend more than one
course and a course can be attended by many students.
Row-Column Relationship
• Rows are a collection of values that describe an entity (such as a bank account).
• Columns are a collection of similar data among rows (such as customer surnames). Each column
has a name and a data type.
• The intersection of row and column contains individual data items called values. Values are
always atomic, that is, each position in a table may contain only one datum (piece of data). If you
have ever used a spreadsheet, you have used a table of data.
It is common to present data in a simple two-dimensional table form. The relational model stipulates that
a relation must have unique tuples—no two entities can be identical or you would not be able to
distinguish one from the other. There must be some combination of columns (possibly, all columns) called
a key, whose values uniquely identify each tuple. Most RDBMSs are less strict. Virtually all of them
allow a table to contain duplicate rows, and allow a table to exist without a key.
Note: In SQL, tables are not required to have primary keys. In other words, the requirement of the
relational model is not enforced in SQL. However, it is enforced as soon as a primary key is added to the
table. A detailed discussion of primary keys, and how to create them, is provided later in the course.
Exercise
Question 1
Modern School of higher education has around 2000 students and three departments. The students belong
to various departments in the school. Every department has a Head of Department along with teachers.
The head of department manages his departmental teachers and the students belonging to his department.
The head of department also teaches the students. All the head of departments report to the Principal of
the school. The Principal manages the departments and also teaches the students. Handling the
administrative staff of the school is also the responsibility of the Principal. Every individual, except the
students, are the employees of the school
Problem
3. Head Of department
a. Name b. age c. Head Id (primary key) d. Phone No
e. Course teach
4. Teacher
a. Name b. Qualification c. Id (primary key) d. Phone No
e. Age f. Experience g. Date of joining h.course teach
6. Principe of school
a. Name (primary key) b. qualification c. Phone no
d. job description
7. Employee
a. EName (primary key) b. EID
f. The Principal manages the departments and also teaches the students.
Manages ,Teaches
g. Handling the administrative staff of the school is also the responsibility of the Principal
Handling
1. The students belong to various departments in the school. Hence the cardinality between the
students and Departments is Many to Many (M:N).
2. Every department has a Head of Department along with teachers..Hence the cardinality between
the Department and Head of department Many to One (M:1).
3. The head of department manages his departmental teachers and the students belonging to his
department.Hence the cardinality between the head of department and departmental teacher
and students one to Many (1:N)
4. The head of department also teaches the students. Hence the cardinality between the Head of
Department and Students One to Many (1: N).
5. All the head of departments report to the Principal of the school. Hence the cardinality between
the
Head of Department and Princixxxxxpal of the School Many to One (M: 1).
6. The Principal manages the departments and also teaches the students. Hence the cardinality
between the Principal and Department , students One to Many(1:M)
7. Handling the administrative staff of the school is also the responsibility of the Principal. Hence
the cardinality between the administrative staff and Principle (M:1)
8. Every individual, except the students, are the employees of the school. Hence the cardinality
between the Employee and all other staff (1:M)
Question 2
1. a professor teaches zero, one or many classes and a class is taught by one professor
Professor Class
2. a course may generate zero, one or many classes and a class comes from one course
Course Class
class Class
Feedback
LAB # 03
The Purpose of this Lab is to introduce Entity Relationship Diagram & its
Notations
___________________
Lab Instructor Signature
03
Objective
The Purpose of this Lab is to introduce Entity Relationship Diagram & its Notations
Theory
Notations
Entities Notation
An entity is represented by a
Entity rectangle which contains the
entity’s name.
Attributes Notation
Relationship Notation
Entity
Entities are represented by means of rectangles. Rectangles are named with the entity set they represent.
Attributes
Attributes are the properties of entities. Attributes are represented by means of ellipses. Every ellipse
represents one attribute and is directly connected to its entity (rectangle).
If the attributes are composite, they are further divided in a tree like structure. Every node is then
connected to its attribute. That is, composite attributes are represented by ellipses that are connected with
an ellipse.
Relationship
Relationships are represented by diamond-shaped box. Name of the relationship is written inside the
diamond-box. All the entities (rectangles) participating in a relationship, are connected to it by a line.
● Many-to-one − when more than one instance of entity is associated with the
relationship, it is marked as 'N:1'. The following image reflects that more
than one instance of an entity on the left and only one instance of an entity
on the right can be associated with the relationship. It depicts many-to-one
relationship.
● Many-to-many − The following image reflects that more than one instance of
an entity on the left and more than one instance of an entity on the right can
be associated with the relationship. It depicts many-to-many relationship.
Participation Constraints
● Total Participation − Each entity is involved in the relationship. Total
participation is represented by double lines.
● Partial participation − Not all entities are involved in the relationship. Partial
participation is represented by single lines.
Exercise
Question 1
Modern School of higher education has around 2000 students and three departments. The students
belong to various departments in the school. Every department has a Head of Department along with
teachers. The head of department manages his departmental teachers and the students belonging to his
department. The head of department also teaches the students. All the head of departments report to
the Principal of the school. The Principal manages the departments and also teaches the students.
Handling the administrative staff of the school is also the responsibility of the Principal. Every individual,
except the students, are the employees of the school
1. an invoice is written by one sales rep but a sales rep writes many invoices
2. a vendor sells many products but a product is bought from one vendor
3. an invoice has one or many products and a product is found on zero, one or many invoices
● Identify the entity
● Identify the entity’s attribute
● Identify the primary and foreign Keys
● Identify relationship between Entities
● Identify the Cardinality constraints
● Draw ERD
Feedback
LAB # 04
The Purpose of this Lab is to make Entity Relationship Diagram by using
Case Studies
Name Muhammad Kamran khan
Date
Registration No 40668
Department BSSE
Quiz
Assignment
___________________
Lab Instructor Signature
04
Objective
The Purpose of this Lab is to make Entity Relationship Diagram by using Case Studies
Theory
CASE - STUDY
Design and draw an ER diagram that captures the information about the university.
Use only the basic ER model here; that is, entities, relationships, and attributes. Be
Sure to indicate any key and participation constraints.
Exercise
The Prescriptions-R-X chain of pharmacies has offered to give you a free lifetime supply of medicine if
you design its database. Given the rising cost of health care, you agree. Here’s the information that you
gather:
● Patients are identified by an SSN, and their names, addresses, and ages must be recorded.
● Doctors are identified by an SSN. For each doctor, the name, specialty, and years of experience
must be recorded.
● Each pharmaceutical company is identified by name and has a phone number.
● For each drug, the trade name and formula must be recorded. Each drug is sold by a given
pharmaceutical company, and the trade name identifies a drug uniquely from among the products
of that company. If a pharmaceutical company is deleted, you need not keep track of its products
any longer.
● Each pharmacy has a name, address, and phone number.
● Every patient has a primary physician. Every doctor has at least one patient.
● Each pharmacy sells several drugs and has a price for each. A drug could be sold at several
pharmacies, and the price could vary from one pharmacy to another.
● Doctors prescribe drugs for patients. A doctor could prescribe one or more drugs for several
patients, and a patient could obtain prescriptions from several doctors.
● Each prescription has a date and a quantity associated with it. You can assume that, if a doctor
prescribes the same drug for the same patient more than once, only the last such prescription
needs to be stored.
Draw an ER diagram that captures the preceding information. Identify any constraints not captured by the
ER diagram.
How would your design change if each drug must be sold at a fixed price by all pharmacies?
How would your design change if the design requirements change as follows: If a doctor prescribes the
same drug for the same patient more than once, several such prescriptions may have to be stored?
Feedback
LAB # 05
The Purpose of this Lab is to introduce the DDL (Data Definition Language)
which includes Create, Drop, and Alter & Truncate Statements
___________________
Lab Instructor Signature
05
Objective
The Purpose of this Lab is to introduce the DDL (Data Definition Language) which includes Create,
Drop, and Alter & Truncate Statements
Theory
The DDL SQL statements are used to define database and table data. The statements shown in the slide
are followed by options to specify data operations.
Creating a Database
When your database design is complete, create the actual database by using the MySQL statement
CREATE DATABASE. It is important for you to name the database according to its purpose. After the
database is created, you can add the tables.
You can add the IF NOT EXISTS option statement. An error occurs if the database exists and you did not
specify IF NOT EXISTS.
For more information about creating a database, see the MySQL Reference Manual at
http://dev.mysql.com/doc/refman/5.5/en/create-database.html.
Table names can be (or contain) reserved words as long as the name is quoted (such as a table named
'my_table' or '$'), but this practice is discouraged.
Creating a Table
• Example:
After the database structure is designed and the database has been created, you can add the individual
tables. You must use accurate assignment of data types and options, then you can add the tables from the
design plan to the database. Table and column options are covered later in this lesson.
Creating tables is a complex topic due to the process of choosing how to create the table and the syntax,
which consists of many elements. The statement syntax shown in the slide includes the column and table
options.
1. Creates a table called CountryLanguage"(" is the beginning of the table structure definition that
ends with ")".
2. The column named CountryCode is assigned the data type of CHAR and maximum length of 3
characters that cannot accept NULL. The comma at the end of the line indicates that you are
continuing to define columns, or set a primary key.
3. The column named Language is assigned the CHAR data type and a length of 30, also with no
NULLs.
4. The column named IsOffical is assigned the ENUM data type (with the value 'True' or 'False').
The addition of NOT NULL means that each row must contain one of the specified values (as
indicated in single quotation marks). If the field is not provided, it is set to 'False' by the phrase
DEFAULT 'False'.
5. The column named Percentage is assigned the FLOAT data type. It contains three digits,
including one to the right of the decimal point. This column cannot accept NULL.
6. Defines the PRIMARY KEY, the type of key, and to what columns it applies. In this case, a
combination of both CountryCode and Language columns define a unique identifier for each
row.
7. ")" is the closing of the table structure definition. “;” means execute this statement (using the
MySQL command-line client) and create the CountryLanguage table.
Note: You can also use the CREATE TABLE statement to create temporary tables. Temporary tables are
covered in detail later in the course.
For more information about creating a table, see the MySQL Reference Manual at
http://dev.mysql.com/doc/refman/5.5/en/create-table.html.
Column Options
The CREATE TABLE column options modify how MySQL handles the associated column. Some
common column options:
Table Options
• You can add options to the CREATE TABLE statement, such as:
• ENGINE
• COMMENT
• DEFAULT CHARACTER SET
• Example:
The CREATE TABLEtable options modify how MySQL handles the entire table. Some common table
options:
• ENGINE = <storage_engine_name>: Indicates the storage engine to be used for the table
• COMMENT: Up to 60 characters of free form text
• DEFAULT CHARACTER SET <character set>: Specifies the default character set for the table
Table Indexing
An index (or key) in MySQL serves to assist in finding rows quickly, like an index at the back of a
technical manual. Database indexes are used to locate rows in a table. Instead of containing all of the row
data, an index contains only the columns used to locate the rows. It also contains information describing
where the rows are physically located. Usually, you create all the indexes you need when you are creating
tables.
You can create indexes on single columns or multiple columns (composite indexes). For example, the
phone number for an individual in a phone book can be used as a single column index, whereas the last
name and first name can be used to create a composite index.
MySQL Indexing
• PRIMARY KEY
• Only one PRIMARY KEY is allowed per table.
• It uniquely identifies a single row in the table.
• No NULL values are permitted.
• No duplicate values are permitted.
• If a duplicate value is INSERT or UPDATE MySQL returns an error and the attempted
operation is not performed.
• UNIQUE
• The same rules as the PRIMARY KEY, with two exceptions:
Can have values stored as NULL
• Example:
The result of the SHOW INDEX statement example in the slide shows that there is a PRIMARY index
on the Code column of the Country table, and an index type of BTREE table. The Cardinality column
shows the number of distinct values that exist in the table: 239 in this case.
Note: Most indexes are stored in B-trees. Exceptions are indexes on spatial data types use R-trees, and
MEMORY tables also support hash indexes.
For more information about the SHOW INDEX statement, see the MySQL Reference Manual at
http://dev.mysql.com/doc/refman/5.5/en/show-index.html.
Table Constraints
• A constraint is a restriction placed on one or more column values of a table to actively enforce
integrity rules.
• Constraints are implemented using indexes.
• Types of constraints:
• PRIMARY KEY
• FOREIGN KEY
• UNIQUE
• MySQL generates indexes to enforce the above constraints.
A constraint is a restriction placed on one or more column values of a table to actively enforce integrity
rules.
• PRIMARY KEY: Defines the columns that guarantee uniqueness within a table
• FOREIGN KEY: Restricts the columns to contain only values that match those in another table’s
PRIMARY KEY or UNIQUE columns
• UNIQUE: The same as PRIMARY KEY except that the columns are allowed to be null-able,
and there may be multiple UNIQUE constraints in one table
For example, if the MySQL server allowed you to modify the world_innodb database by changing the
CountryCode value in the CountryLanguage table without changing the corresponding CountryCode
value in the City table, then you end up with rows that no longer point to valid country records (known as
orphaned rows). With constraints in place (FOREIGN KEY, in this case), the server raises an error if an
attempt is made to modify or delete data that is referenced by other tables, or it propagates the changes to
other tables for you.
Note: Only the InnoDB storage engine supports FOREIGN KEY constraints. Other storage engines
ignore these constraints in table definitions.
DROP DATABASE does not require the database to be empty. Before dropping the database, MySQL
removes any objects that it contains, such as tables, stored routines, and triggers.
A successful DROP DATABASE returns a row count that indicates the number of tables dropped. (This
actually is the number of .frmfiles removed, which amounts to the same thing.) You can check your
current databases to make sure that the database is removed by using the SHOW DATABASES
statement.
A database is represented by a directory under the data directory. The server deletes only files and
directories that it can identify as having been created by itself (such as .frm files). It does not delete other
files and directories. If you have put nontable files in that directory, those files are not deleted by the
DROP DATABASE statement. This results in a failure to remove the database directory. In that case, the
database continues to be listed by SHOW DATABASES. To correct this problem, you can manually
remove the database directory and any files that it contains.
Any warning generated by DROP DATABASE can be displayed with the SHOW WARNINGS
statement.
• Adding a column to a table populates the rows with NULL, the default value as specified, or the
data type implicit default.
• In a query, the column appears as empty or zero:
Note: The statement for populating a table with data is covered in detail later in the course.
Removing a Table Column
You should not remove a column from a table if it is a primary key. You cannot remove a column that is a
foreign key from another table.
For more information about using ALTER TABLE, see the MySQL Reference Manual at:
http://dev.mysql.com/doc/refman/5.5/en/alter-table.html.
If you also want to disallow NULL in the column, you must include the NOT NULL attribute in the
column definition for MODIFYCOLUMN, even if you originally defined the column with NOT NULL.
This is true for other column attributes as well. If you do not specify them explicitly, the new definition
does not carry them over from the old definition.
You cannot modify a column from a table if it is a primary key and if a foreign key from another table
references the column.
The previous ALTER TABLE...MODIFY COLUMN statement example changes the row contents of
the table as follows:
Note: The statement for populating a table with data is covered in detail later in the course.
Anything that can be added using CREATE TABLE can be changed using ALTER TABLE.
For more information about using ALTER TABLE, see the MySQL Reference Manual at:
http://dev.mysql.com/doc/refman/5.5/en/alter-table.html.
Truncate a 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.
truncate command is different from delete command. delete command will delete all the rows from a
table whereas truncate command re-initializes a table(like a newly created table).
For e.g. If you have a table with 10 rows and an auto_increment primary key, if you use delete command
to delete all the rows, it will delete all the rows, but will not initialize the primary key, hence if you will
insert any row after using delete command, the auto_increment primary key will start from 11. But in case
of truncate command, primary key is re-initialized.
Exercise
alter table product add column company_name varchar (255) not null;
LAB # 06
The Purpose of this Lab is to introduce the DML (Data Manipulation
Language) which includes Insert, Update & Delete Statements
___________________
Lab Instructor Signature
06
Objective
The Purpose of this Lab is to introduce the DML (Data Manipulation Language) which includes
Insert, Update & Delete Statements
Theory
The DML SQL statements are used to manipulate database and table data. The statements shown in the
slide are followed by options to specify data operations (such as table name).
• Do not grant users (including yourself) more permissions than required. For example, if
you are running some ad hoc queries on a database for the finance department, do not use
the MySQL root account. Instead, create a user who has permission to run only the
needed SELECT queries and then log in as the user.
• Keep daily backups of the data stored in MySQL.
• Always make a backup before you make any major changes, or when using unfamiliar
features.
• For beginners, a useful startup option is the safe updates option. It can be turned on with
the command-line client option --safe-updates, or by issuing SET
SQL_SAFE_UPDATES=1. It is helpful for cases when you might have issued a
DELETE FROM tbl_name statement but forgotten the WHERE clause. Normally,
such a statement deletes all rows from the table. With this option, you can delete rows
only by specifying the key values that identify them. This helps prevent accidents.
• Test queries and updates on a test table before running them on the real table.
• Execute a SELECT statement with the same WHERE clause to verify that the right
results are returned, before running a DELETE or an UPDATE statement.
INSERT Statement
The syntax for INSERT uses separate column and value lists following the name of the table into which
you add the single record. The number of columns and values must be the same.
In the INSERT example in the slide, you add Chinese as a language for Albania, with a percentage of
20, and the default F (false) for the IsOfficial column is acceptable because it is not the official language
of the country.
In the result for the example in the slide, the false (F) value for the IsOfficial column is the default value,
which is used in the absence of a specific assignment.
In the INSERT example in the slide, you add MySQL as a language for Greenland, Fiji, and Belgium.
However, you do not want to give it a percentage, and the default F (false) for the IsOfficial column is
acceptable. The row data for each of the three rows is enclosed in parentheses.
The result for the example in the slide is achieved with the following query:
In the example result in the slide, the F (false) value for the IsOfficial column is the default value, which
is used in the absence of a specific assignment.
Note: You must enclose all column values in single quotation marks (for string and temporal data types)
in the INSERT statement.
UPDATE Statement
The example in the slide demonstrates how you can update the Country database by changing the
Population column calculation and the Region to Dolphin Country for the country Sweden (code
'SWE'). The results show one row affected, one row matched (selected by the WHERE clause), and one
row changed.
• There is no guarantee about the order in which rows are updated, which can result in errors:
To solve the problem of the first UPDATE in the slide that causes an error, add an ORDERBY clause to
cause the row updates to occur in a particular order, as shown in the second UPDATE.
The results shown in the slide are a result of the following query:
+------+----------------+-------------+---------------+------------+
...
+------+----------------+-------------+---------------+------------+
DELETE Statement
• Use DELETE to remove whole, specified table rows instead of individual columns
• General syntax:
• Use DELETE with extreme caution, because it does not have the “undo” feature.
The DELETE result indicates the number of rows affected, which can be zero (0) if the statement did not
cause a change to be made.
Exercise
Question 1
___________________
Lab Instructor Signature
07
Objective
The Purpose of this Lab is to introduce the DCL (Data Control Language) which includes Grant &
Revoke Statements
Theory
Data Control Language (DCL) is used to control privilege in Database. To perform any operation in the
database, such as for creating tables, sequences or views we need privileges. Privileges are of two types,
● System: creating session, table etc are all types of system privilege.
● Object: any command or query to work on tables comes under object privilege.
Exercise
Question 1
Question 2
___________________
Lab Instructor Signature
08
Objective
The Purpose of this Lab is to get familiar with basic Select Queries which includes Selection &
Projection Queries & Some Built-in Functions
Theory
SELECT Statement
SELECT is the most commonly used data manipulation language (DML) statement. The SELECT
statement forms a description of the data that is to be retrieved from the database. It does not specify
exactly how the data is to be retrieved. The result returned by the database server in response to a
SELECT statement takes the form of a table, which is a collection of rows.
An expression that does not contain any column name is allowed in <column_list>.
SELECT example:
Projection, which retrieves all the rows in the Name and Rating columns from the Sailor table. Queries
can be performed on one, multiple, or all columns, on one or more tables.
For example, you can retrieve all the column data from the Sailortable, using (*):
Note: The word “query” is most commonly used to describe a SELECT statement.
Optional clauses can be used alone (or in combination) to generate specific query results.
• Types of clauses:
• DISTINCT: Eliminates duplicate rows from the result set
• FROM: Specifies what tables to retrieve data from
• WHERE: Filters for specific rows
• ORDER BY: Sorts rows by specified order
• Syntax example (with the order of the clauses fixed):
The syntax example in the slide shows the correct order and usage of each of the listed optional clauses.
This statement performs the following:
Without DISTINCT
mysql>SELECT rating FROM sailor
With DISTINCT
Subset of Relation can be obtained using Some Condition (or Using Where Clause)
• Arithmetic:+, -, *, /, DIV, %
• Comparison:<, <=, =, <=>, <> or !=, >=, >, BETWEEN
• Logical:AND, OR, XOR, NOT
• Additional options:IN, IS NULL, LIKE, ()
Arithmetic Operators
• + Addition
• - Subtraction
• * Multiplication
• / Division
• DIV Integer division
• % Modulo (remainder after division)
Comparison Operators
• + Addition
• < Less than
• <= Less than or equal to
• = Equal to
• <=> Equal to (works even for NULL values)
• <> or != Not equal to
• >= Greater than or equal to
• > Greater than
• BETWEEN <value1> AND <value2>Indicate a range of values (inclusive)
Logical Operators
• IN is equivalent to a list of comparisons with OR, but more readable and efficient.
• You can use IS NULL to check whether a value is null (such as ... <column_name> IS NULL).
• The LIKE operator can be used for pattern matching (such as WHERE <value>LIKE
'<pattern>').
• You can also use parentheses (<expression>) to group parts of an expression.
• Operators can be applied to almost all types of value expressions such as literals, columns,
function calls, and so on.
• You can also combine several criteria with logical operators.
SELECT with WHERE
FROM sailor
By default, the server returns the rows in the SELECT statement to the client in no particular order.
When you issue a query, the server is free to return the rows in any convenient order. This order can be
affected by factors such as the order in which the rows are actually stored in the table, or which indexes
are used to process the query. If you require output rows to be returned in a specific order, include an
ORDER BY clause that indicates how to sort the results.
The example in the slide sorts the names of the countries in alphabetical order by sname, from the
sailortable.
Previous Example With ORDER By Clause:
mysql> SELECT sid, sname, rating
FROM sailor
WHERE age>30 AND (rating = 3 OR rating = 8)
ORDER BY sname
SELECT with ORDER BY with ASC and DESC
● Specify order with ASC and DESC
– ASC: Ascending order (default)
– DESC: Descending order
● Example of ORDER BY with DESC:
mysql> SELECT sname
FROM sailor
ORDER BY sname DESC
Ascending order is the default sort order in an ORDER BY clause. You can specify explicitly whether to
sort a column in ascending or descending order by using the ASC or DESC keywords after the column
names. Ascending means that the lowest value comes first.
Functions
MySQL Expressions
• Returns the part of the string starting at the specified position, and the number of characters
indicated:
The Date/Time formats chart in the slide gives a list of all date and time formats permitted to be used
within temporal functions.
See the Data Types lesson for specific information about the values and ranges for these format types.
Functions that expect date values usually accept DATETIME values and ignore the time part. Functions
that expect time values usually accept DATETIME values and ignore the date part.
• Addition of a specified interval of days from the current date and time:
• Rounding
• Truncation
• Trigonometric calculations
• Generating random numbers
ROUND (<number>):
• Geometric functions:
• DEGREES(), PI(), RADIANS()
• Trigonometric functions:
• COS(), SIN(), COT()
• ACOS(), ASIN(), ATAN(), ATAN2()
• Other functions:
• EXP(), LN(), LOG(), LOG2(), LOG10()
• POWER(), SQRT()
• MOD()
Exercise
Emp_num Emp_Name Emp_Job Emp_Sal
1. List all employees’ number, employee’s name and jobs from emp.
select emp_num,Emp_name,Emp_job from employe;
2. List all employees’ number, employee’s name and jobs from emp whose salaries greater than 5,000.
select emp_num,Emp_name,Emp_job from employe where emp_sal>5000;
3. List all employees’ number, employee’s name and jobs from emp whose salaries less than 5,000.
4. List all employees’ number, employee’s name and jobs from emp whose salaries between 1,000 to
5,000.
select emp_num,Emp_name,Emp_job from employe where emp_sal between 1000 and 5000;
5. List all employees’ number, employee’s name, jobs and salaries from emp.
select * from employe;
Feedback
LAB # 09
The Purpose of this Lab is to get familiar the Tables Joins Which Includes
Inner, Outer & Natural Joins
___________________
Lab Instructor Signature
09
Objective
The Purpose of this Lab is to get familiar the Tables Joins Which Includes Inner, Outer & Natural
Joins
Theory
The SELECT queries shown so far in this course retrieve data from a single table at a time. This lesson
addresses the performance of multiple table queries.
If you want to find the details of records referenced in a foreign key, you combine data from two or more
tables by performing a table join.
A cross-join between two tables each containing 1000 rows will return 1000 × 1000 = 1 million rows.
That is a lot of rows, even though the individual tables are small. Such a join is also called an unqualified
join.
Categories of Joins
The syntax discussed earlier uses the comma separator in the FROM clause to name (and separate) the
joined tables. Another inner join syntax uses the INNER JOIN keywords. With this syntax, those
keywords replace the comma separator between table names. Also with INNER JOIN, the conditions
that indicate how to perform row matching for the tables move from the WHERE clause to become part
of the FROM clause.
Note: ON and USING are not exactly identical. USING treats the columns from the two tables as the
same, whereas ON treats them as two different columns.
JOIN Keywords
Note: The INNER JOIN keywords are equivalent to the JOIN keyword, and they can be used
interchangeably.
Outer Joins
The LEFT JOIN and RIGHT JOIN answer the same kinds of questions, but differ slightly in their
syntax. A LEFT JOIN can always be rewritten into an equivalent RIGHT JOIN.
In the above example, the LEFT JOIN results in a list that shows where there were NULLs for those
sailor who were not reserved any boat:
Natural Join
● The associated tables have one or more pairs of identically named columns.
● The columns must be the same data type.
● Don’t use ON clause in a NATURAL JOIN.
● Example
mysql> SELECT s.sname
FROM sailor s NATURAL JOIN reserves r
Exercise
Question No. 1
We have the following tables which creates statement are
1. create table supplier(S_NO int identity(1,1), SUP_ID varchar(50) primary key,SUP_NAME
varchar (50), SUP_ADD varchar (50), SUP_NIC int, rank int)
2. create table Product(Prod_ID varchar(50) primary key,Prod_Name varchar(50),[Price/Unit] float)
3. create table Orders(Ord_ID varchar(50) primary key,Prod_ID varchar(50),Qty int,Totalrate
int,SUP_ID varchar (50))
Write the Queries using Joins on above tables
1. List of all supplier that palced order
2. SELECT S.S_NO,S.SUP_NAME,S.SUP_ADD,S.RANK,S.SUP_ID FROM ORDERS O INNER
JOIN SUPPLIER S
ON O.SUP_ID=S.SUP_ID;
Feedback
LAB # 10
The Purpose of this Lab is to get familiar that how to use Groups & Having
Clauses with Aggregates Functions
___________________
Lab Instructor Signature
10
Objective
The Purpose of this Lab is to get familiar that how to use Groups & Having Clauses with
Aggregates Functions
Theory
Aggregate Functions
All the functions can use the DISTINCT keyword, although it is not useful for the MAX() and MIN()
functions.
DISTINCT examples:
SUM(DISTINCT <column_name>)
AVG(DISTINCT <column_name>)
COUNT(DISTINCT <column_name>)
GROUP BY
• The GROUP BY clause places rows into groups.
• Each group consists of rows having the same value in one or more columns.
• Calculates a summary value for each group
• General Syntax:
SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
GROUP BY grouping-list
• Example:
mysql> SELECT rating, COUNT(sid)
FROM sailor
GROUP BY rating
In above Example, group is make on rating column and count the no. of sailor for each rating.
Find no. of sailor for each rating in which sailor age must be greater than 25
mysql> SELECT rating, COUNT(sid)
FROM sailor
WHERE age>25
GROUP BY rating
HAVING
• Use the HAVING clause to eliminate rows based on aggregate values.
• Evaluated after the grouping implied by GROUP BY
• General Syntax:
SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
GROUP BY grouping-list
HAVING group-qualification
• Example
mysql> SELECT rating, COUNT(sid)
FROM sailor
GROUP BY rating
HAVING COUNT(sid)>1
In above Example, group is make on rating column and count the no. of sailor for each rating which
rating have minimum sailor count is 2.
You can use the HAVING modifier to require that the groups produced by a GROUP BY clause satisfy
particular criteria.
As such, it resembles the WHERE clause. The difference is that the HAVING clause is evaluated after
the grouping implied by the GROUP BY clause. This means that the HAVING condition can refer to
aggregate functions. However, any part of a condition that can also appear in the WHERE clause should
not be in the HAVING clause. A good HAVING clause is always based on aggregate functions (because
these are not allowed in the WHERE clause).
Exercise
Question No. 1
1. List average salary of each job.
select avg(salary) from customers as avgsalary;
2. Find average and sum of all the salaries of each job excluding clerks.
SELECT avg(SALARY),sum(SALARY) FROM customer WHERE SALARY>all
( SELECT SALARY FROM customers WHERE dept ='clerk') and dept <>'clerk';
3. Find average and sum of the salaries of each job excluding salesmen', clerk' and 'manager'.
SELECT avg(SALARY),sum(SALARY) FROM customers
WHERE SALARY>all ( SELECT SALARY FROM customers
WHERE dept ='clerk' and dept='manager') and dept <>'clerk';
4. Find count, sum and average salaries of each job excluding salesmen', clerk' and 'manager'.
SELECT count(salary), avg(SALARY),sum(SALARY)
FROM customers
WHERE SALARY>all ( SELECT SALARY
FROM customers
WHERE dept ='clerk' and dept='manager') and dept <>'clerk';
___________________
Lab Instructor Signature
Theory
The ROLLUP operator is useful in generating reports that contain subtotals and totals. The ROLLUP
operator generates a result set that is similar to the result sets generated by the CUBE operator.
ROLLUP
● ROLLUP generates a result set that shows aggregates for a hierarchy of values in the selected
columns.
● General Syntax:
SELECT [DISTINCT] target-list
FROM relation-list
WHERE qualification
GROUP BY grouping-list
WITH ROLLUP
● Example:
mysql> SELECT rating, age, COUNT(sid)
FROM sailor
WHERE age>25
WITH ROLLUP
CUBE
● CUBE generates a result set that shows aggregates for all combinations of values in the selected
columns.
LIMIT
• Specifies the number of rows to output in result set
• Example withoutLIMIT:
mysql> SELECT bid,COUNT(sid)
FROM reserves
GROUP BY bid
ORDER BY bid DESC
Exercise
Question No. 1
1. Find the names of Top 10 employees which salaries are highest.
Ans. SELECT * FROM customers
ORDER BY salary DESC LIMIT 10;