0% found this document useful (0 votes)
56 views16 pages

SQL Questions

The document discusses constraints and data types in SQL. It defines several constraint types like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, and CREATE INDEX and provides examples of each. It also discusses DDL commands for defining database schema and structure, and various data types for different data like strings, numbers, dates, and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
56 views16 pages

SQL Questions

The document discusses constraints and data types in SQL. It defines several constraint types like NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, and CREATE INDEX and provides examples of each. It also discusses DDL commands for defining database schema and structure, and various data types for different data like strings, numbers, dates, and more.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

10

Database Management Systems(4BCS503) Notes


1. Explain specifying constraints in SQL with the help of examples ---- 10 marks
SQL Constraints

In this tutorial, we'll learn about constraints in SQL with the help of examples.

In a database table, we can add rules to a column known as constraints. These rules control the
data that can be stored in a column.
For example, if a column has NOT NULL constraint, it means the column cannot
store NULL values.
The constraints used in SQL are:

Constraint Description

NOT NULL values cannot be null

UNIQUE values cannot match any older value

PRIMARY KEY used to uniquely identify a row

FOREIGN KEY references a row in another table

CHECK validates condition for new value

DEFAULT set default value if not passed

CREATE INDEX used to speedup the read process

NOT NULL Constraint

The NOT NULL constraint in a column means that the column cannot store NULL values. For
example,
CREATE TABLE Colleges (
college_id INT NOT NULL,
college_code VARCHAR(20) NOT NULL,
college_name VARCHAR(50)
);
Run Code

Here, the college_id and the college_code columns of the Colleges table won't
allow NULL values.
10
Database Management Systems(4BCS503) Notes

UNIQUE Constraint

The UNIQUE constraint in a column means that the column must have unique value. For
example,
CREATE TABLE Colleges (
college_id INT NOT NULL UNIQUE,
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);
Run Code

Here, the value of the college_code column must be unique. Similarly, the value
of college_id must be unique as well as it cannot store NULL values.

PRIMARY KEY Constraint

The PRIMARY KEY constraint is simply a combination of NOT


NULL and UNIQUE constraints. It means that the column value is used to uniquely identify the
row. For example,
CREATE TABLE Colleges (
college_id INT PRIMARY KEY,
college_code VARCHAR(20) NOT NULL,
college_name VARCHAR(50)
);
Run Code

Here, the value of the college_id column is a unique identifier for a row. Similarly, it cannot
store NULL value and must be UNIQUE.

FOREIGN KEY Constraint

The FOREIGN KEY (REFERENCES in some databases) constraint in a column is used to


reference a record that exists in another table. For example,
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
customer_id int REFERENCES Customers(id)
);
Run Code

Here, the value of the college_code column references the row in another table named Customers.
It means that the value of customer_id in the Orders table must be a value from the id column of
the Customers table.
10
Database Management Systems(4BCS503) Notes

CHECK Constraint

The CHECK constraint checks the condition before allowing values in a table. For example,
CREATE TABLE Orders (
order_id INT PRIMARY KEY,
amount int CHECK (amount >= 100)
);
Run Code

Here, the value of the amount column must be greater than or equal to 100. If not, the SQL
statement results in an error.

DEFAULT Constraint

The DEFAULT constraint is used to set the default value if we try to store NULL in a column.
For example,
CREATE TABLE College (
college_id INT PRIMARY KEY,
college_code VARCHAR(20),
college_country VARCHAR(20) DEFAULT 'US'
);
Run Code

Here, the default value of the college_country column is US.


If we try to store the NULL value in the college_country column, its value will be US.

CREATE INDEX Constraint

If a column has CREATE INDEX constraint, it's faster to retrieve data if we use that column for
data retrieval. For example,
-- create table
CREATE TABLE Colleges (
college_id INT PRIMARY KEY,
college_code VARCHAR(20) NOT NULL,
college_name VARCHAR(50)
);

-- create index
CREATE INDEX college_index
ON Colleges(college_code);
Run Code
10
Database Management Systems(4BCS503) Notes

Here, the SQL command creates an index named customers_index on the Customers table
using customer_id column.

2. Explain data definition and data types in SQL.------------ 10marks


DDL (Data Definition Language):
DDL or Data Definition Language actually consists of the SQL commands that can be used to
define the database schema. It simply deals with descriptions of the database schema and is used
to create and modify the structure of database objects in the database.DDL is a set of SQL
commands used to create, modify, and delete database structures but not data. These commands
are normally not used by a general user, who should be accessing the database via an
application.
List of DDL commands:
CREATE: This command is used to create the database or its objects (like table, index,
function, views, store procedure, and triggers).

CREATE TABLE employees (


id INTEGER PRIMARY KEY,
first_name VARCHAR(50) not null,
last_name VARCHAR(75) not null,
mid_name VARCHAR(50) not null,
dateofbirth DATE not null
);

DROP: This command is used to delete objects from the database.

DROP objecttype objectname.


DROP TABLE employees;

ALTER: This is used to alter the structure of the database.

ALTER objecttype objectname parameters


ALTER TABLE sink ADD bubbles INTEGER;
ALTER TABLE sink DROP COLUMN bubbles;

TRUNCATE: This is used to remove all records from a table, including all spaces allocated
for the records are removed.

TRUNCATE TABLE table_name;

COMMENT: This is used to add comments to the data dictionary.


-- Select all:
SELECT * FROM Customers;
RENAME: This is used to rename an object existing in the database.

ALTER TABLE old_table_name RENAME new_table_name;


10
Database Management Systems(4BCS503) Notes

SQL Data Types


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.

o String Data types


o Numeric Data types
o Date and time Data types
o String Data types
CHAR(Size) It is used to specify a fixed length string that can contain numbers,
letters, and special characters. Its size can be 0 to 255 characters.
Default is 1.

VARCHAR(Size) It is used to specify a variable length string that can contain numbers,
letters, and special characters. Its size can be from 0 to 65535
characters.

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.

VARBINARY(Size) It is equal to VARCHAR() but stores binary byte strings. Its size
parameter specifies the maximum column length in bytes.

TEXT(Size) It holds a string that can contain a maximum length of 255 characters.

TINYTEXT It holds a string with a maximum length of 255 characters.

MEDIUMTEXT It holds a string with a maximum length of 16,777,215.

LONGTEXT It holds a string with a maximum length of 4,294,967,295 characters.

ENUM(val1, val2, It is used when a string object having only one value, chosen from a
val3,...) 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.

SET( It is used to specify a string that can have 0 or more values, chosen
val1,val2,val3,....) from a list of possible values. You can list up to 64 values at one time
in a SET list.

BLOB(size) It is used for BLOBs (Binary Large Objects). It can hold up to 65,535
bytes.

o MySQL Numeric Data Types

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.
10
Database Management Systems(4BCS503) Notes

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.

INTEGER(size) It is equal to INT(size).

FLOAT(size, d) It is used to specify a floating point number. Its size parameter


specifies the total number of digits. The number of digits after the
decimal point is specified by d parameter.

FLOAT(p) It is used to specify a floating point number. MySQL used p parameter


to determine whether to use FLOAT or DOUBLE. If p is between 0
to24, the data type becomes FLOAT (). If p is from 25 to 53, the data
type becomes DOUBLE().

DOUBLE(size, It is a normal size floating point number. Its size parameter specifies
d) the total number of digits. The number of digits after the decimal is
specified by d parameter.

DECIMAL(size, It is used to specify a fixed point number. Its size parameter specifies
d) the total number of digits. The number of digits after the decimal
parameter is specified by d parameter. The maximum value for the
size is 65, and the default value is 10. The maximum value for d is 30,
and the default value is 0.

DEC(size, d) It is equal to DECIMAL(size, d).

BOOL It is used to specify Boolean values true and false. Zero is considered
as false, and nonzero values are considered as true.

o MySQL Date and Time Data Types

DATE It is used to specify date format YYYY-MM-DD. Its supported range


is from '1000-01-01' to '9999-12-31'.

DATETIME(fsp) It is used to specify date and time combination. Its format is YYYY-
MM-DD hh:mm:ss. Its supported range is from '1000-01-01
00:00:00' to 9999-12-31 23:59:59'.

TIMESTAMP(fsp) It is used to specify the timestamp. Its value is stored as the number
of seconds since the Unix epoch('1970-01-01 00:00:00' UTC). Its
format is YYYY-MM-DD hh:mm:ss. Its supported range is from
'1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC.

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'

YEAR It is used to specify a year in four-digit format. Values allowed in


four digit format from 1901 to 2155, and 0000.
10
Database Management Systems(4BCS503) Notes

3.Explain the specifications of constraints as assertions and triggers. --------- 10 marks

Two additional features of SQL: the CREATE ASSERTION statement and the CREATE
TRIGGER statement.

CREATE ASSERTION, which can be used to specify additional types of constraints that are
outside the scope of the built-in relational model constraints (primary and unique keys, entity
integrity, and referential integrity) that we presented early.

CREATE TRIGGER, which can be used to specify automatic actions that the database system
will perform when certain events and conditions occur. This type of functionality is generally
referred to as active databases.

Specifying General Constraints as Assertions in SQL

ASSERTIONS
In SQL, users can specify general constraints—those that do not fall into any of the categories
described via declarative assertions, using the CREATE ASSERTION statement of the DDL.
Each assertion is given a constraint name and is specified via a condition similar to the WHERE
clause of an SQL query.

The basic technique for writing such assertions is to specify a query that selects
any tuples that violate the desired condition. By including this query inside a NOT
EXISTS clause, the assertion will specify that the result of this query must be
empty so that the condition will always be TRUE. Thus, the assertion is violated if
the result of the query is not empty. In the preceding example, the query selects
all employees whose salaries are greater than the salary of the manager of their
department. If the result of the query is not empty, the assertion is violated.
Introduction to Triggers in SQL
Another important statement in SQL is CREATE TRIGGER. In many cases it is
10
Database Management Systems(4BCS503) Notes
convenient to specify the type of action to be taken when certain events occur and
when certain conditions are satisfied. For example, it may be useful to specify a
condition that, if violated, causes some user to be informed of the violation. The
CREATE TRIGGER statement is used to implement such actions in SQL.
A typical trigger has three components:
Event: When this event happens, the trigger is activated
Condition (optional): If the condition is true, the trigger executes, otherwise skipped
Action: The actions performed by the trigger
The action is to be executed automatically if the condition is satisfied when event occurs.

Trigger: Events

Three event types

Insert
Update
Delete
Two triggering times
Before the event
After the event
Two granularities
Execute for each row
Execute for each statement
10
Database Management Systems(4BCS503) Notes
10
Database Management Systems(4BCS503) Notes

Trigger: Action

Example 1

Example 2
10
Database Management Systems(4BCS503) Notes
4. Explain the schema change statements in SQL in detail with the help of
examples. ------ 10 marks
The commands available in SQL which can be used to alter a schema by adding or
dropping tables, attributes, constraints, and other schema elements. This can be done
while the database is operational and does not require recompilation of the database
schema. Certain checks must be done by the DBMS to ensure that the changes do not
affect the rest of the database and makeit inconsistent.

DROP TABLE COMMAND :


If a base relation within a schema is no longer needed,the relation and its definition can
be deleted by using the DROP TABLE command. For example, if we no longer wish to
keep track of dependents of employees in the COMPANY .we can get rid of the
DEPENDENT relationby issuing the following command:
DROP TABLE DEPENDENT CASCADE;
If the RESTRICT option is chosen instead of CASCADE, a table is dropped only if it is
not referenced in any constraints (for example, by foreign key definitions in another
relation) or views or by any other elements. With the CASCADE option, all such
constraints, views, and other elements that reference the table being dropped are also
dropped automatically from the schema, along with the table itself.
Notice that the DROP TABLE command not only deletes all the records in the table if
successful, but also removes the table definition from the catalog.
The ALTER Command
The definition of a base table or of other named schema elements can be changed by
using the ALTER command. For base tables, the possible alter table actions include
adding or dropping a column (attribute),changing a column definition,and adding or
dropping table constraints.
For example, to add an attribute for keeping track of jobs of employees to the
EMPLOYEEbase relation in the COMPANY schema , we can use the command.
ALTER TABLE COMPANY.EMPLOYEE ADD COLUMN Job VARCHAR(12);
We must still enter a value for the new attribute Job for each individual EMPLOYEE
tuple. This can be done either by specifying a default clause or by using the UPDATE
command individually on each tuple. .If no default clause is specified, the new attribute
will have NULLs in all the tuples of the relation immediately after the command is
executed; hence, the NOT NULL constraint is not allowed in this case.
The DROP Command
The DROP command can be used to drop named schema elements, such as tables,
domains, or constraints.
One can also drop a schema. For example, if a whole schema is no longer needed, the
DROP SCHEMA command can be used. There are two drop behavior options:
CASCADE and RESTRICT. For example, to remove the COMPANY database schema
and all its tables, domains, and other elements, the CASCADE option is used as follows:

DROP SCHEMA COMPANY CASCADE;


10
Database Management Systems(4BCS503) Notes
If the RESTRICT option is chosen in place of CASCADE, the schema is dropped only if it has no elements in
it; otherwise, the DROP command will not be executed. To use the RESTRICT option, the user must first
individually drop each element in the schema, then drop the schema itself

5. Explain additional features of SQL. ---- 10 marks


 Various techniques for specifying complex retrieval queries, including nested
queries, aggregate functions, grouping, joined tables, outer joins, and
recursive queries; SQL views, triggers, and assertions; and commands for
schema modification.

SQL has various techniques for writing programs in various programming


languages that include SQL statements to access one or more databases. These
include embedded (and dynamic) SQL, SQL/CLI (Call Level Interface) and its
predecessor ODBC (Open Data Base Connectivity), and SQL/PSM (Persistent
Stored Modules).

Each commercial RDBMS will have, in addition to the SQL commands, a set of
commands for specifying physical database design parameters, file structures for
relations, and access paths such as indexes. We called these commands a
storage definition language (SDL)

SQL has transaction control commands. These are used to specify units of
database processing for concurrency control and recovery purposes.

SQL has language constructs for specifying the granting and revoking of
10
Database Management Systems(4BCS503) Notes
privileges to users. Privileges typically correspond to the right to use certain SQL
commands to access certain relations. Each relation is assigned an owner, and
either the owner or the DBA staff can grant to selected users the privilege to use
an SQL statement—such as SELECT, INSERT, DELETE, or UPDATE—to
access the relation. In addition, the DBA staff can grant the privileges to create
schemas, tables, or views to certain users.

SQL has language constructs for creating triggers. These are generally referred
to as active database techniques, since they specify actions that are
automatically triggered by events such as database updates

SQL has incorporated many features from object-oriented models to have more
powerful capabilities, leading to enhanced relational systems known as object-
relational. Capabilities such as creating complex-structured attributes (also
called nested relations), specifying abstract data types (called UDTs or user-
defined types)for attributes and tables, creating object identifiers for referencing
tuples, and specifying operations on types.

 SQL and relational databases can interact with new technologies such as XML.

6. Explain views in SQL with the help of examples 10 marks


A view refers to a single table that is derived from other tables

CREATE VIEW WORKS_ON1


AS SELECT FNAME, LNAME, PNAME, HOURS
FROM EMPLOYEE, PROJECT, WORKS_ON
WHERE SSN=ESSN ANDPNO=PNUMBER

More on View

CREATE VIEW
DEPT_INFO(DEPT_NAME,NO_OF_EMPLS,TOTAL_SAL) AS SELECT
DNAME, COUNT(*), SUM(SALARY)
FROM DEPARTMENT, EMPLOYEE
WHERE DNUMBER=DNO GROUP BY DNAME

More on view

Treat WORKS_ON1 like a base

table asfollows SELECT FNAME,

LNAME FROM WORKS_ON1

WHERE PNMAE=‘PROJECTX‘

Main advantage of view:


Simplify the specification of commonly

usedqueries More on View


10
Database Management Systems(4BCS503) Notes
A View is always up to date;

A view is realized at the time we specify(or execute) a query

onthe view DROP VIEW WORKS_ON1

Updating of Views

Updating the views can be complicated and ambiguous

In general, an update on a view on defined on a single table w/o any aggregate


functionscan be mapped to an update on the base table

More on Views

We can make the following observations:

A view with a single defining table is updatable if we view contain PK or CK of the

basetable View on multiple tables using joins are not updatable

View defined using grouping/aggregate are not

updatable Specifying General Constraints

Users can specify certain constraints such as semantics

constraints CREATE ASSERTION

SALARY_CONSTRAINT

CHECK ( NOT EXISTS ( SELECT * FROM EMPLOYEE E,


EMPLOYEE M, DEPARTMENT D

WHERE E.SALARY > M. SALARY AND E.DNO=D.NUMBER AND


D.MGRSSN=M.SSN))

7.Explain insert, delete and update operation with the help of examples. .---10 marks
The Insert Command

INSERT INTO EMPLOYEE


11
Database Management Systems(4BCS503) Notes 5

VALUES (‘Richard‘,‘K‘,‘Marini‘,653298653‘,‘30dec52‘,’98 Oak Forest, Ky,


TX‘,‘M‘,37000,‘987654321‘,4)

More on Insert

Use explicit attribute names:


INSERT INTOEMPLOYEE(FNAME,LNAME,SSN)VALUES (‘Richard‘,‘Marini‘,
‘653298653‘));
The DELETE Command

DELETE FROM EMPLOYEE

WHERE LNAME=’Brown‘

The UPDATE Command

Used to modify values of one or more selected tuples

Change the location and controlling department number of project number 10 to


‘Bellaire‘and 5 respectively

UPDATE PROJECT

SET PLOCATION = ‘Bellaire‘,

DNUM=5 Where PNUMBER=10;

8. Explain the concepts of 3 Tier architecture in DBMS. 10 marks

Tier-3 Architecture
The 3-tier architecture contains one more layer between the client and the server.
 In this architecture, there is no direct communication between client and server.
 Mainly, the 3-tier is used for large applications on the web.
 The features of 3-tier architecture are data backup, recovery, security, and
concurrency control.
Layers
The 3-tier architecture consists of the three layers as follows −
 Presentation layer − This layer is also called the client layer. The front-end layer
consists of a user interface. The main purpose is to communicate with the
application layer.
 Application layer − This layer is also called the business logic layer. It acts as a
middle layer between the client and the database server which are used to
exchange partially processed data.
 Database layer − In this layer the data or information is stored. This layer performs
operations like insert, update and delete to connect with the database.
11
Database Management Systems(4BCS503) Notes 6

The Tier-3 Architecture is diagrammatically represented below −

Purpose of three-tier architecture

 Integrity: because of the middle layer between the client and server-side data corruption
can be removed
 Security: as there is no direct interaction between client and server we can restrict
unauthorized access if any
 To provide a clear separation between the user application and physical database
 Program data independence and multiple views of data
 Because of the above features, a large number of users can access a database easily

Demerits

 There might be complexity in implementation and communication


 Sometimes it becomes difficult for interaction due to the presence of middle layers
and responses may be delayed but they can be easily overcome by efficient server
administration.

*********************************************************************

You might also like