DBMS FILE-12
DBMS FILE-12
MySQL queries are SQL functions that help us to access a particular set of records
from a database table. We can request any information or data from the database using
the clauses or, let’s say, SQL statements. For example, SQL Clauses receives a
conditional expression that can be a column name or valid term involving columns
where this supports the MySQL functions to calculate the result values for a table in
the database. There are generally four kinds of SQL Clauses in MySQL Server.
• WHERE Clause
• ORDER BY clause
• HAVING Clause
• GROUP BY Clause
WHERE Clause
WHERE clause allows filtering certain records that exactly match a specified condition.
Thus, it helps us to fetch only the necessary data from the database that satisfies the
given expressional conditions.. We can also use logical or comparison operators such
as LIKE,<,>,=, etc. with WHERE clause to fulfill certain conditions.
Syntax: SELECTColumn1,….ColumnFromTable_nameWHERE[condition];
Code
OUTPUT:
ORDER BY Clause:
The ORDER BY clause is used in SQL for sorting records. It is used to arrange the
result set either in ascending or descending order. When we query using SELECT
statement the result is not in an ordered form. Hence, the result rows can be sorted
when we combine the SELECT statement with the ORDER BY clause.
Syntax:
Code
OUTPUT:
GROUP BY Clause
The GROUP BY clause is used to group rows that have the same values in the result
set. This clause is generally used with aggregate functions that allow grouping the
query result rows by multiple columns. The aggregate functions are COUNT, MAX,
MIN, SUM, AVG, etc.
Syntax:
SELECT Column FROM Table WHERE condition GROUP BY Column [ORDER BY
Column];
Code
OUTPUT:
HAVING Clause
Actually, this clause is introduced to apply functions in the query with the WHERE
clause. In SQL, the HAVING clause was added because the WHERE clause could not
be applied with aggregate functions.
Syntax:
OUTPUT:
EXPERIMENT NO: 8
MySQL has several pre-defined sets of string functions, which can be applied to string
characters to perform several operations in SQL programming scenarios. A few of the
commonly used operations are RIGHT, used to fetch the number of characters in the
rightmost part of the string, CONCAT used for string concatenation, SPACE used to
get the return value for a number of space characters in a string, INSERT used to insert
a new string within another string specific to the position with the number of characters
to be inserted, etc.
ASCII(str):
Returns the ASCII value of the leftmost character of the string str.
Code
select Name,ASCII(Name) from student;
OUTPUT:
CHAR_LENGTH(str)
Returns the length of the string str in characters.
OUTPUT:
CONCAT(str1, str2, …., strn)
Returns a string formed by joining str1 to strn. If any sub-string is NULL, the result is
NULL.
Syntax:
Code
select Name,Gender,concat(Name,Gender) from student;
OUTPUT:
Syntax:
Code
select Name,Gender,field('F',Name,Gender) as final from student;
OUTPUT:
REPLACE(str, from_str, to_str)
Replaces all occurrences of sub-string from_str with sub-string to_str in the string str. It
is case-sensitive.
Code
OUTPUT:
REVERSE(str)
Reverses the string str.
Code
OUTPUT:
EXPERIMENT NO: 9
In SQL, dates are complicated for newbies, since while working with a database, the
format of the data in the table must be matched with the input data to insert. In various
scenarios instead of date, datetime (time is also involved with date) is used.
For storing a date or a date and time value in a database, MySQL offers the following
data types:
1.NOW()
Returns the current date and time.
Syntax:
SELECT NOW();
Code
Select now();
Output:
2.CURDATE()
Returns the current date.
Syntax:
SELECT CURDATE();
Output:
3.CURTIME()
Returns the current time.
Syntax:
SELECT CURTIME();
Output:
4.DATE()
Extracts the date part of a date or date/time expression.
Syntax:
Output:
5.EXTRACT()
Returns a single part of a date/time.
Syntax:
EXTRACT(unit FROM date);
Output:
EXPERIMENT NO: 10
Views in SQL are a kind of virtual table. A view also has rows and columns like tables,
but a view doesn’t store data on the disk like a table. View defines a customized query
that retrieves data from one or more tables and represents the data as if it was
coming from a single source.
We can create a view by selecting fields from one or more tables present in the
database. A View can either have all the rows of a table or specific rows based on
certain conditions.
Syntax:
CREATE VIEW view name AS
SELECT column1,column2 ………
FROM table name;
Code
create view show_view as
select name,dept
from student;
select * from show_view;
Output:
DELETE VIEWS in SQL
SQL allows us to delete an existing View. We can delete or drop View using
the DROP statement.
Syntax:
DROP VIEW view name;
Code
Drop view show_view;
Output:
Syntax:
INSERT INTO view name (column1, column2……) Values ( );
Code
values("Siddharth","Biotech");
Output:
Syntax:
DELETE FROM Details view WHERE condition;
Code
Delete from show_view where name= “Rahul”;
Output:
Syntax:
USE database name;
SHOW FULL TABLES WHERE table type LIKE “%VIEW”;
Output:
EXPERIMENT NO: 6
AIM: A detailed study of SQL data types and data type objects.
Data types are used to represent the nature of the data that can be stored in the
database table. For example, in a particular column of a table, if we want to store a
string type of data then we will have to declare a string data type of this column.
Data types mainly classified into three categories for every database.
BINARY(Size) It is equal to CHAR() but stores binary byte strings. Its size
parameter specifies the column length in the bytes. Default
is 1.
ENUM(val1, val2, It is used when a string object having only one value, chosen
val3,...) from a list of possible values. It contains 65535 values in an
ENUM list. If you insert a value that is not in the list, a blank
value will be inserted.
BIT(Size) It is used for a bit-value type. The number of bits per value is
specified in size. Its size can be 1 to 64. The default value is 1.
INT(size) It is used for the integer value. Its signed range varies from -
2147483648 to 2147483647 and unsigned range varies from 0 to
4294967295. The size parameter specifies the max display width
that is 255.
TIME(fsp) It is used to specify the time format. Its format is hh:mm:ss. Its
supported range is from '-838:59:59' to '838:59:59'
Table –
This database object is used to create a table in database.
Syntax :
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr][, ...]);
Example :
CREATE TABLE dept
(deptno NUMBER(2),
dname VARCHAR2(14),
loc VARCHAR2(13));
Output :
View –
This database object is used to create a view in database.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. The tables on which a view
is based are called base tables. The view is stored as a SELECT statement in the data
dictionary.
Syntax :
CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view
[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
[WITH READ ONLY [CONSTRAINT constraint]];
Example :
CREATE VIEW salvu50
AS SELECT employee_id ID_NUMBER, last_name NAME,
salary*12 ANN_SALARY
FROM employees
WHERE department_id = 50;
SELECT *FROM salvu50;
Output :
Sequence –
This database object is used to create a sequence in database.A sequence is a user
created database object that can be shared by multiple users to generate unique
integers. A typical usage for sequences is to create a primary key value, which must
be unique for each row.The sequence is generated and incremented (or decremented)
by an internal Oracle routine.
Syntax :
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
Example :
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999
NOCACHE
NOCYCLE;
Check if sequence is created by :
SELECT sequence_name, min_value, max_value,
increment_by, last_number
FROM user_sequences;
Index –
This database object is used to create a indexes in database.An Oracle server index is
a schema object that can speed up the retrieval of rows by using a pointer.Indexes can
be created explicitly or automatically. If you do not have an index on the column, then
a full table scan occurs.
An index provides direct and fast access to rows in a table. Its purpose is to reduce
the necessity of disk I/O by using an indexed path to locate data quickly. The index is
used and maintained automatically by the Oracle server. Once an index is created, no
direct activity is required by the user.Indexes are logically and physically independent
of the table they index. This means that they can be created or dropped at any time
and have no effect on the base tables or other indexes.
Syntax :
CREATE INDEX index
ON table (column[, column]...);
Example :
CREATE INDEX emp_last_name_idx
ON employees(last_name);
Synonym –
This database object is used to create a indexes in database.It simplify access to
objects by creating a synonym(another name for an object). With synonyms, you can
Ease referring to a table owned by another user and shorten lengthy object names.To
refer to a table owned by another user, you need to prefix the table name with the name
of the user who created it followed by a period. Creating a synonym eliminates the
need to qualify the object name with the schema and provides you with an alternative
name for a table, view, sequence,procedure, or other objects. This method can be
especially useful with lengthy object names, such as views.
Syntax :
CREATE [PUBLIC] SYNONYM synonym FOR object;
Example :
CREATE SYNONYM d_sum FOR dept_sum_vu;
EXPERIMENT NO: 11
Relational Algebra
Select Operation:
Syntax: σ condition(relation_name);
Output:
Output:
NAME CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
Union Operation:
o Suppose there are two tuples R and S. The union operation contains all the
tuples that are either in R or S or both in R & S.
o It eliminates the duplicate tuples. It is denoted by ∪.
Syntax: R ∪ S
CUSTOMER_NAME
Johnson
Smith
Hayes
Turner
Jones
Lindsay
Jackson
Curry
Williams
Mayes
Set Intersection:
o Suppose there are two tuples R and S. The set intersection operation contains
all tuples that are in both R & S.
o It is denoted by intersection ∩.
Syntax: R ∩ S
Output:
CUSTOMER_NAME
Smith
Jones
Set Difference:
o Suppose there are two tuples R and S. The set intersection operation contains
all tuples that are in R but not in S.
o It is denoted by intersection minus (-).
Syntax: R - S
Output:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
Cartesian product
o The Cartesian product is used to combine each row in one table with each row
in the other table. It is also known as a cross product.
o It is denoted by X.
Syntax: E X D
Code: EMPLOYEE X DEPARTMENT ;
Output:
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
Rename Operation:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• NATURAL JOIN
INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the
condition is satisfied. This keyword will create the result-set by combining all rows
from both the tables where the condition satisfies i.e value of the common field will
be the same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNERJOIN table2
ON table1.matching_column = table2.matching_column;
Code:
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
INNERJOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:
LEFT JOIN
LEFT JOIN returns all the rows of the table on the left side of the join and matches
rows for the table on the right side of the join. For the rows for which there is no
matching row on the right side, the result-set will contain null. LEFT JOIN is also
known as LEFT OUTER JOIN.
Syntax:
SELECTtable1.column1,table1.column2,table2.column1,....
FROMtable1
LEFTJOINtable2
ON table1.matching_column = table2.matching_column;
Code:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFTJOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
RIGHT JOIN
RIGHT JOIN returns all the rows of the table on the right side of the join and matching
rows for the table on the left side of the join. It is very similar to LEFT JOIN For the
rows for which there is no matching row on the left side, the result-set will
contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECTtable1.column1,table1.column2,table2.column1,....
FROMtable1
RIGHTJOINtable2
ON table1.matching_column = table2.matching_column;
Code:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHTJOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT
JOIN. The result-set will contain all the rows from both tables. For the rows for which
there is no matching, the result-set will contain NULL values.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULLJOIN table2
ON table1.matching_column = table2.matching_column;
Code:
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
FULLJOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4