Experiments 1 15
Experiments 1 15
Experiments 1 15
Introduction to MySQL
MySQL is an open source database management software that helps users store, organize, and
retrieve data. It is a very powerful program with a lot of flexibility.
We can access the MySQL shell by typing the following command into terminal:
mysql -u root -p
After entering the root MySQL password into the prompt , you will be able to start building your
MySQL database.
A MySQL database server contains many databases (or schemas). Each database consists of one
or more tables. A table is made up of columns (or fields) and rows (records).
The SQL keywords and commands are NOT case-sensitive. For clarity, they are shown in
uppercase. The names or identifiers (database names, table names, column names, etc.) are case-
sensitive in some systems, but not in other systems. Hence, it is best to treat identifiers as case-
sensitive.
SHOW DATABASES;
You can use SHOW DATABASES to list all the existing databases in the server.
Database-Level:
DROP DATABASE databaseName -- Delete the database (irrecoverable!)
DROP DATABASE IF EXISTS databaseName -- Delete if it exists
CREATE DATABASE databaseName -- Create a new database
CREATE DATABASE IF NOT EXISTS databaseName -- Create only if it does not exists
SHOW DATABASES -- Show all the databases in this server
USE databaseName -- Set the default (current) database
SELECT DATABASE() -- Show the default database
SHOW CREATE DATABASE databaseName -- Show the CREATE DATABASE
statement
Table-Level:
DROP TABLE [IF EXISTS] tableName, ...
CREATE TABLE [IF NOT EXISTS] tableName (
columnName columnType columnAttribute, ...
PRIMARY KEY(columnName),
FOREIGN KEY (columnNmae) REFERENCES tableName (columnNmae)
)
SHOW TABLES -- Show all the tables in the default database
DESCRIBE|DESC tableName -- Describe the details for a table
ALTER TABLE tableName ... -- Modify a table, e.g., ADD COLUMN and DROP COLUMN
ALTER TABLE tableName ADD columnDefinition
ALTER TABLE tableName DROP columnName
ALTER TABLE tableName ADD FOREIGN KEY (columnNmae) REFERENCES tableName
(columnNmae)
ALTER TABLE tableName DROP FOREIGN KEY constraintName
SHOW CREATE TABLE tableName -- Show the CREATE TABLE statement for this
tableName
Row-Level:
INSERT INTO tableName VALUES (column1Value, column2Value,...) -- Insert on all
Columns
INSERT INTO tableName VALUES (column1Value, column2Value,...), ... -- Insert
multiple rows
INSERT INTO tableName (column1Name, ..., columnNName) VALUES (column1Value, ...,
columnNValue) -- Insert on selected Columns
DELETE FROM tableName WHERE criteria
UPDATE tableName SET columnName = expr, ... WHERE criteria
SELECT * | column1Name AS alias1, ..., columnNName AS aliasN
FROM tableName
• Some numeric data may also be stored as a character field e.g. zip codes
• Common Numeric Types:
Decimal :Floating point number
Float: Floating point number
Integer(size):Integer of specified length
Money: A number which contains exactly two digits after the decimal point
Number:A standard number field that can hold a floating point data.
Database changed
6. To add a new column called “SEM” to the existing table STUDENT and whose default
value is “4”
+-------+-------------+------+-----+---------+-------+
Example:
mysql> DROP TABLE ENROLL1;
Query OK, 0 rows affected (0.08 sec)
ii)Delete Statement:
It is used to remove records from a table of the database. The where clause in the syntax is used
to restrict the rows deleted from the table otherwise all the rows from the table are deleted.
Syntax: DELETE FROM table_name [WHERE Condition]
Example:
DELETE FROM STUDENT
WHERE SNAME = ‘Ramesh’
• Deletes all the rows where the sname is ‘Ramesh’ keeps all the other rows.
It is used to make changes to existing rows of the table. It has three parts. First, you ,must specify
which table is going to be updated. The second part of the statement is the set clause, in which
you should specify the columns that will be updated as well as the values that will be inserted.
Finally, the where clause is used to specify which rows will be updated.
Syntax:
UPDATE table_name
SET column_name1 = value1, column_name2 = value2, …..
[WHERE Condition]
Example:
UPDATE STUDENT SET SNAME = ‘Vignesh’, MAJOR = ‘IS’
WHERE snum = 1;
1. Inserting Data into Tables: - once a table is created the most natural thing to do is load this
table with data to be manipulated later.
Syntax:
i)insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>);
mysql> INSERT INTO STUDENT(SNUM,SNAME,MAJOR,DOB,SEM) VALUES
(1001,'CHETHAN','CSE','2000-05-03',4);
Query OK, 1 row affected (0.07 sec)
2. Delete operations.
+---------+-------------+------+-----+---------+----------------+
4 rows in set (0.03 sec)
i)Entity Integrity Constraint: Primary Key Value cannot be NULL and duplicate.
mysql> INSERT INTO STUDENT VALUES (NULL,'CHETHAN','CSE','2000-20-03',4);
ERROR 1048 (23000): Column 'SNUM' cannot be null.
mysql> INSERT INTO STUDENT(SNUM,SNAME,MAJOR,DOB,SEM) VALUES
(1001,'CHETHAN','CSE','2000-05-03',4);
ERROR 1062 (23000): Duplicate entry '1001' for key 'PRIMARY'.
Operators in SQL:
The following are the commonly used operators in SQL
Arithmetic Operators +, -, *, /
Relational Operators =, <, >, <=, >=, <>
Logical Operators OR, AND, NOT
Arithmetic operators are used to perform simple arithmetic operations.
Relational Operators are used when two values are to be compared and
Logical operators are used to connect search conditions in the WHERE Clause in SQL.
SELECT Command:
SELECT count(*) AS “Total Number of Records” FROM student;
Display the total number of records with title as “Total Number of Records” i.e an alias
DISTINCT keyword is used to restrict the duplicate rows from the results of a SELECT
statement.
e.g. SELECT DISTINCT name FROM student;
e.g SELECT Roll_no, name, city FROM student WHERE Roll_no LIKE “%3”;
displays those records where last digit of Roll_no is 3 and may have any number of characters in
front.
Illustration:
1. Viewing data in the tables: - once data has been inserted into a table, the next most logical
operation would be to view what has been inserted.
a) all rows and all columns
Syntax: Select <col> to <col n> from tablename;
mysql> SELECT * FROM STUDENT;
+------+----------------+-------+------------+------+
| SNUM | SNAME | MAJOR | DOB | SEM |
+------+----------------+-------+------------+------+
| 1001 | CHETHAN | ECE | 2000-11-03 | 4 |
| 1002 | CHETHAN CHAVAN | ISE | 2000-11-03 | 4 |
+------+----------------+-------+------------+------+
2 rows in set (0.00 sec)
2. Filtering table data: - while viewing data from a table, it is rare that all the data from table
will be required each time. Hence, sql must give us a method of filtering out data that is not
required data.
a) All columns and all rows:
Syntax: select <col1>,<col2> from <tablename>;
mysql> SELECT * FROM STUDENT;
+------+----------------+-------+------------+------+
| SNUM | SNAME | MAJOR | DOB | SEM |
+------+----------------+-------+------------+------+
| 1001 | CHETHAN | ECE | 2000-11-03 | 4 |
| 1002 | CHETHAN CHAVAN | ISE | 2000-11-03 | 4 |
+------+----------------+-------+------------+------+
2 rows in set (0.00 sec)
| 104 | 4CSE5 |
| 105 | 4CSE5 |
| 106 | 4CSE5 |
| 101 | 4CSE6 |
| 102 | 4CSE7 |
| 103 | 4CSE8 |
| 104 | 4CSE9 |
+------+--------------+
14 ows in set (0.00 sec)
Basic Queries:
1. Add the columns 'Fees' & 'Email' to the STUDENT table with default value '30000' &
'[email protected]'.
9.Display the details of the student whose student name starts with letter A.
Experiment No.5: To study and implement different SQL single row and
multiple row functions.
Functions available in SQL:
SQL provide large collection of inbuilt functions also called library functions that can be used
directly in SQL statements.
1. Mathematical functions
2. String functions
3. Date & Time functions
1.Mathematical functions:
Some of the commonly used mathematical functions are sum() avg(), count(), min(), max() etc.
Example: SELECT sum(marks) FROM student;
displays the sum of all the marks in the table student.
Example: SELECT min(Roll_no), max(marks) FROM student;
displays smallest Roll_no and highest marks in the table student.
2. String functions:
These functions are used to deal with the string type values like
ASCII, LOWEWR, UPPER, LENGTH,LEFT, RIGHT, TRIM, LTRIM, RTRIM etc.
ASCII : Returns the ASCII code value of a character (leftmost character of string).
Syntax: ASCII(character)
Example:
Note:
For Upper character 'A' to 'Z' ASCII value 65 to 90
For Lower character 'A' to 'Z' ASCII value 97 to 122
For digit '0' to '9' ASCII value 48 to 57
LEFT : Returns left part of a string with the specified number of characters counting from
left.LEFT function is used to retrieve portions of the string.
Syntax: LEFT(string,integer)
SELECT LEFT('STRING FUNCTION', 6)
returns STRING
HAVING Clause
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a
SELECT statement to filter the records that a GROUP BY returns.
The syntax for the HAVING clause is:
SELECT column1, column2, ... column_n, aggregate_function (expression)
FROM tables
WHERE predicates
GROUP BY column1, column2, ... column_n
HAVING condition1 ... condition_n;
ORDER BY Clause
ORDER BY clause is used to display the result of a query in a specific order(sorted order).
The sorting can be done in ascending or in descending order. It should be kept in mind that the
actual data in the database is not sorted but only the results of the query are displayed in sorted
order.
Example: SELECT name, city FROM student ORDER BY name;
The above query returns name and city columns of table student sorted by name in
increasing/ascending order.
Example: SELECT * FROM student ORDER BY city DESC;
It displays all the records of table student ordered by city in descending order.
Note:- If order is not specifies that by default the sorting will be performed in ascending
order.
BRANCH TABLE
CREATE TABLE BRANCH (BR_NAME VARCHAR(20) PRIMARY KEY, BR_CITY
VARCHAR(20), ASSETS REAL);
ACCOUNT TABLE
CREATE TABLE ACCOUNT (ACCNO INT PRIMARY KEY, BR_NAME VARCHAR(20),
BALANCE REAL, FOREIGN KEY (BR_NAME) REFERENCES BRANCH (BR_NAME) ON
DELETE CASCADE);
CUSTOMER TABLE
CREATE TABLE CUSTOMER (CUST_NAME VARCHAR(20) PRIMARY KEY,
CUST_STREET VARCHAR (20), CUST_CITY VARCHAR (20));
DEPOSITOR TABLE
CREATE TABLE DEPOSITOR (CUST_NAME VARCHAR (20), ACCNO INT, PRIMARY
KEY (CUST_NAME, ACCNO), FOREIGN KEY (CUST_NAME) REFERENCES
CUSTOMER (CUST_NAME) ON DELETE CASCADE, FOREIGN KEY (ACCNO)
REFERENCES ACCOUNT (ACCNO) ON DELETE CASCADE);
LOAN TABLE
CREATE TABLE LOAN (LOAN_NO INT PRIMARY KEY, BR_NAME VARCHAR (20),
AMOUNT REAL, FOREIGN KEY (BR_NAME) REFERENCES BRANCH (BR_NAME) ON
DELETE CASCADE);
BORROWER TABLE
Write and Execute the SQL Queries for the following statements:
1. Find bank accounts with a balance greater than 20000
SELECT ACCNO,BALANCE
FROM ACCOUNT
WHERE BALANCE>20000;
SELECT ACCNO,BALANCE
FROM ACCOUNT
WHERE BALANCE>20000
ORDER BY BALANCE DESC;
3. Retrieve a list of all bank branch details, ordered by branch city, with each city’s branches
listed in reverse order of assets.
SELECT AVG(BALANCE)
FROM ACCOUNT WHERE BR_NAME= 'SADASHIVANAGAR';
1.UNION OPERATION:
SELECT EMP_ID FROM EMPLOYEE
UNION
SELECT DEPT_ID FROM DEPARTMENT ORDER BY EMP_ID;
Output:
2. INTERSECTION OPERATION
SELECT EMP_ID FROM
EMPLOYEE
WHERE EMP_ID IN(SELECT DEPT_ID FROM DEPARTMENT);
Output:
3.MINUS/DIFFERENCE OPEARATION:
SELECT EMP_ID
FROM EMPLOYEE
WHERE EMP_ID NOT IN(SELECT DEPT_ID FROM DEPARTMENT);
4.CARTESIAN PRODUCT
select * from employee cross join department;
SQL JOIN
SQL Join is used to fetch data from two or more tables, which is joined to appear as single set of
data. It is used for combining column from two or more tables by using values common to both
tables.
JOIN Keyword is used in SQL queries for joining two or more tables. Minimum required
condition for joining table, is (n-1) where n, is number of tables. A table can also join to itself,
which is known as, Self Join.
Types of JOIN:
Following are the types of JOIN that we can use in SQL:
Inner
Outer
Left
Right
OUTER JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
The left outer join returns a resultset table with the matched data from the two tables and then
the remaining rows of the left table and null from the right table's columns.
Syntax for Left Outer Join is,
SELECT column-name-list FROM
table-name1 LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
OUTER JOIN:
1. LEFT OUTER JOIN OR LEFT JOIN
SELECT *
FROM EMPLOYEE E LEFT JOIN DEPARTMENT D ON E.DEPT_NUM=D.DEPT_ID;
SELECT *
FROM DEPARTMENT NATURAL JOIN EMPLOYEE
A complete SELECT query, called a nested query, can be specified within the WHERE-
clause of another query, called the outer query.
Syntax:
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Subqueries:
A subquery is a SELECT statement that is embedded in a clause of another SELECT statement.
They can be very useful when you need to select rows from a table with a condition that
depends on the data in the table itself.
You can place the subquery in a number of SQL clauses:
WHERE clause
HAVING clause
FROM clause
The comparison operator IN compares a value v with a set (or multi-set) of values V, and
evaluates to TRUE if v is one of the elements in V. The subquery (inner query) executes once
before the main query. The result of the subquery is used by the main query (outer query).
Single-Row Subqueries:
• Return only one row
• Use single-row comparison operators(=, >,<= ,>= ,< >)
Multiple-Row Subqueries:
• Return more than one row
• Use multiple-row comparison operators( IN, ANY, ALL)
An Example:
SCHEMA Diagram of Student Database:
1. Find the names of all Juniors (level = JR) who are enrolled in a Class taught by
Prof.Narasimha.
+----------+
| SNAME |
+----------+
| ABHI |
+----------+
1 row in set (0.00 sec)
2. Find the names of all Classes that either meet in room KG04 or have five or more
Students enrolled.
mysql> SELECT C.CNAME
-> FROM CLASS C
-> WHERE C.ROOM='KG04' OR C.CNAME IN
-> (SELECT E.CNAME
-> FROM ENROLLED E
-> GROUP BY E.CNAME
-> HAVING COUNT(*)>=5);
+------------+
| CNAME |
+------------+
| 4CSE10 |
+------------+
1 row in set (0.03 sec)
3. Find the names of all students who are enrolled in two classes that meet at the same time
5. Find the names of faculty members for whom the combined enrolment of the courses
that they teach is less than five.
+--------------------+
| FNAME |
+--------------------+
| JAMES |
| SUNIL |
| SUKRUTH |
| NARASIMHA |
| AFROZ |
| JOHN |
| AHMED |
| SUNITHA |
| SRIVINAY |
+-------------------+
SCHEMA DIAGRAM:
SCHEMA DIAGRAM
BRANCH
DEPOSITOR
ACCOUNT
CNAME ACCNO
ACCNO BNAME BALANCE
CUSTOMER
LOAN BORROWER
2.Find all the customers who have at least two accounts at the Main branch.
SELECT D.CUST_NAME
FROM DEPOSITOR D, ACCOUNT A
WHERE A.ACCNO=D.ACCNO AND A.BR_NAME= 'SADASHIVANAGAR'
GROUP BY D.CUST_NAME
HAVING COUNT (D.CUST_NAME) >=2;
3.Find all the customers who have an account at all the branches located in a specific city.
SELECT D.CUST_NAME
FROM BRANCH B, ACCOUNT A, DEPOSITOR D
WHERE B.BR_NAME=A.BR_NAME AND A.ACCNO=D.ACCNO AND
B.BR_CITY=‘BANGALORE’
GROUP BY D.CUST_NAME
HAVING COUNT (DISTINCT A.BR_NAME) =
(SELECT COUNT (*)
FROM BRANCH
WHERE BR_CITY=‘BANGALORE’);
4. Demonstrate how you delete all account tuples at every branch located in a specific city.
Views are relations, except that they are not physically stored.
Views are created for presenting different information to different users
A view is a “virtual table” or a “stored query” which takes the output of a query and treats it as a
table. The table upon which a view is created is called as base table.
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
OBJECTIVE
SQL COMMANDS
Creating views:
Syntax:
Create view <view name>;
Description:
This command is used to create view by combining two tables.
Viewing single row of table:
Syntax:
Create view<view name> as select from <table name>;
Description:
This command is used to view a single row from a particular table.
Viewing all columns from a single table:
Syntax:
Create view<view name> as select * from <table name>;
Description :
This is used to create view which displays all columns from a single table.
Syntax:
Create view<view table name> as select * from <table name> where ‘condition’;
Description:
This is used to create view which displays all the columns of a table.
Inserting into views:
Syntax:
Insert into <view name> values <’data1’,’data2’,……>;
Description:
This is used to do inserting of information or data into values.
Updating in view: is done by using query materialization and query modification.
Deleting a view:
Syntax:
Drop view <view name>;
Illustration:
mysql> use studentdb;
Database changed
1.Create a simple view named as “Studentdetails”
Solution:
mysql> create view studentdetails as
-> select * from student;
Query OK, 0 rows affected (0.30 sec)
2.To retrieve all the data in the studentdetails view
Solution:
Query on a view.
3. Retieve the name and id student of ‘cse’ department(major).
mysql> select snum, sname from studentdetails where major='cse';
+------+-------+
| snum | SNAME |
+------+-------+
| 1003 | abhi |
| 1004 | aniv |
+------+-------+
2 rows in set (0.11 sec)
Complex Views:
4.Writea Query view for each department retrieve the details like number of
students, major of the students.
A stored procedure contains a sequence of SQL commands stored in the database catalog so that
it can be invoked later by a program
• Stored procedures are declared using the following syntax:
Create Procedure <proc-name>
(param_spec1, param_spec2, …, param_specn )
begin
-- execution code
end;
where each param_spec is of the form:
[in | out | inout] <param_name> <param_type>
• in mode: allows you to pass values into the procedure,
• out mode: allows you to pass value back from procedure to the calling program
An example consider the Employee and Department tables which are shown below.
Suppose we want to keep track of the total salaries of employees working for each
department
Illustration Example:
Step 1: Change the delimiter (i.e., terminating character) of SQL statement from semicolon (;) to
something else (e.g., //) So that you can distinguish between the semicolon of the SQL
statements in the procedure and the terminating character of the procedure definition.
Example:
Step 2:
Example:
mysql> delimeter ;
Step 4: Call the procedure to update the totalsalary for each department
Example:
• Use show procedure status to display the list of stored procedures you have created
• The previous procedure updates one row in deptsal table based on input parameter
• Suppose we want to update all the rows in deptsal simultaneously
• First, let’s reset the totalsalary in deptsal to zero
An example illustration:
An Example:
Functions:
Example of Functions:
Triggers are nothing but the procedures/functions that involve actions and fired/executed
automatically whenever an event occurs such as an insert, delete, or update operation or pressing
a button or when mouse button is clicked.
Examples:
• Charge $10 overdraft fee if the balance of an account after a withdrawal
transaction is less than $500
• Limit the salary increase of an employee to no more than 5% raise
Syntax:
An example: We want to create a trigger to update the total salary of a department when a new
employee is hired
Problem Statemenet:
l Create a trigger to update the total salary of a department when a new employee is
hired:
2.Create a trigger to update the total salary of a department when an employee tuple is
modified:
3.Create a trigger to update the total salary of a department when an employee tuple is
deleted:
ER DIAGRAM
SCHEMA DIAGRAM
FLIGHTS TABLE
CREATE TABLE FLIGHTS (FNO INT PRIMARY KEY, F_FROM VARCHAR(10) NOT NULL,
F_TO VARCHAR(10) NOT NULL, DISTANCE INT, DEPARTS TIME,
ARRIVES TIME, PRICE FLOAT);
AIRCRAFT TABLE
CREATE TABLE AIRCRAFT (AID INT PRIMARY KEY, ANAME VARCHAR(10),
CRUISINGRANGE INT);
EMPLOYEES TABLE
CREATE TABLE EMPLOYEES (EID INT PRIMARY KEY, ENAME VARCHAR(15),
SALARY FLOAT);
CERTIFIED TABLE
CREATE TABLE CERTIFIED (EID INT, AID INT, PRIMARY KEY (EID, AID), FOREIGN KEY (EID)
REFERENCES EMPLOYEES (EID) ON DELETE CASCADE, FOREIGN KEY (AID) REFERENCES
AIRCRAFT (AID) ON DELETE CASCADE);
FLYS TABLE
CREATE TABLE FLYS(FNO INT, EID INT, PRIMARY KEY(FNO,EID), FOREIGN KEY (FNO)
REFERENCES FLIGHTS(FNO) ON DELETE CASCADE), FOREIGN KEY(EID) REFERENCES
EMPLOYEES(EID) ON DELETE CASCADE);
Write and Execute the SQL Queries for the following statements:
1. Display all the details of first four employees.
4. Display the total cost of travel from bengaluru to newdelhi via mumbai.
6. For each pilot who is certified for more than three aircrafts, find the eid and the
maximum cruisingrange of the aircraft for which she or he is certified.
7. Find the names of pilots whose salary is less than the price of the cheapest route from
Bengaluru to Frankfurt.
8. For all aircraft with cruisingrange over 1000 Kms. find the name of the aircraft and the
average salary of all pilots certified for this aircraft.
SCHEMA DIAGRAM:
ER DIAGRAM:
Write and Execute the SQL Queries for the following statements:
1. Make a list of all project numbers for projects that involve an employee whose last name
is ‘Ganesh’, either as a worker or as a manager of the department that controls the project.
2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10
percent raise.
3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as the
maximum salary, the minimum salary, and the average salary in this department
4. For each project on which more than ONE employee(s) work, retrieve the project
number, the project name, and the number of employees who work on the project.
5. For each project, retrieve the project number, the project name, and the number of
employees from department 3 who work on the project.
7. Display the count of Male and Female Employees working for Department 2.
11. Display SSN, Name and Age of Employees working on Project 501.
12. Display SSN, Name and Age of Employees NOT working on Project 501.
13. Display the Employee name and Address who work for ‘Research’ Department
(USING JOINS).
SELECT DISTINCT ENAME, ADDRESS FROM((EMPLOYEE E JOIN WORKS_FOR W ON
E.SSN=W.SSN) JOIN DEPARTMENT D ON W.DNO=D.DNO AND
D.DNAME='RESEARCH');
SELECT IF(1>3,'TRUE','FALSE');
14. Display SSN, Name and HE/SHE for all employees respectively.
15. Display SSN, Name and AGE as Major or Minor for all employees.
16. Create Views for FEMALE employees to check Age>22 and Salary>25000
17. Create Views for MALE employees to check Age>22 and Salary>25000
USE OF TRIGGERS
DELIMITER //
DELIMITER ;
Solution:
Entity-Relationship Diagram
Dir_id Dir_Name
Act_id Act_Name
Dir_Phone
Act_Gender Actor Director
M
Has
Movie_Cast
N
Role
Rev_Stars
N Movies
Movie ID Year
Movie_Title MovieLang
Schema Diagram
Actor
Act_id Act_Name Act_Gender
Director
Dir_id Dir_Name Dir_Phone
Movies
Mov_id Mov_Title Mov_Year Mov_Lang Dir_id
Movie_Cast
Act_id Mov_id Role
Rating
Mov_id Rev_Stars
Table Creation
Table Descriptions
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Queries:
2. Find the movie names where one or more actors acted in two or more movies.
+------------+
| MOV_TITLE |
+------------+
| BAHUBALI-1 |
+------------+
1 row in set (0.06 sec)
3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use
JOIN operation).
4. Find the title of movies and number of stars for each movie that has at least one
rating and find the highest number of stars that movie received. Sort the result by
movie title.
| MOV_TITLE | MAX(REV_STARS) |
+------------+----------------+
| AKASH |5 |
| BAHUBALI-1 | 2 |
| BAHUBALI-2 | 4 |
| WAR HORSE | 5 |
+------------+----------------+
4 rows in set (0.23 sec)
1. What is SQL?
Structured Query Language is a non procedural language or a data sub language.
2. What is database?
A database is a logically coherent collection of data with some inherent meaning,
representing some aspect of real world and which is designed, built and populated with data
for a specific purpose.
3. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other
words it is general-purpose software that provides the users with the processes of defining,
constructing and manipulating the database for various applications.
4. What is a Database system?
The database and DBMS software together is called as Database system.
5. Advantages of DBMS?
Redundancy is controlled.
Unauthorized access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
6. Disadvantage in File Processing System?
Data redundancy & inconsistency.
Data isolation.
Data integrity.
Security Problems.
View level:The highest level of abstraction describes only part of entire database.
7. Define the "integrity rules"
There are two Integrity rules.
Minimizing redundancy
Minimizing insertion, deletion and update anomalies.
35. What is Functional Dependency?
A Functional dependency is denoted by XY between sets of attributes X and Y
that are subsets of R specifies a constraint on the possible tuple that can form a relation state
r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have
t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the
value of component Y.
36. When is a functional dependency F said to be minimal?
Every dependency in F has a single attribute for its right hand side.
We cannot replace any dependency X A in F dependency Y A where Y is a proper
subset of X and still have a set of dependency that is equivalent to F.
We cannot remove any dependency from F and still have set of dependency that is
equivalent to F.
36. What is Multivalued dependency?
Multivalued dependency denoted by X Y specified on relation schema R, where
X and Y are both subsets of R, specifies the following constraint on any relation r of R: if
two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r
with the following properties
t3[x] = t4[X] = t1[X] = t2[X]
t3[Y] = t1[Y] and t4[Y] = t2[Y]
t3[Z] = t2[Z] and
t4[Z]=t1[Z]
where [Z = (R-(X U Y)) ]
38. What is Lossless join property?
It guarantees that the spurious tuple generation does not occur with respect to relation
schemas after decomposition.
39. What is 1 NF (Normal Form)?
The domain of attribute must include only atomic (simple, indivisible) values.
40. What is Fully Functional dependency?
It is based on concept of full functional dependency. A functional dependency X Y is
fully functional dependency if removal of any attribute A from X means that the dependency
does not hold any more.
41. What is 2NF?
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is
fully functionally dependent on primary key.
42. What is 3NF?
A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the
following is true
X is a Super-key of R.
A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
43. What is BCNF (Boyce-Codd Normal Form)?
A relation schema R is in BCNF if it is in 3NF and satisfies additional constraints that
for every FD X A, X must be a candidate key.
44. What is 4NF?
A relation schema R is said to be in 4NF if for every Multivalued dependency X Y
that holds over R, one of following is true
X is subset or equal to (or) XY = R.
X is a super key.
45. What is 5NF?
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ...,Rn} that
holds R, one the following is true
Ri = R for some i.
The join dependency is implied by the set of FD, over R in which the left side is key of R.
47. What are partial, alternate,, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same owner
entity. It is sometime called as Discriminator.
Alternate Key:All Candidate Keys excluding the Primary Key are known as Alternate Keys.
ArtificialKey:If no obvious key, either stand alone or compound is available, then the last
resort is to simply create a key, by assigning a unique number to each record or occurrence. Then
this is known as developing an artificial key.
CompoundKey: If no single data element uniquely identifies occurrences within a construct,
then
combining multiple elements to create a unique identifier for the construct is known as creating a
compound key.
NaturalKey: When one of the data elements stored within a construct is utilized as the primary
key, then it is called the natural key.
48. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be
found.
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing
49. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about
every relation and index that it contains. This information is stored in a collection of relations
maintained by the system called metadata. It is also called data dictionary.
50. What is meant by query optimization?
The phase that identifies an efficient execution plan for evaluating a query that has the
least estimated cost is referred to as query optimization.
51. What is join dependency and inclusion dependency?
JoinDependency:
JOIN: Concatenation of rows from one relation and related rows from another.
66. What is RDBMS KERNEL?
Two important pieces of RDBMS architecture are the kernel, which is the software, and
the data dictionary, which consists of the system-level data structures used by the kernel to
manage the database
You might think of an RDBMS as an operating system (or set of subsystems), designed
specifically for controlling data access; its primary functions are storing, retrieving, and securing
data. An RDBMS maintains its own list of authorized users and their associated privileges;
manages memory caches and paging; controls locking for concurrent resource usage; dispatches
and schedules user requests; and manages space usage within its table-space structures.