DBMS Unit 2
DBMS Unit 2
SQL BASICS
3.1 Introduction:
SQL stands for Structured Query Language. SQL is the language used to create, edit
and manipulate a database. In other words, SQL is used to manage data held within
The topics covered in this blog are mainly divided into 4 categories:
There are two ways in which you can comment in SQL, i.e. either the Single
Single-Line Comments
The single line comment starts with two hyphens (–). So, any text mentioned after
(–), till the end of a single line will be ignored by the compiler.
Example:
--Select all:
Multi-Line Comments
The Multi-line comments start with /* and end with */. So, any text mentioned
Example:
records
Data definition language is one of the subcategories of SQL. It is used to define and
work with the database schema (structure). This includes the attributes (columns)
within each table, the name of each table, the name of the database, and the
connection of keys between tables. Here are general explanations of the types of
commands in DDL:
▪
CREATE – used to create the database, the tables, and the columns within each
table. Within the create statement we also define the data type of each column.
A data type is literally the type of data we are supposed to store within each
column, whether it be an
▪ CREATE
▪ DROP
▪ TRUNCATE
▪ ALTER
▪ BACKUP DATABASE
CREATE
Syntax
Example
table.
Syntax
( Column1 datatype,
Column2
datatype,
Column3
datatype,
....
ColumnN datatype
);
Example
EmployeeIDint,
EmployeeNamevarchar(255),
Emergency
ContactNamevarchar(255),
PhoneNumberint,
Address
varchar(255), City
varchar(255),
Country
varchar(255)
);
You can also create a table using another table. Refer the below syntax and example:
Syntax
FROM ExistingTableName
WHERE ;
Example
CREATE TABLE ExampleTable AS
DROP
This statement is used to drop an existing database. When you use this statement,
Syntax
Example
This statement is used to drop an existing table. When you use this statement, complete
Syntax
Example
TRUNCATE
This command is used to delete the information present in the table but does not
delete the table. So, once you use this command, your information will be lost, but
Syntax
Example
ALTER
This command is used to delete, modify or add constraints or columns in an existing table.
The ‘ALTER TABLE’ Statement
You can use the ALTER TABLE statement with ADD/DROP Column command
according to your need. If you wish to add a column, then you will use the ADD
command, and if you wish to delete a column, then you will use the DROP COLUMN
command.
Syntax
Example
ADD BloodGroupvarchar(255);
Syntax
BACKUP DATABASE
Syntax
BACKUP DATABASE
Example
TO DISK = 'C:UsersSahitiDesktop';
You can also use a differential back up. This type of back up only backs up the
parts of the database, which have changed since the last complete backup of the
database.
Syntax
BACKUP DATABASE
WITH DIFFERENTIAL;
Example
TO DISK = 'C:UsersSahitiDesktop'
WITH DIFFERENTIAL;
Now that you know the data definition commands, let me take you through the
various types of Keys and Constraints that you need to understand before learning
Data manipulation language is used to work with the actual data within the database.
if we looked at an example with a users table, the table is created with DDL while the
▪ SELECT – this is used to select data from our database. We first say SELECT and
then we say what columns to select. After we say what columns, we specify what
tables using FROM. After we select what columns and what tables we can limit
our results using a WHERE clause. Example: SELECT user_id FROM users
The SQL data manipulation language (DML) is used to query and modify
database data. In this chapter, we will describe how to use the SELECT, INSERT,
● The beginning of each clause should line up with the beginning of other clauses.
● If a clause has several parts, they should appear on separate lines and be
SELECT Statement
The SELECT statement, or command, allows the user to extract data from tables,
FROM table(s)
WHERE predicate
GROUP BY field(s)
ORDER BY fields
ORDER BY LastName
This action will display employee’s last name, first name, and phone number
that Canada is mispelled in the Publisher Country field for Example Publishing
standardize the country field to Canada – see UPDATE statement later in this
chapter.)
Publisher Publisher
Publisher Name Publisher
City Province Country
Example
Edmonton AB Cnada
Publishing
If you add the publisher’s name and city, you would use the SELECT statement
FROM Publishers
This action will display the publisher’s name and city from the Publishers table.
If you just want the publisher’s name under the display name city, you would use
FROM Publishers
Performing this action will display only the pub_name from the Publishers table
with a “city” heading. If you do not include the comma, SQL Server assumes you
Sometimes you might want to focus on a portion of the Publishers table, such as
only publishers that are in Vancouver. In this situation, you would use the SELECT
These first two examples illustrate how to limit record selection with the WHERE
criterion using BETWEEN. Each of these examples give the same results for store
FROM Sales
FROM Sales
Example #3 illustrates how to limit record selection with the WHERE criterion
FROM Sales
The next two examples show two different ways to limit record selection
with the WHERE criterion using IN, with each yielding the same results.
WHERE statement.
SELECT *
FROM Publishers
SELECT *
FROM Publishers
The final two examples illustrate how NULL and NOT NULL can be used to select
records. For these examples, a Books table (not shown) would be used that
contains fields called Title, Quantity, and Price (of book). Each publisher has a
FROM Books
FROM Books
The LIKE keyword selects rows containing fields that match specified portions of
character strings. LIKE is used with char, varchar, text, datetime and
smalldatetime data. A wildcard allows the user to match fields that contain
certain letters. For example, the wildcard province = ‘N%’ would give all
express format.
In example #1, LIKE ‘Mc%’ searches for all last names that begin with the letters
SELECT
LastName FROM
Employees
For example #2: LIKE ‘%inger’ searches for all last names that end with the
SELECT
LastName FROM
Employees
In, example #3: LIKE ‘%en%’ searches for all last names that have the letters “en”
LastName FROM
Employees
You use the ORDER BY clause to sort the records in the resulting list. Use ASC
to sort the results in ascending order and DESC to sort the results in descending
order.
SELECT *
FROM Employees
SELECT *
FROM Books
The GROUP BY clause is used to create one output row per each group and
SELECT type
FROM Books
GROUP BY type
FROM Books
WHERE royalty > 10
GROUP BY type
If the SELECT statement includes a WHERE criterion where price is not null,
FROM Books
then a statement with the GROUP BY clause would look like this:
FROM Books
GROUP BY type
We can use COUNT to tally how many items are in a container. However, if we
want to count different items into separate groups, such as marbles of varying
colours, then we would use the COUNT function with the GROUP BY command.
The below SELECT statement illustrates how to count groups of data using the
SELECT COUNT(*)
FROM Books
GROUP BY type
We can use the AVG function to give us the average of any group, and SUM to
FROM Books
GROUP BY type
SELECT SUM(qty)
FROM Books
GROUP BY type
Example #3 uses both the AVG and SUM functions with the GROUP BY type
FROM Sales
The HAVING clause can be used to restrict rows. It is similar to the WHERE
condition except HAVING can include the aggregate function; the WHERE cannot
do this.
The HAVING clause behaves like the WHERE clause, but is applicable to groups.
In this example, we use the HAVING clause to exclude the groups with the
province ‘BC’.
FROM Authors
INSERT statement
● INSERT specifies the table or view that data will be inserted into.
● VALUES specifies the data that you want to insert into the table.
VALUES is required.
When inserting rows with the INSERT statement, these rules apply:
● Inserting an empty string (‘ ‘) into a varchar or text column inserts a single space.
● All trailing spaces are removed from data inserted into varchar columns,
except in strings that contain only spaces. These strings are truncated to a
single space.
wrong data type, the statement fails and SQL Server displays an error
message.
When you specify values for only some of the columns in the column_list, one
2. NULL is entered if the column allows NULLs and no default value exists
3. An error message is displayed and the row is rejected if the column is defined
This example uses INSERT to add a record to the publisher’s Authors table.
INSERT INTO Authors
This following example illustrates how to insert a partial row into the Publishers
table with a column list. The country column had a default value of Canada so it
To insert rows into a table with an IDENTITY column, follow the below example.
Do not supply the value for the IDENTITY nor the name of the column in the
column list.
a row is accidentally deleted, or there are gaps in the IDENTITY column values,
you can insert a row and specify the IDENTITY column value.
IDENTITY_INSERT option
To allow an insert with a specific identity value, the IDENTITY_INSERT option can
be used as follows.
can insert rows with a SELECT statement. When using this command, there is no
validation for uniqueness. Consequently, there may be many rows with the same
This example creates a smaller temporary Publishers table using the CREATE
TABLE statement. Then the INSERT with a SELECT statement is used to add
INSERT tmpPublishers
FROM Publishers
In this example, the publishers’ data are copied to the tmpPublishers table and
FROM Publishers
UPDATE statement
The UPDATE statement changes data in existing rows either by adding new data
This example uses the UPDATE statement to standardize the country field to be
UPDATE Publishers
This example increases the royalty amount by 10% for those royalty amounts
UPDATE roysched
20
The employees from the Employees table who were hired by the publisher in
2010 are given a promotion to the highest job level for their job type. This is what
UPDATE
Employees SET
job_lvl=
DELETE statement
The DELETE statement removes rows from a record set. DELETE names the
table or view that holds the rows that will be deleted and only one table or row
may be listed at a time. WHERE is a standard WHERE clause that limits the
[WHERE clause]
1. If you omit a WHERE clause, all rows in the table are removed (except for
2. DELETE cannot be used with a view that has a FROM clause naming more
than one table. (Delete can affect only one base table at a time.)
What follows are three different DELETE statements that can be used.
DELETE
FROM Discounts
DELETE
FROM Sales
WHERE title_idIN
3.6Aggregate functions
FUNCTION DESCRIPTION
Returns the average of all the values, or only the DISTINCT values, in
AVG
the expression.
Returns the maximum value in the expression. MAX can be used with
numeric, character and datetime columns, but not with bit columns.
MAX
With character columns, MAX finds the highest value in the collating
sequence. MAX ignores any null values.
Returns the minimum value in the expression. MIN can be used with
numeric, character and datetime columns, but not with bit columns.
MIN
With character columns, MIN finds the value that is lowest in the sort
sequence. MIN ignores any null values.
Returns the sum of all the values, or only the DISTINCT values, in
SUM
the expression. SUM can be used with numeric columns only.
-FROM Publishers
SELECT COUNT(*)
FROM Employees
WHERE job_lvl = 35
In the example below, a price that contains two 9s is converted into five characters. The
syntax for this statement is SELECT ‘The date is ‘ + CONVERT(varchar(12), getdate()).
In this second example, the conversion function changes data to a data type with a different size.
The date function produces a date by adding an interval to a specified date. The result is
a datetime value equal to the date plus the number of date parts. If the date parameter is
a smalldatetime value, the result is also a smalldatetime value.
The DATEADD function is used to add and increment date values. The syntax for this
function is DATEADD(datepart, number, date).
Year Yy 1753-9999
Quarter Qq 1-4
Month mm 1-12
Day of year dy 1-366
Day dd 1-31
Week wk 1-53
Hour hh 0-23
Minute mi 0-59
Second ss 0-59
Millisecond ms 0-999
This command returns the number of datepart “boundaries” crossed between two
specified dates. The method of counting crossed boundaries makes the result given by
DATEDIFF consistent across all data types such as minutes, seconds, and milliseconds.
For any particular date, we can examine any part of that date from the year to the millisecond.
The date parts (DATEPART) and abbreviations recognized by SQL Server, and the
acceptable values are listed in Table 16.5.
rules that the database is not permitted to violate. Constraints may apply to
EXAMPLE- A brood group must be ‘A’ or ‘B’ or ‘AB’ or ‘O’ only (cannot any other
values else).
1. Domain Integrity
4. Key Constraints
1. Domain Integrity-
Domain integrity means the definition of a valid set of values for an attribute. You
define data type, length or size, is null value allowed , is the value unique or not for an
attribute ,the default value, the range (values in between) and/or specific values for
the attribute.
This rule states that in any database relation value of attribute of a primary key can't
and it must not contain any null value whereas other attributes may contain null value
11255324 Ajay ME
It states that if a foreign key exists in a relation then either the foreign key value must
match a primary key value of some tuple in its home relation or the foreign key value
must be null.
1. You can't delete a record from a primary table if matching records exist in a
related table.
2. You can't change a primary key value in the primary table if that record has
related records.
3. You can't enter a value in the foreign key field of the related table that doesn't
4. However, you can enter a Null value in the foreign key, specifying that the
EXAMPLE-
Consider 2 relations "stu" and "stu_1" Where "Stu_id " is the primary key in the "stu"
Relation "stu"
Relation "stu_1"
Examples
Rule 1. You can't delete any of the rows in the ”stu” relation that are visible since all
Rule 2. You can't change any of the ”Stu_id” in the “stu” relation since all the “Stu_id”
are in use in the ”stu_1” relation. * Rule 3.* The values that you can enter in the”
Stu_id” field in the “stu_1” relation must be in the” Stu_id” field in the “stu” relation.
Rule 4 You can enter a null value in the "stu_1" relation if the records are unrelated.
13.Key Constraints-
5. Check constraints
row of data unique. Although the primary key typically consists of one column in a
table, more than one column can comprise the primary key.
For example, either the employee's Social Security number or an assigned employee
identification number is the logical primary key for an employee table. The objective
is for every record to have a unique primary key or value for the employee's
identification number. Because there is probably no need to have more than one
record for each employee in an employee table, the employee identification number
makes a logical primary key. The primary key is assigned at table creation.
The following example identifies the EMP_ID column as the PRIMARY KEY for the
EMPLOYEES table:
A unique column constraint in a table is similar to a primary key in that the value in
that column for every row of data in the table must have a unique value. Although a
primary key constraint is placed on one column, you can place a unique constraint
on another column even though it is not actually for use as the primary key.
A foreign key is a column in a child table that references a primary key in the parent
table. A foreign key constraint is the main mechanism used to enforce referential
Previous examples use the keywords NULL and NOT NULL listed on the same line as
each column and after the data type. NOT NULL is a constraint that you can place on
a table's column. This constraint disallows the entrance of NULL values into a
column; in other words, data is required in a NOT NULL column for each row of data
in the table. NULL is generally the default for a column if NOT NULL is not specified,
Check (CHK) constraints can be utilized to check the validity of data entered into
particular table columns. Check constraints are used to provide back-end database
edits, although edits are commonly found in the front-end application as well.
General edits restrict values that can be entered into columns or objects, whether
referencing a column, or set of columns, in the Child table that contains the foreign
key, to the PRIMARY KEY column or set of columns, in the Parent table.
The relationship between the child and the parent tables is maintained by checking
the existence of the child table FOREIGN KEY values in the referenced parent table’s
PRIMARY KEY before inserting these values into the child table. In this way, the
FOREIGN KEY constraint, in the child table that references the PRIMARY KEY in the
parent table, will enforce database referential integrity. Referential integrity ensures
that the relationship between the database tables is preserved during the data
insertion process. Recall that the PRIMARY KEY constraint guarantees that no NULL
or duplicate values for the selected column or columns will be inserted into that table,
enforcing the entity integrity for that table. The entity integrity enforced by the
PRIMARY KEY and the referential integrity enforced by the FOREIGN KEY together
The FOREIGN KEY constraint differs from the PRIMARY KEY constraint in that, you
can create only one PRIMARY KEY per each table, with the ability to create multiple
FOREIGN
KEY constraints in each table by referencing multiple parent table.
values if there is no NOT NULL constraint defined on this key, but the
The FOREIGN KEY constraint provides you also with the ability to control
what action will be taken when the referenced value in the parent table
The supported actions that can be taken when deleting or updating the
parent table, all related rows in the child table are also deleted.
modified, all related values in the child table are set to NULL value.
values in the child table with FOREIGN KEY columns will be set to