SQL Questions
SQL Questions
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
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.
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.
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
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.
TRUNCATE: This is used to remove all records from a table, including all spaces allocated
for the records are removed.
Data types mainly classified into three categories for every database.
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.
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.
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.
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.
BOOL It is used to specify Boolean values true and false. Zero is considered
as false, and nonzero values are considered as true.
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'
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.
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
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.
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.
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
WHERE PNMAE=‘PROJECTX‘
Updating of Views
More on Views
SALARY_CONSTRAINT
7.Explain insert, delete and update operation with the help of examples. .---10 marks
The Insert Command
More on Insert
WHERE LNAME=’Brown‘
UPDATE PROJECT
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
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
*********************************************************************