Professional Documents
Culture Documents
SQL
Q1) With respect to SQL explain the following with an example.
a) CREATE TABLE b) ALTER TABLE c) DROP d) CREATE SCHEMA
e) CREATE DOMAIN command
a) CREATE TABLE Command
CREATETABLE: The CREATE TABLE command is used to create a new relation by giving it
a name and specifying attributes and constraints. The general syntax is.
Here the <attribute name> is column name to be removed from the relation (table).
If CASCADE option is used, then all constraints and views that reference the column are dropped
automatically from the database, along with the column.
If RESTRICT option is used, then specified attribute (column) is dropped only if no views or
constraints references the column.
We can drop an existing default clause by using the ALTER and DROP DEFAULT clause with
ALTER TABLE command, the general syntax is
Here the<attribute name>is the name of the column to which the specified new value is to be stored.
Example: ALTER TABLE EMPLOYEE ALTER JOB SET DEFAULT ’DAILYWAGE‘;
Dropping constraint:
The constraint which has given a name can be dropped by using DROP CONSTRAINT clause.
Database Management Systems /21CS53, ISE, DBIT 2
General syntax is
c) DROP Command
This command is used to delete the table, if it is no longer needed. The general syntax is
DROP TABLE <table name>[RESTRICT or CASCADE]
Here if the RESTRICT option is chosen the table is dropped only if it is not referenced in any
constraints (such as by foreign key definitions in another relation).
With CASCADE option, all such constraints and views that reference the table are dropped
automatically, along with the table itself.
Note: Schema Evolution (or Schema change) commands in SQL: Drop, Alter Command. These
commands are used to alter a schema by adding or dropping tables, attributes, constraints and
other schema elements.
The concept of an SQL schema is incorporated in SQL2 in order to group together tables and
other constructs that belong to the same database application. An SQL schema is identified by a
schema name, and includes an authorization identifier to indicate the user or account who owns
the schema, as well as descriptors for each element in the schema. Schema elements include
tables, constraints, views, domains, and other constructs (such as authorization grants) that
describe the schema. A schema is created via the CREATE SCHEMA statement, which can
include all the schema elements‘ definitions. Alternatively, the schema can be assigned a name
and authorization identifier, and the elements can be defined later.
For example, the following statement creates a schema called COMPANY, owned by the user
with authorization identifier ‘Jsmith ‘. Note that each statement in SQL ends with a semicolon.
CREATE SCHEMA COMPANY AUTHORIZATION ‘Jsmith ‘;
The SQL schema in which the relations are declared is implicitly specified in the environment in
We can use SSN_TYPE in place of CHAR(9) as used in the above example, for the attributes Ssn
and Super_ssn of EMPLOYEE, Mgr_ssn of DEPARTMENT, Essn of WORKS_ON, and Essn of
DEPENDENT. A domain can also have an optional default specification via a DEFAULT clause.
Numeric: Numeric data types include integer numbers of various sizes (INTEGER or INT, and
SMALLINT) and floating-point (real) numbers of various precision (FLOAT or REAL, and
DOUBLE PRECISION). Formatted numbers can be declared by using DECIMAL(i, j)—or
DEC(i, j) or NUMERIC(i, j)—where i, the precision, is the total number of decimal digits and j,
the scale, is the number of digits after the decimal point. The default for scale is zero, and the
default for precision is implementation-defined.
Bit-string: Bit-string data types are either of fixed length n-BIT(n) or varying length-BIT
VARYING(n), where n is the maximum number of bits. The default for n, the length of a
character string or bit string, is 1. Literal bit strings are placed between single quotes but preceded
by a B to distinguish them from character strings.
Another variable-length bit string data type called BINARY LARGE OBJECT or BLOB is also
available to specify columns that have large binary values, such as images. The maximum length
of a BLOB can be specified in kilobits (K), megabits (M), or gigabits (G).
Boolean: A Boolean data type has the traditional values of TRUE or FALSE. In SQL, because of
the presence of NULL values, a three-valued logic is used, so a third possible value for a Boolean
data type is UNKNOWN.
DATE and TIME: The DATE data type has ten positions, and its components are YEAR,
MONTH, and DAY in the form YYYY-MM-DD. The TIME data type has at least eight
positions, with the components HOUR, MINUTE, and SECOND in the form HH:MM:SS.
Literal values are represented by single-quoted strings preceded by the keyword DATE or TIME;
for example, DATE ‘2008-09-27‘or TIME ‘09:12:47‘.
INTERVAL: Another data type related to DATE, TIME, and TIMESTAMP is the INTERVAL
data type. This specifies an interval—a relative value that can be used to increment or decrement
an absolute value of a date, time, or timestamp. Intervals are qualified to be either
YEAR/MONTH intervals or DAY/TIME intervals.
Q3) Explain the different constraints and default clause in SQL.
Constraints: After the attributes specifications the following constraints can be specified on a
table: Not null, Primary key, Foreign Key, Unique.
NOT NULL: As the SQL allows NULL as attribute value, NOT NULL constraint may be
specified if NULL is not permitted for a particular attribute. The NOT NULL constraint should
always be specified for the primary key attributes of each relation and for any other attributes
whose values are not to be NULL.
Another type of constraint can restrict attribute or domain values using the CHECK clause
following an attribute or domain definition.
For example, suppose that department numbers are restricted to integer numbers between 1
and20; then, we can change the attribute declaration of Dnumber in the DEPARTMENT table to
the following:
Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber<21);
The CHECK clause can also be used in conjunction with the CREATE DOMAIN statement.
For example, we can write the following statement:
CREATE DOMAIN D_NUM AS INTEGER
CHECK (D_NUM > 0 AND D_NUM<21);
In addition to key and referential integrity constraints, which are specified by special key words,
other table constraints can be specified through additional CHECK clauses at the end of
aCREATE TABLE statement. These can be called tuple-based constraints because they apply to
each tuple individually and are checked whenever a tuple is inserted or modified.
For example, suppose that the DEPARTMENT table had an additional attribute
Dept_create_date, which stores the date when the department was created. Then we could add the
following CHECK clause at the end of the CREATE TABLE statement for the DEPARTMENT
table to make sure that a manager‘s start date is later than the department creation date.
CHECK(Dept_create_date<=Mgr_start_date);
Default clause: It is also possible to define a default value for an attribute by appending the
clause DEFAULT <value> to an attribute definition. DEFAULT clause includes the specified
value in any new tuple if an explicit value is not provided for that attribute. For example:
CREATE TABLE DEPARTMENT(DNAME VARCHAR(15) NOT NULL, DNUMBER INT
NOT NULL, DLOCATION VARCHAR(15) NOT NULL DEFAULT ‘MYSURU’);
Here dname, dumber, dlocation cannot take null values and default value for dlocation is
MYSURU.
PRIMARY KEY: This clause specifies one or more attributes that make up the primary key of a
relation.
CONSTRAINT: This keyword is used to give a name to a constraint. The names of all
constraints within a particular schema must be unique. A constraint name is used to identify a
particular constraint in case the constraint must be dropped and replaced with another constraint.
Example
CREATE TABLE EMPLOYEE ( ,DNO INT NOT NULL DEFAULT1, CONSTRAINT EMPK
PRIMARY KEY(SSN), CONSTRAINT EMPFK FOREIGNKEY(DNO) REFERENCES
DEPARTMENT(DNUMBER)ON DELETE SET NULL);
Database Management Systems /21CS53, ISE, DBIT 7
Q4) Explain Update statements in SQL.ORExplain Insert, Delete and Update statement in
SQL.
In SQL three commands can be used to modify the database, they are INSERT, DELETE, and
UPDATE.
INSERT Command:
The insert command can be used to add data in to table. INSERT command can be used in
different forms as shown below.
The simplest form is:
INSERT INTO <table name> VALUES (val1,val2,val3,…,valn).
This form can be used to add a single tuple (row) to a relation. Here the values should be listed in
the same order in which the corresponding attributes were specified in the CREATE TABLE
command. For example:
INSERTINTOEMPLOYEE VALUES (‘Mohan‘, ’12345‘ , ’1stmain‘,5000,’Physics‘,‘Lecturer‘);
The second form is:
INSERT INTO <table name>(attr1, attr2,..., attrn) VALUES (val1,val2,val3,...valn);
This form allows the user to specify explicit attribute names that correspond to the values in the
INSERT command. In this case, attributes with NULL or DEFAULT values are left out. For
example:
INSERT INTO EMPLOYEE (FNAME, EMPNO) VALUES (‘Mohan‘,’123‘);
The third form is:
INSERT INTO <table name> [(attr1,attr2,......attrn)]SELECT <attributes> FROM <tables>
WHERE<condition>;
This form of INSERT command inserts multiple tuples into the relation based on result of the
query.
For example:
INSERT INTO DEPOSIT SELECT BRANCH_NAME, LOAN_NUMBER, CUST_NAME
FROM BORROW WHERE BRANCH_NAME= ‘Bengaluru‘;
The DELETE Command:
The DELETE command removes tuples (rows) from a table. This command includes WHERE
clause to select the tuples to be deleted. Depending on the number of tuples selected by the
condition in the WHERE clause 0, 1, 2, or several tuples can be deleted by single DELETE
command. If there is no WHERE clause in the DELETE commands, then all tuples (rows) in the
table are deleted. The general syntax is:
Database Management Systems /21CS53, ISE, DBIT 8
DELETE FROM<table name>WHERE<condition>;
For example: DELETE FROM EMPLOYEE WHERE SALARY=2000;
The above command updates the salary of all Research department employees by 10%.
Note: Updating the primary Key values may propagate to the foreign Key values of tuples in
other relation.
Q5) Give the complete syntax of SELECT statement in SQL and discuss all the clauses with
examples.
The basic structure of an SQL expression consists of six clauses: SELECT, FROM, WHERE,
GROUP BY, HAVING, and ORDER BY has the following syntax.
SELECT<attribute and function
list>FROM < table list>
[WHERE <condition>]
[GROUP BY <grouping attribute(s)>]
[HAVING <group condition>]
[ORDER BY<attribute list>] [ASC|DESC];
SELECT: This clause corresponds to the projection operation of the relational algebra. It is used
to list the attributes desired in the result of a query.
FROM: This clause corresponds to the Cartesian product operation of the relational algebra. It
lists the relations to be scanned in the evaluation of the expression.
WHERE: This clause corresponds to the selection predicate (condition) of the relational algebra.
It consists of conditions involving attributes of the relations that appears in the from clause.
Database Management Systems /21CS53, ISE, DBIT 9
<attributelist>: It is the list of attribute names that are to be retrieved by the query.
<tablelist>: It is the list of relation names required to process the query.
<condition>: is a conditional search expression that identifies the tuples to be retrieved by
thequery.
Example: Retrieve the name and address of all employees who work for Research
department.
SELECTE NAME, ADDRESS FROM EMPLOYEE, DEPARTMENT
WHERE DNAME=’Research’ AND DNUMBER=DNO;
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups.
For eg: Retrieve the total no of employees and total salary of employees in each department,
then GROUP BY query would be as follows:
SELECT DNO, COUNT(*) as No_of_Emp, SUM(SALARY)
FROM EMPLOYEE GROUP BY DNO;
The HAVING clause provides a condition on the group of tuples associated with each value of
the grouping attributes. Only the groups that satisfy the condition are retrieved in the result of the
query. For eg: For each department in which more than 2 employees work, retrieve the total
num of employees and total salary of employees.
SELECT DNO, COUNT(*) as No_of_Emp, SUM(SALARY) FROM
EMPLOYEE GROUP BY DNO HAVING COUNT(*)>2;
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on
one or more columns.
For eg: Retrieve the SSN and Name of employees arranged alphabetically by their name.
SELECT Ssn, Fname SELECT Ssn, Fname
FROM EMPLOYEE OR FROM EMPLOYEE
ORDER BY Fname; ORDER BY Fname ASC;
For example: Retrieve the SSN and Name of employees arranged in descending order by name.
SELECT Ssn, Fname
FROM EMPLOYEE
ORDER BY Fname DESC;
Database Management Systems /21CS53, ISE, DBIT 10
Note: Some database sorts query results in ascending order by default. We can use more than one
column in the ORDER BY clause. Make sure whatever column you are using to sort, that column
should be in column-list.
Q6) Conceptually how SQL retrieval query will be executed? Explain.
A query is evaluated conceptually by first applying the FROM clause (to identify all tables
involved in the query or to materialize any joined tables), followed by the WHERE clause to
select and join tuples, and then by GROUP BY and HAVING. Conceptually, ORDER BY is
applied at the end to sort the query result. At last, SELECT clause displays the attributes
specified.
Q7) Explain how SQL deals with Ambiguous Attributes names and how Aliasing can be
done.
In SQL the same name can be used for two or more attributes as long as the attributes are in
different relations. If this is the case, and a query refers to two are more attributes with same
name, we must qualify the attribute name with the relation name to prevent ambiguity. This is
done by prefixing the relation name to the attribute name and separating the two by a
period (.).
For example, suppose if both the relations EMPLOYEE and DEPARTMENT have the attributes
with names NAME and DNUMBER the following query can prevent the ambiguity.
SELECT EMPLOYEE.NAME, AGE, ADDRESS FROM EMPLOYEE,
DEPARTMENT WHERE DEPARTMENT.NAME=‘Research’ AND
DEPARTMENT.DNUMBER=EMPLOYEE.DNUMBER;
Using Aliases: The ambiguity also arises in case of the queries that refer to the same relation
twice. In this case the user is allowed to declare the alternative relation names called aliases. An
alias can directly follow the relation name. For example:
Retrieve name, age, and department number of all the employees whose employee number and
department number are same.
SELECT E.NAME, E.AGE, S.DNO FROM EMPLOYEE E,
EMPLOYEE S WHERE E.EMPNO = S.DNO;
Here relation names E and S are called aliases.
We use this alias naming mechanism in any SQL query, whether or not the same relation needs to
be referenced more than once.
Q8) Explain the consequence of not using WHERE clause and use of *.
A missing WHERE clause in a query indicates no condition on tuple selection, hence all tuples of
relation specified in the FROM clause qualify and are selected for query result.
For example: Retrieve ssn of all employees.
SELECT SSN FROM EMPLOYE E;
If more than one relation is specified in the FROM clause and there is no WHERE clause then all
possible tuple combination (CROSS PRODUCT) of the specified relations is selected (with no
proper join condition, in correct and large result may result.
Q9) Explain why SQL does not automatically eliminate duplicate tuples in query results.
SQL does not treat table as a set. SQL does not automatically eliminate duplicate tuples in the
results of queries, for the following reasons.
. Duplicate elimination is an expensive operation. One way to implement it is to sort the tuples
first and then eliminate duplicates.
. The user may want to see duplicate tuples in the result of query.
. When aggregate function is applied to tuples, in most cases the user do not want to eliminate
duplicates.
Q10) Explain the use of DISTINCT Keyword in SQL.
The key word DISTINCT can be used in SELECT clause to eliminate duplicate tuples from
theresult of the query i.e., only the distinct tuples remain in the result.
For example: Retrieve the distinct salary values of employees.
SQL includes the operations union, intersect, and minus, which operates on the relations and
corresponds to the relational algebra operation respectively.
Use of UNION Keyword: UNION keyword is used to perform, relational algebra operation,
union ( ). UNION operation bydefault eliminates duplicate tuples, to retain duplicates we must
use UNION ALL in the place of UNION.
Example: Find the customers having loan, or an account, or both at Mysuru branch.
(SELECT CUST_NAME FROM DEPOSIT
WHERE BRANCH_NAME = ‘Mysuru’)
UNION
(SELECT CUST_NAME FROM BORROW
WHERE BRANCH_NAME = ‘Mysuru’);
Use of INTERSECT Keyword: INTERSECT keyword is used to perform, relational algebra
operation, intersect ( ). INTERSECT operation by default eliminates duplicate tuples.
Example: Find the customers having both loan, and an account, at Mysuru branch.
(SELECT CUST_NAME FROM DEPOSIT
WHERE BRANCH_NAME = ‘Mysuru’)
INTERSECT
(SELECT CUST_NAME FROM BORROW
WHERE BRANCH_NAME = ‘Mysuru’);
Use of MINUS Keyword: MINUS keyword is used to perform, relational algebra operation,
minus ( ). MINUS operation by default eliminates duplicate tuples.
Example: Find the customers of Mysuru branch who have an account there but no loan there.
(SELECT CUST_NAME FROM DEPOSIT
WHERE BRANCH_NAME=‘Mysuru’)
MINUS
(SELECT CUST_NAME FROM BORROW
WHERE BRANCH_NAME = ‘Mysuru’);
Note: All these set operations by default, eliminates duplicate tuples from the result. As because
Database Management Systems /21CS53, ISE, DBIT 13
the set operations apply only to the union compatible relations, user should make sure that the two
relations have the same attributes and that the attributes appear in the same order in both relations.
Set Comparison Operators: The set comparison operators are IN, SOME, ALL, ANY,
CONTAINS and NOT CONTAINS. With the key words ANY, SOME and ALL, other operators
like >, <, =, >=, <= and<> can be combined. The key words ANY and SOME have the same
meaning.
Use IN key word: IN is a comparison operator that compares the single value ‘v’ with a set (or
multiset) of values ‘V’ and evaluates to TRUE if ‘v’ is one of the elements in V. The IN operator
can also compare tuple of values in parentheses with a set. IN keyword is equivalent to =ANY
and =SOME.
For example: Find the customers who are having account in the branch where the “Kumar”
has an account.
Select cust_name
From deposit
Where branch_name in(select branch_name
From deposit
Where cust_name=‘Kumar’);
Use of SOME (ANY) keyword: SOME is a comparison operator that compares the single value
‘v’ with a set (or multiset) of values ‘V’. With this keyword the operators like >, <, =, >=, <= and
<> can be combined.
For example: v>SOME V returns TRUE if value ‘v’ is greater than at least one member of the
value set ‘V’.
Use of ALL keyword: ALL is a comparison operator that compares the single value ‘v’ with a
set (or multi set) of values ‘V’. With this keyword the operators like >, <, =, >=, <= and<> can be
combined.
For example: Find the names of employees whose salary is greater than the salary of all the
employees in department 5.
Select Fname
From employee
Where salary >ALL(select salary
From employee
Where Dno= 5);
Use of CONTAINS Key word: CONTAINS construct can be used to compare two sets of values
and returns TRUEif one set contains all the members of some other set. For Example: Find the
employee who works on all the projects controlled by department number 5.
Select Fname From employee Where((select Pno
From works_on
Where ssn=essn)
CONTAINS
(Select Pnumber
From project
Where Dnum=5));
Q13) Explain correlated nested query.
Whenever a condition in the WHERE clause of a nested query references some attribute in the
outer query, the two queries are said to be correlated. The nested queryis evaluated once for each
tuple in the outer query.
Example: Retrieve the name of employees who has a dependent with the same name as the
employee.
Select Fname From Employeee
Where ssn in(selecte ssn
From dependent d
Where e.fname=d.name);
NOT EXISTS returns TRUE if there are no tuples in the result of the nested query and FALSE
otherwise.
Example: Retrieve the name of employees who have no dependents.
Select Fname
From Employee e
Where NOT EXISTS(select*
From Dependent d
Where e.ssn=d.essn);
UNIQUE function returns TRUE if there are no duplicates in the result of the query and FALSE
otherwise.
Q15) What are aggregate functions in SQL? Explain with examples.
Aggregate functions are applied to set of tuples and return a single value. Some of the built in
functions are: COUNT, SUM, MAX, MIN, AVG.
The COUNT function returns the number of tuples or values as specified in the query. The
functions SUM, MAX, MIN, AVG are applied to a set or multiset of numeric values and return
the sum, maximum, minimum, average of those values respectively.
These functions can be used in the SELECT or HAVING clause.
For example: For each department in which more than2 employees work, retrieve the total
num of employees and total salary of employees.
SELECT DNO, COUNT(*) as No_of_Emp, SUM(SALARY)
FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT(*)>2;
Q17) What are views in SQL? Explain how views are created and dropped. List the
advantages of views?
A view in SQL terminology is a single table that is derived from other tables. A view does not
necessarily exist in physical form, it is considered to be a virtual table.
We can think of a view as a wayof specifying a table that we need to referencefrequently,
even though it may not exist physically.
Creation (or Specification) of Views in SQL
In SQL, the command to specify a view is CREATE VIEW. The view is given a(virtual)table
name (or view name), a list of attribute names, and a query to specify the contents of the view.
CREATE VIEW <view name> [<col1 name>,<col2 name>,…,<coln name>] as <select>;