SQL Lab Practical Guide
SQL Lab Practical Guide
SUBMITTED AT:
DELHI SCHOOL OF PROFESSIONAL STUDIES & RESEARCH
ROHINI, NEW DELHI-85
[AFFILIATED TO GGSIPU-NEW DELHI]
INDEX
S.No. CONTENT PgNo. T.SIGN
What is SQL?
SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.
SQL is the standard language for Relational Database System. All the Relational Database
Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix,
Postgres and SQL Server use SQL as their standard database language.
SQL Process
When you are executing an SQL command for any RDBMS, the system determines the
best way to carry out your request and SQL engine figures out how to interpret the task.
There are various components included in this process.
1
Lab Practical Information Management
Query Dispatcher
Optimization Engines
Classic Query Engine
SQL Query Engine, etc.
A classic query engine handles all the non-SQL queries, but a SQL query engine won't
handle logical files.
Following is a simple diagram showing the SQL Architecture −
Advantages of SQL:
* High Speed:
2
Lab Practical Information Management
Disadvantages of SQL:
* Difficulty in Interfacing:
Interfacing an SQL database is more complex
than adding a few lines of code.
* More Features Implemented in Proprietary way:
Question 2: Explain what are the different types of data types in SQL
MySQL uses many different data types broken into three categories −
Numeric
Date and Time
String Types.
3
Lab Practical Information Management
MySQL uses all the standard ANSI SQL numeric data types, so if you're coming to
MySQL from a different database system, these definitions will look familiar to you.
The following list shows the common numeric data types and their descriptions −
INT − A normal-sized integer that can be signed or unsigned. If signed, the
allowable range is from -2147483648 to 2147483647. If unsigned, the allowable
range is from 0 to 4294967295. You can specify a width of up to 11 digits.
TINYINT − A very small integer that can be signed or unsigned. If signed, the
allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to
255. You can specify a width of up to 4 digits.
SMALLINT − A small integer that can be signed or unsigned. If signed, the
allowable range is from -32768 to 32767. If unsigned, the allowable range is from
0 to 65535. You can specify a width of up to 5 digits.
MEDIUMINT − A medium-sized integer that can be signed or unsigned. If signed,
the allowable range is from -8388608 to 8388607. If unsigned, the allowable range
is from 0 to 16777215. You can specify a width of upto 9 digits.
BIGINT − A large integer that can be signed or unsigned. If signed, the allowable
range is from -9223372036854775808 to 9223372036854775807. If unsigned, the
allowable range is from 0 to 18446744073709551615. You can specify a width of
up to 20 digits.
FLOAT(M,D) − A floating-point number that cannot be unsigned. You can define
the display length (M) and the number of decimals (D). This is not required and
will default to 10,2, where 2 is the number of decimals and 10 is the total number
of digits (including decimals). Decimal precision can go to 24 places for a FLOAT.
4
Lab Practical Information Management
String Types
Although the numeric and date types are fun, most data you'll store will be in a string
format. This list describes the common string datatypes in MySQL.
CHAR(M) − A fixed-length string between 1 and 255 characters in length (for
example CHAR(5)), right-padded with spaces to the specified length when stored.
Defining a length is not required, but the default is 1.
VARCHAR(M) − A variable-length string between 1 and 255 characters in length.
For example, VARCHAR(25). You must define a length when creating a
VARCHAR field.
BLOB or TEXT − A field with a maximum length of 65535 characters. BLOBsare
"Binary Large Objects" and are used to store large amounts of binary data, such as
images or other types of files. Fields defined as TEXT also hold large amounts of
data. The difference between the two is that the sorts and comparisons on the stored
data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You
do not specify a length with BLOB or TEXT.
5
Lab Practical Information Management
SQL-DDL Commands
The DDL commands in SQL are used to create database schema and to define the type and
structure of the data that will be stored in a database. SQL DDL commands are further
divided into the following major categories:
CREATE
ALTER
DROP
TRUNCATE
CREATE
The CREATE query is used to create a database or objects such as tables, views, stored
procedures, etc.
Creating a database
The following example demonstrates how the CREATE query can be used to create a
database in MS SQL Server:
6
Lab Practical Information Management
Creating a table
The CREATE query is also used to add tables in an existing database as shown in the
following script:
USE Library
CREATE TABLE Books
(
Id INT PRIMARY KEY IDENTITY(1,1),
Name VARCHAR (50) NOT NULL,
Price INT
)
The above script creates a table named “Books” in the “Library” database that we created
earlier.
The “Books” table contains three columns: Id, Name, and Price. The Id column is the
primary key column and it cannot be NULL. A column with a PRIMARY KEY constraint
must contain unique values. However, since we have set the IDENTITY property for the Id
column, every time a new record is added in the Books table, the value of the Id column
will be incremented by 1, starting from 1. You need to specify the values for the Name
column as well as it cannot have NULL. Finally, the Price column can have NULL values.
To view all the tables in the Library, execute the following QL DDL script:
USE Library
SELECT * FROM INFORMATION_SCHEMA.TABLES
OUTPUT:
ALTER
By The use of ALTER TABLE Command we can modify our exiting table.
Adding New
Columns ALTER
Syntax: TABLE <table_name>
ADD (<NewColumnName>
The Student table is already exist and then we added two more columns Age and Marks
respectively, by the use of above command.
Dropping a Column from the Table
7
Lab Practical Information Management
Syntax:
ALTER TABLE <table_name> DROP COLUMN <column_name>
Example:
ALTER TABLE Student DROP COLUMN Age;
The Name column already exist in Student table, it was char and size 30, now it is
modified by Varchar2 and size 40.
Restriction on the ALTER TABLE
Using the ALTER TABLE clause the following tasks cannot be performed.
8
Lab Practical Information Management
SQL-DML Commands
Data Manipulation Language (DML) statements or commands are used for managing data
within tables. Some commands of DML are:
Some commands of DML are:
SELECT – retrieve data from the a database
INSERT – insert data into a table
UPDATE – updates existing data within a table
DELETE – deletes all records from a table, the space for the records remain
MERGE – UPSERT operation (insert or update)
SELECT
Viewing Data in the Table (Select Command)
Once data has been inserted into a table, the next most logical operation would be to view
what has been inserted. The SELECT SQL verb is used to achieve this.
All Rows and All Columns
9
Lab Practical Information Management
It scans through entire rows, and eliminates rows that have exactly the same contents in
each column.
Sorting DATA:
The Rows retrieved from the table will be sorted in either Ascending or Descending order
depending on the condition specified in select statement, the Keyword has used ORDER
BY.
it will in show records as alphabetical order from A to Z ascending order. If you want
Descending order means Z to A then used DESC Keyword at last.
Syntax: INSERT INTO <table name> VALUES (<value 1>, ... <value
n>);
Example:
The inserted values must match the table structure exactly in the number of attributes and
the data type of each attribute. Character type values are always enclosed in single quotes;
number values are never in quotes; date values are often (but not always) in the format
‘yyyy- mm-dd’ (for example, ‘2006-11- 30’).
UPDATE :
The update statement is used to change values that are already in a table.
Example:
Syntax:
UPDATE
UPDATE STUDENT SET
<table name> Name
SET = ‘Amar’
<attribute> WHERE StudID=1001;
= <expression> WHERE <condition>;
10
Lab Practical Information Management
The update expression can be a constant, any computed value, or even the result of a
SELECT statement that returns a single row and a single column.
DELETE :
The delete statement deletes row(s) from a table.
Example:
Syntax:
STUDENT
DELETE FROM <table WHERE
name> StudID=1001;
WHERE <condition>;
If the WHERE clause is omitted, then every row of the table is deleted that matches with
the specified condition.
Question 5: Create table named customer (c_id, c_name, address, city, pincode ,
country) .Insert atleast 10 values .Display the table.
11
Lab Practical Information Management
12
Lab Practical Information Management
Question 6: Create the following table and perform SQL commands. Student (Roll_no, name,
age, course, marks).
13
Lab Practical Information Management
1. List all those students who are greater than 18 years of age and have
opted for MBA course.
4. Find out the name, course, marks and sort in the order of marks.
14
Lab Practical Information Management
15
Lab Practical Information Management
Table 1
16
Lab Practical Information Management
Table 2
Table 3
17
Lab Practical Information Management
The name of suppliers who supplies quantity of the item P1 more than 50 :
18
Lab Practical Information Management
An Entity is a thing or object in real world that is distinguishable from surrounding environment.
For example each employee of an organization is a separate entity. Following are some of major
characteristics of entities.
The building blocks of an ERD are entities, relationships and attributes. Entities have entity types,
which are known as instances of the corresponding entities. Each entity type can exist independently
of another; for example, the entity "vehicle" can have the entity types "car" and "bus." Relationship
is the property that links the entity types together. For example, the entity type husband is related to
the entity type wife by a relationship known as "is-married-to." Attributes are properties that belong
to the entity types as well as to the relationships.
There are a number of ER diagramming tools available on the market. The most common ones are
MySQL Workben
Components of the ER Diagram
Entities
Attributes
Relationships
Example
For example, in a University database, we might have entities for Students, Courses, and
Lecturers. Students entity can have attributes like Rollno, Name, and DeptID. They might have
relationships with Courses and Lecturers.ch and Open model Sphere.
19
Lab Practical Information Management
WHAT IS ENTITY?
A real-world thing either living or non-living that is easily recognizable and nonrecognizable. It is
anything in the enterprise that is to be represented in our database. It may be a physical thing or
simply a fact about the enterprise or an event that happens in the real world.
An entity can be place, person, object, event or a concept, which stores data in the database. The
characteristics of entities are must have an attribute, and a unique key. Every entity is made up of
some 'attributes' which represent that entity.
Examples of entities:
Notation of an Entity
Entity set
An entity set is a group of similar kind of entities. It may contain entities with attribute sharing
similar values. Entities are represented by their properties, which also called attributes. All attributes
have their separate values. For example, a student entity may have a name, age, class, as attributes.
Example of Entities:
A university may have some departments. All these departments employ various lecturers and offer
several programs.
20
Lab Practical Information Management
Some courses make up each program. Students register in a particular program and enroll in various
courses. A lecturer from the specific department takes each course, and each lecturer teaches a
various group of students.
Relationship
Relationship is nothing but an association among two or more entities. E.g., Tom works in the
Chemistry department.
Entities take part in relationships. We can often identify relationships with verbs or verb
A weak entity is a type of entity which doesn't have its key attribute. It can be identified uniquely by
considering the primary key of another entity. For that, weak entity sets need to have participation.
An entity relationship diagram showing relationships between sales reps, customers and
product orders.
For example, an ERD representing the information system for a company's sales department
might start with graphical representations of entities such as the sales representative, the
customer, the customer's address, the customer's order, the product and the warehouse. Then
lines
21
Lab Practical Information Management
or other symbols can be used to represent the relationship between entities, and text can be
used to label the relationships.
A cardinality notation can then define the attributes of the relationship between the entities.
Cardinalities can denote that an entity is optional (for example, a sales rep could have no
customers or could have many) or mandatory (for example, there must be at least one
product listed in an order.)
The three main cardinalities are:
A. Entity: - Any real-world object can be represented as an entity about which data can
be stored in a database. All the real world objects like a book, an organization, a
product, a car, a person are the examples of an entity. Any living or non-living objects
can be represented by an entity. An entity is symbolically represented by a rectangle
enclosing its name.
o Strong entity: A strong entity has a primary key attribute which uniquely
identifies each entity.
Symbol of strong entity is same as an entity
o Weak entity: A weak entity does not have a primary key attribute and depends
on other entity via a foreign key attribute.
22
Lab Practical Information Management
B. Attribute: - Each entity has a set of properties. These properties of each entity are
termed as attributes. For example, a car entity would be described by attributes such
as price, registration number, model number, color etc. Attributes are indicated by
ovals in an e-r diagram.
A primary key attribute is depicted by an underline in the e-r diagram. An attribute can
be characterized into following types:
• Simple attribute :- An attribute is classified as a simple attribute if it cannot be
partitioned into smaller components. For example, age and sex of a person. A simple attribute
is represented by an oval.
Multi valued attribute: – An attribute which can hold more than one value,
it is then termed as multi-valued attribute. For example, phone number of a
person. Symbol of multi- valued attribute is shown below,
23
Lab Practical Information Management
24
Lab Practical Information Management
Other types of relationships are ternary and quaternary. As the name signifies, a ternary
relationship is associated with three entities and a quaternary relationship is associated with
four entities.
Entity: A definable thins such as person, Object, concept or event that can have data stored
about it think of entities as noun.
In this ERD we have Four Entities: - Books, Readers, Staff, Authentication System
25
Lab Practical Information Management
Entity: A definable thins such as person, Object, concept or event that can have data stored
about it think of entities as noun.
In this ERD we have five Entities: - Student, University, College, Course, Faculty.
26
Lab Practical Information Management
PRIMARY KEY: - The field that is unique for all the record occurrences.it denotes as
Underline. In this ERD we have Stu_id In Student, Uni_id in University, Clg_id in
College, Course_id in Course, Fac_name in Faculty.
27