DB Lab Manual
DB Lab Manual
DB Lab Manual
DATABASE SYSTEMS
Tool
Microsoft SQL Server Management Studio
Semester-Fall
Spring-2023
Instructor
Course
Database Systems
Department
Computer Science
LAB#01______________________________________
1
Database Systems Lab_Manual
The data type specifies what type of data the column can hold. For a complete reference of all
the data types available in MS Access, MySQL, and SQL Server, go to our complete Data Types
reference.
Now we want to create a table called "Persons" that contains five columns: P_Id, LastName,
FirstName, Address, and City.
2
Database Systems Lab_Manual
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
Now we want to update the person "Tjessem, Jakob" in the "Persons" table.
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'
3
Database Systems Lab_Manual
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.
4
Database Systems Lab_Manual
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
or
Note: Be very careful when deleting records. You cannot undo this statement!
5
Database Systems Lab_Manual
LAB#02______________________________________
1-SQL DROP TABLE Statement
Syntax
DROP TABLE table_name;
Note: Be careful before dropping a table. Deleting a table will result in loss of complete
information stored in the table!
DROP TABLE Shippers;
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table
itself.
Syntax
TRUNCATE TABLE table_name;
The ALTER TABLE statement is also used to add and drop various constraints on an existing
table.
6
Database Systems Lab_Manual
ALTER TABLE table_name
ADD column_name datatype;
ALTER TABLE Customers
ADD Email varchar(255);
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;
ALTER TABLE table_name
RENAME COLUMN old_name to new_name;
7
Database Systems Lab_Manual
To change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
ALTER TABLE table_name
MODIFY column_name datatype;
8
Database Systems Lab_Manual
ALTER TABLE Persons
ADD DateOfBirth date;
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date. The data
type specifies what type of data the column can hold. For a complete reference of all the data
types available in MS Access, MySQL, and SQL Server, go to our complete Data Types
reference.
Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two- or
four-digit format.
Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
ALTER TABLE Persons
DROP COLUMN DateOfBirth;
9
Database Systems Lab_Manual
LAB#03______________________________________
The AND and OR operators are used to filter records based on more than one condition:
1-AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
10
Database Systems Lab_Manual
2-OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
3-NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
AND Example
The following SQL statement selects all fields from "Customers" where country is "Germany"
AND city is "Berlin":
Example
SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
OR Example
The following SQL statement selects all fields from "Customers" where city is
"Berlin" OR "München":
Example
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is "Germany"
OR "Spain":
Example
SELECT * FROM Customers
WHERE Country='Germany' OR Country='Spain';
11
Database Systems Lab_Manual
NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany';
The following SQL statement selects all fields from "Customers" where country is "Germany"
AND city must be "Berlin" OR "München" (use parenthesis to form complex expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
The following SQL statement selects all fields from "Customers" where country is NOT
"Germany" and NOT "USA":
Example
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
LAB#04______________________________________
12
Database Systems Lab_Manual
This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT
accept NULL values when the "Persons" table is created:
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
To create a NOT NULL constraint on the "Age" column when the "Persons" table is already
created, use the following SQL:
ALTER TABLE Persons
ALTER COLUMN Age int NOT NULL;
ALTER TABLE Persons
MODIFY COLUMN Age int NOT NULL;
ALTER TABLE Persons
MODIFY Age int NOT NULL;
13
Database Systems Lab_Manual
Inside a table, a column often contains many duplicate values; and sometimes you only want to
list the different (distinct) values.
Demo Database
14
Database Systems Lab_Manual
Example
SELECT DISTINCT Country FROM Customers;
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
Example
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
The default value will be added to all new records, if no other value is specified.
15
Database Systems Lab_Manual
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);
CREATE TABLE Orders (
ID int NOT NULL,
OrderNumber int NOT NULL,
OrderDate date DEFAULT GETDATE()
);
To create a DEFAULT constraint on the "City" column when the table is already created, use the
following SQL:
MySQL:
ALTER TABLE Persons
ALTER City SET DEFAULT 'Sandnes';
SQL Server:
ALTER TABLE Persons
ADD CONSTRAINT df_City
DEFAULT 'Sandnes' FOR City;
MS Access:
16
Database Systems Lab_Manual
ALTER TABLE Persons
ALTER COLUMN City SET DEFAULT 'Sandnes';
Oracle:
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';
MySQL:
ALTER TABLE Persons
ALTER City DROP DEFAULT;
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT;
SQL Server:
ALTER TABLE Persons
ALTER COLUMN City DROP DEFAULT;
LAB#05______________________________________
17
Database Systems Lab_Manual
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
18
Database Systems Lab_Manual
snabbköp Berglund n8
The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:
Example
SELECT * FROM Customers
WHERE Country='Mexico';
SQL requires single quotes around text values (most database systems will also allow double
quotes).
Example
SELECT * FROM Customers
WHERE CustomerID=1;
Operator Description
19
Database Systems Lab_Manual
= Equal
20
Database Systems Lab_Manual
If a field in a table is optional, it is possible to insert a new record or update a record without
adding a value to this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a
NULL value is one that has been left blank during record creation!
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
21
Database Systems Lab_Manual
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
22
Database Systems Lab_Manual
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample
database:
23
Database Systems Lab_Manual
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" column:
Example
SELECT * FROM Customers
ORDER BY Country;
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
Example
SELECT * FROM Customers
ORDER BY Country DESC;
24
Database Systems Lab_Manual
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column. This means that it orders by Country, but if some
rows have the same Country, it orders them by CustomerName:
Example
SELECT * FROM Customers
ORDER BY Country, CustomerName;
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
LAB#06______________________________________
* Represents zero or more bl* finds bl, black, blue, and blob
25
Database Systems Lab_Manual
characters
[] Represents any single character h[oa]t finds hot and hat, but not
within the brackets hit
! Represents any character not in h[!oa]t finds hit, but not hot and
the brackets hat
# Represents any single numeric 2#5 finds 205, 215, 225, 235,
character 245, 255, 265, 275, 285, and 295
26
Database Systems Lab_Manual
[] Represents any single character within h[oa]t finds hot and hat,
the brackets but not hit
^ Represents any character not in the h[^oa]t finds hit, but not
brackets hot and hat
- Represents any single character within c[a-b]t finds cat and cbt
the specified range
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
WHERE CustomerName Finds any values that have "or" in any position
LIKE '%or%'
WHERE CustomerName Finds any values that have "r" in the second
LIKE '_r%' position
27
Database Systems Lab_Manual
WHERE CustomerName Finds any values that starts with "a" and are at
LIKE 'a__%' least 3 characters in length
WHERE ContactName LIKE Finds any values that starts with "a" and ends with
'a%o' "o"
The following SQL statement selects all customers with a City starting with "ber":
Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';
The following SQL statement selects all customers with a City containing the
pattern "es":
Example
SELECT * FROM Customers
WHERE City LIKE '%es%';
The following SQL statement selects all customers with a City starting with any character,
followed by "ondon":
Example
SELECT * FROM Customers
WHERE City LIKE '_ondon';
28
Database Systems Lab_Manual
The following SQL statement selects all customers with a City starting with "L", followed by
any character, followed by "n", followed by any character, followed by "on":
Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';
The following SQL statement selects all customers with a City starting with "b", "s", or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';
The two following SQL statements select all customers with a City NOT starting with "b", "s",
or "p":
Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';
Or:
Example
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';
29
Database Systems Lab_Manual
LAB#07______________________________________
The ALL operator:
ALL means that the condition will be true only if the operation is true for all values in the range.
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
30
Database Systems Lab_Manual
The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table
is created. The CHECK constraint ensures that the age of a person must be 18, or older:
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int CHECK (Age>=18)
);
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
To create a CHECK constraint on the "Age" column when the table is already created, use the
following SQL:
31
Database Systems Lab_Manual
ALTER TABLE Persons
ADD CHECK (Age>=18);
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
ALTER TABLE Persons
DROP CONSTRAINT CHK_PersonAge;
MySQL:
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;
If a field in a table is optional, it is possible to insert a new record or update a record without
adding a value to this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a
NULL value is one that has been left blank during record creation!
32
Database Systems Lab_Manual
It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
33
Database Systems Lab_Manual
D.F.
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL;
The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
The following SQL lists all customers with a value in the "Address" field:
34
Database Systems Lab_Manual
Example
SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NOT NULL;
LAB#08______________________________________
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single
or multiple columns (fields).
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons"
table is created:
MySQL:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
35
Database Systems Lab_Manual
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);
Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the
VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use
the following SQL:
ALTER TABLE Persons
ADD PRIMARY KEY (ID);
ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);
Note: If you use ALTER TABLE to add a primary key, the primary key column(s) must have
been declared to not contain NULL values (when the table was first created).
36
Database Systems Lab_Manual
MySQL:
ALTER TABLE Persons
DROP PRIMARY KEY;
ALTER TABLE Persons
DROP CONSTRAINT PK_Person;
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.
The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
Persons Table
1 Hansen Ola 30
2 Svendson Tove 23
3 Pettersen Kari 20
37
Database Systems Lab_Manual
Orders Table
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key
column, because it has to be one of the values contained in the parent table.
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders"
table is created:
MySQL:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
38
Database Systems Lab_Manual
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
REFERENCES Persons(PersonID)
);
To create a FOREIGN KEY constraint on the "PersonID" column when the "Orders" table is
already created, use the following SQL:
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
39
Database Systems Lab_Manual
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
MySQL:
ALTER TABLE Orders
DROP FOREIGN KEY FK_PersonOrder;
ALTER TABLE Orders
DROP CONSTRAINT FK_PersonOrder;
LAB#09______________________________________
SQL Functions
SQL aggregate functions return a single value, calculated from values in a column.
40
Database Systems Lab_Manual
OrderAverage
950
Now we want to find the customers that have an OrderPrice value higher than the average
OrderPrice value.
41
Database Systems Lab_Manual
Customer
Hansen
Nilsen
Jensen
The COUNT() function returns the number of rows that matches a specified criteria.
The COUNT(column_name) function returns the number of values (NULL values will not be
counted) of the specified column:
The COUNT(DISTINCT column_name) function returns the number of distinct values of the
specified column:
Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with
Microsoft Access.
42
Database Systems Lab_Manual
The result of the SQL statement above will be 2, because the customer Nilsen has made 2 orders
in total:
CustomerNilsen
2
NumberOfOrders
6
43
Database Systems Lab_Manual
Now we want to count the number of unique customers in the "Orders" table.
NumberOfCustomers
3
which is the number of unique customers (Hansen, Nilsen, and Jensen) in the "Orders" table.
The FIRST() function returns the first value of the selected column.
44
Database Systems Lab_Manual
FirstOrderPrice
1000
The LAST() function returns the last value of the selected column.
45
Database Systems Lab_Manual
LastOrderPrice
100
The MAX() function returns the largest value of the selected column.
46
Database Systems Lab_Manual
LargestOrderPrice
2000
The MIN() function returns the smallest value of the selected column.
47
Database Systems Lab_Manual
SmallestOrderPrice
100
48
Database Systems Lab_Manual
OrderTotal
5700
LAB#10______________________________________
1-SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.
The following SQL statement creates two aliases, one for the CustomerID column and one for
the CustomerName column:
Example
SELECT CustomerID AS ID, CustomerName AS Customer
FROM Customers;
49
Database Systems Lab_Manual
The following SQL statement creates two aliases, one for the CustomerName column and one
for the ContactName column. Note: It requires double quotation marks or square brackets if the
alias name contains spaces:
Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person]
FROM Customers;
The following SQL statement creates an alias named "Address" that combine four columns
(Address, PostalCode, City and Country):
Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;
Note: To get the SQL statement above to work in MySQL use the following:
Note: To get the SQL statement above to work in Oracle use the following:
SELECT CustomerName, (Address || ', ' || PostalCode || ' ' || City || ', ' || Country) AS Address
FROM Customers;
The following SQL statement selects all the orders from the customer with CustomerID=4
(Around the Horn). We use the "Customers" and "Orders" tables, and give them the table aliases
of "c" and "o" respectively (Here we use aliases to make the SQL shorter):
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;
The following SQL statement is the same as above, but without aliases:
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName
FROM Customers, Orders
50
Database Systems Lab_Manual
WHERE Customers.CustomerName='Around the
Horn' AND Customers.CustomerID=Orders.CustomerID;
The BETWEEN operator selects values within a given range. The values can be numbers, text,
or dates.
BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
To display the products outside the range of the previous example, use NOT
BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
51
Database Systems Lab_Manual
The following SQL statement selects all products with a price between 10 and
20. In addition; do not show products with a CategoryID of 1,2, or 3:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20
AND CategoryID NOT IN (1,2,3);
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
IN Operator Examples
The following SQL statement selects all customers that are located in
"Germany", "France" or "UK":
52
Database Systems Lab_Manual
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
The following SQL statement lists the number of customers in each country.
Only include countries with more than 5 customers:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
LAB#11______________________________________
53
Database Systems Lab_Manual
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a
question mark (?) instead of the underscore (_).
The percent sign and the underscore can also be used in combinations!
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
WHERE CustomerName LIKE Finds any values that start with "a"
'a%'
WHERE CustomerName LIKE Finds any values that end with "a"
'%a'
54
Database Systems Lab_Manual
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second
'_r%' position
WHERE CustomerName LIKE Finds any values that start with "a" and are at
'a_%' least 2 characters in length
WHERE CustomerName LIKE Finds any values that start with "a" and are at
'a__%' least 3 characters in length
WHERE ContactName LIKE Finds any values that start with "a" and ends with
'a%o' "o"
Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
55
Database Systems Lab_Manual
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle 12 Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
SELECT *
FROM (SELECT column_name(s) FROM table_name ORDER BY column_name(s))
WHERE ROWNUM <= number;
The following SQL statement selects the first three records from the
"Customers" table (for SQL Server/MS Access):
Example
SELECT TOP 3 * FROM Customers;
The following SQL statement selects the first 50% of the records from the
"Customers" table (for SQL Server/MS Access):
56
Database Systems Lab_Manual
Example
SELECT TOP 50 PERCENT * FROM Customers;
Inside a table, a column often contains many duplicate values; and sometimes
you only want to list the different (distinct) values.
The following SQL statement selects only the DISTINCT values from the
"Country" column in the "Customers" table:
Example
SELECT DISTINCT Country FROM Customers;
LAB#12______________________________________
The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".
57
Database Systems Lab_Manual
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
The following SQL statement lists the number of customers in each country:
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
58
Database Systems Lab_Manual
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the column
names in the first SELECT statement.
The following SQL statement returns the cities (only distinct values) from both
the "Customers" and the "Suppliers" table:
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
The following SQL statement returns the cities (duplicate values also) from both
the "Customers" and the "Suppliers" table:
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
LAB#13______________________________________
59
Database Systems Lab_Manual
SQL JOIN
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two tables
above is the "CustomerID" column.
60
Database Systems Lab_Manual
Then, we can create the following SQL statement (that contains an INNER JOIN),
that selects records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
61
Database Systems Lab_Manual
The following SQL statement selects all orders with customer information:
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
The following SQL statement selects all orders with customer and shipper
information:
Example
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from the
right side, if there is no match.
62
Database Systems Lab_Manual
The following SQL statement will select all customers, and any orders they
might have:
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records from the left table (table1). The result is 0 records from the
left side, if there is no match.
The following SQL statement will return all employees, and any orders they
might have placed:
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
63
Database Systems Lab_Manual
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
LAB#14______________________________________
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
64
Database Systems Lab_Manual
You can add SQL statements and functions to a view and present the data as if
the data were coming from one single table.
Note: A view always shows up-to-date data! The database engine recreates the
view, every time a user queries it.
The following SQL creates a view that shows all customers from Brazil:
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
Example
SELECT * FROM [Brazil Customers];
The following SQL adds the "City" column to the "Brazil Customers" view:
65
Database Systems Lab_Manual
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
Example
DROP VIEW [Brazil Customers];
2-identity(for increment)
Note: no.15 and no.16 labs can be arranged and managed up to need of time, and these labs
will be considered for the evaluation of Project/Presentation( Depends on Instructor).
66