DBMS lab session unit 5
DBMS lab session unit 5
1
Introduction To SQL Server
Microsoft is the vendor of SQL Server. The newest
version is “SQL Server 2012”.
We have different editions of SQL Server, where SQL
Server Express is free to download and use.
SQL Server uses T-SQL (Transact-SQL).
T-SQL is Microsoft's proprietary extension to SQL.
T-SQL is very similar to standard SQL, but in addition it
supports some extra functionality, built-in functions, etc.
T-SQL expands on the SQL standard to include
procedural programming, local variables, various
support functions for string processing, date processing,
mathematics, etc.
2
SQL Server consists of a Database Engine and a
Management Studio.
The Database engine has no graphical interface - it is
just a service running in the background of your
computer (preferable on the server).
The Management Studio is graphical tool for
configuring and viewing the information in the
database.
It can be installed on the server or on the client (or both).
3
4
SQL Server runs as a separate Windows process on a
suitable Windows-based computer be it on a standalone
desktop machine, or on a server or network.
If you open Task Manager and move to the Processes tab,
you will see, among other processes, sqlservr.exe.
This process or service runs in its own process space,
and is isolated from other processes on the machine.
This that SQL Server should not be affected by any other
piece of software that does not talk to any SQL Server
component.
If you have to kill any other component’s process, the
SQL Server engine should continue to run.
SQL Server runs as a service that is controlled and
monitored by Windows itself. 5
Windows ensures that it is given the right amount of
memory, processing power, and time, and that everything
is working well.
Because SQL Server runs as a service, it has no interface
attached to it for a user to interact with.
As a result, there needs to be at least one separate utility
that can pass commands and functions from a user
through to the SQL Server service, which then passes them
through to the underlying database.
The GUI tool that accomplishes this is SQL Server
Management Studio, also known as SSMS
6
SQL Server Management Studio
SQL Server Management Studio is a GUI tool included
with SQL Server for configuring, managing, and
administering all components within Microsoft SQL
Server.
The tool includes both script editors and graphical tools
that work with objects and features of the server.
As mentioned earlier, version of SQL Server
Management Studio is also available for SQL Server
Express Edition, for which it is known as SQL Server
Management Studio Express.
A central feature of SQL Server Management Studio is
the Object Explorer, which allows the user to browse,
select, and act upon any of the objects within the server.
7
It can be used to visually observe and analyze query
plans and optimize the database performance, among
others.
SQL Server Management Studio can also be used to
create a new database, alter any existing database
schema by adding or modifying tables and indexes, or
analyze performance.
It includes the query windows which provide a GUI
based interface to write and execute queries.
8
9
SQL
SQL is a database computer language designed for the
retrieval and management of data in relational
database.
SQL stands for Structured Query Language.
SQL is a language of database, it includes:
Database creation, deletion, fetching rows and
modifying rows etc.
SQL is an ANSI (American National Standards Institute)
standard but there are many different versions of the SQL
language.
• SQL is structured Query Language which is a computer
language for storing, manipulating and retrieving data
stored in relational database.
• SQL is the standard language for Relation Database
System. 10
All relational database management systems like MySQL,
MS Access, Oracle, Sybase, Informix, postgres and SQL
Server uses SQL as standard database language.
Why SQL?
Allow users to access data in relational database
management systems.
Allow users to describe the data.
Allow users to define the data in database and manipulate
that data.
Allow to embed within other languages using SQL
modules, libraries & pre-compilers.
Allow users to create and drop databases and tables.
Allow users to create view, stored procedure, functions in
a database.
Allow users to set permissions on tables, procedures, and
11
views
SQL Commands:
The standard SQL commands to interact with relational databases
are CREATE, SELECT, INSERT, UPDATE, DELETE, and
DROP.
These commands can be classified into groups based on their
nature:
12
13
SQL –Syntax
SQL is followed by unique set of rules and guidelines
called Syntax.
All the SQL statements start with any of the keywords like
SELECT, INSERT, UPDATE, DELETE, ALTER,
DROP, CREATE, USE, SHOW and all the statements end
with a semicolon (;).
Important point to be noted is that SQL is not case
sensitive which means SELECT and select have same
meaning in SQL statements but MySQL make difference
in table names.
So if you are working with MySQL then you need to give
table names as they exist in the database.
14
1. Database Definition Language (DDL)
The Data Definition Language (DDL) manages table and index
structure.
The most basic items of DDL are the CREATE, ALTER,
RENAME, TRUNCATE and DROP statements.
The major CREATE statements are:
CREATE Database –defines to create a new SQL database.
CREATE TABLE – defines a table and its columns
CREATE VIEW – defines a logical table from one or more
views.
ALTER modifies the structure an existing object in various
ways—for example, adding a column to an existing table.
TRUNCATE deletes all data from a table in a very fast
way. It usually implies a subsequent COMMIT operation.
15
1.1 CREATE Database
The SQL CREATE DATABASE statement is used to
create new SQL database.
Syntax:
Basic syntax of CREATE DATABASE statement is as
follows:
CREATE DATABASE DatabaseName;
Always database name should be unique within the
RDBMS.
Example: If you want to create new database such as
SCHOOLDB DATABASE then CREATE DATABASE
statement would be as follows:
CREATE DATABASE SCHOOLDB;
16
1.2 DROP or DELETE Database
The SQL DROP DATABASE statement is used to drop any
existing database in SQL schema.
Syntax of DROP DATABASE statement is as follows:
DROP DATABASE DatabaseName;
Always database name should be unique within the
RDBMS.
Example: If you want to delete an existing database
SCHOOLDB then DROP DATABASE statement would be
as follows:
DROP DATABASE SCHOOLDB;
NOTE: Be careful before using this operation because by
deleting an existing database would result in loss of
complete information stored in the database.
Make sure you has admin privilege before dropping any
database. 17
1.3 SELECT Database
When you have multiple databases in your SQL Schema,
then before starting your operation, you would need to
select a database where all the operations would be
performed.
The SQL USE statement is used to select any existing
database in SQL schema.
Basic syntax of USE statement is as follows:
USE DatabaseName;
Always database name should be unique within the
RDBMS.
18
1.4 CREATE Table
Creating a basic table involves naming the table and
defining its columns and each column's data type.
The SQL CREATE TABLE statement is used to create a
new table.
Syntax:
20
Best practice:
When creating tables you should consider following these
guidelines:
Tables: Use upper case and singular form in table names –
not plural, e.g., “CUSTOMER”. Never use spaces inside the
table names.
Columns: Use Pascal notation, e.g., “CustomerId”.
Never use spaces inside the column names.
Primary Keys: Use Integer and Identity(1,1) for Primary
Keys.
Then the Primary Keys will just be a running number that
is automatically inserted by the system.
It is also a good idea to name the Primary Key column the
same as the table name + Id, e.g., if the table name is
“CUSTOMER” (upper case), then the Primary Key column
21
should be named “CustomerId” (Pascal notation).
1.5 DROP or DELETE Table
Used to remove a table definition and all data,
indexes, triggers, constraints, and permission
specifications for that table.
NOTE: You have to be careful while using this
command because once a table is deleted then all
the information available in the table would also be
lost forever.
Syntax :
DROP TABLE table_name;
Example: Let us first verify CUSTOMERS table,
and then we would drop it from the database:
It is done as follows:
DROP TABLE CUSTOMER; 22
SQL Constraints
Constraints are used to limit the type of data that can go
into a table.
Constraints can be specified:
i) When a table is created (with the CREATE TABLE
statement) or
ii)After the table is created (with the ALTER TABLE
statement).
Here are the most important constraints used in SQL:
PRIMARY KEY
FOREIGN KEY
NOT NULL
UNIQUE
CHECK
DEFAULT
IDENTITY 23
A) PRIMARY KEY
Used to uniquely identifies each record in a database table.
Primary keys must contain unique values.
Syntax: column_name dtata_type identity () Primary key
It is normal to just use running numbers, like 1, 2, 3, 4, 5, …
as values in Primary Key column.
It is a good idea to let the system handle this for you by
specifying that the Primary Key should be set to
identity(1,1).
IDENTITY(1,1) means the first value will be 1 and then it
will increment by 1.
Each table should have a primary key, and each table can
have only ONE primary key.
In the previous example we placed the primary key column
at the beginning when we identify the column name we can
also set the primary key as follows: 24
USE SCHOOLDB
CREATE TABLE CUSTOMER
(
CustomerId int,
CustomerNumber int,
LastName varchar(50),
FirstName varchar(50),
AreaCode int,
Address varchar(50),
Phone varchar(50),
PRIMARY KEY (CustomerId)
);
25
B) FOREIGN KEY
A foreign key is used:
i) Prevent actions that would destroy links between tables.
ii)Prevents that invalid data from being inserted into the
foreign key column.
Because it has to be one of the values contained in the
table it points to.
A FOREIGN KEY in one table points to a PRIMARY
KEY in another table.
Syntax: column_name data_type foreign key references
table_name (column_name-used as a foreign key)
Example: Let’s create two tables by the name SCHOOL
and CLASS under SCHOOLDB and implement the
primary key of SCHOOL table to be a foreign key of
CLASS table since SCHOOL and CLASS table has one
to many relationships. 26
First Create a table SCHOOL using the following SQL
code:
USE SCHOOLDB
CREATE TABLE SCHOOL
(
SchoolId int PRIMARY KEY,
SchoolName varchar(50),
Description varchar(1000),
Address varchar(50),
Phone varchar(50) ,
PostCode varchar(50) ,
PostAddress varchar(50)
);
27
The many side relationship table called CLASS SQL code
is described below in which the table uses the primary key
of the SCHOOL table as a foreign key.
The CLASS table has also its own primary key in order to
uniquely identify each records in the table.
USE SCHOOLDB
CREATE TABLE CLASS
(
ClassId int PRIMARY KEY,
SchoolId int FOREIGN KEY REFERENCES
SCHOOL (SchoolId),
ClassName varchar(50) ,
Description varchar(1000)
); 28
C) NOT NULL / Required Columns
used to enforces a column to NOT accept NULL values or a
field to always contain a value.
This means that you cannot insert a new record, or update a
record without adding a value to this field.
Syntax: column_name data_type constraint_name
Example: Let’s implement NOT NULL constraint at the
CUSTOMER table created earlier in all of the fields except
the CustomerId:
USE SCHOOLDB
CREATE TABLE CUSTOMER
(
CustomerId int PRIMARY KEY,
CustomerNumber int NOT NULL,
LastName varchar(50) NOT NULL,
29
FirstName varchar(50) NOT NULL,
AreaCode int NOT NULL,
Address varchar(50) NOT NULL,
Phone varchar(50) NOT NULL
);
We see that all the above columns or fields except
CustomerId is set to “NOT NULL”, this means these
columns needs to contain data.
Note: A primary key column cannot contain NULL
values.
30
D) UNIQUE
Uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both
provide a guarantee for uniqueness for a column or set
of columns.
A PRIMARY KEY constraint automatically has a
UNIQUE constraint defined on it.
Note: You can have many UNIQUE constraints per
table, but only one PRIMARY KEY constraint per table.
Syntax: Column_name data_type constraint_name
Example: Let’s implement the UNIQUE constraint TO
CustomerNumber column name at the CUSTOMER table
created earlier:
The SQL code to implement this constraint is as follows.
31
USE SCHOOLDB
CREATE TABLE CUSTOMER
(
CustomerId int PRIMARY KEY,
CustomerNumber int UNIQUE,
LastName varchar(50) , NULL
FirstName varchar(50), NULL
AreaCode int , NULL
Address varchar(50) , NULL
Phone varchar(50), NULL
);
32
E) CHECK
used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it
allows 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.
Syntax: Column_name Data_Type Constraint_Name(Expression)
33
USE SCHOOLDB
CREATE TABLE CUSTOMER
(
CustomerId int PRIMARY KEY,
CustomerNumber int UNIQUE CHECK
(CustomerNumber>10),
LastName varchar(50) ,
FirstName varchar(50) ,
AreaCode int ,
Address varchar(50) ,
Phone varchar(50)
);
35
USE SCHOOLDB
CREATE TABLE CUSTOMER
(
CustomerId int PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE CHECK
(CustomerNumber>0),
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
Country varchar(50) DEFAULT 'Norway',
AreaCode int NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL,
);
In this case the default value is ‘Norway’ what ever
the users will not enter any value to the country column
36
in the table.
G) AUTO INCREAMENT or IDENTITY
used to allow the value of the primary key field to be
created automatically every time a new record is
inserted.
Syntax: Column_name Data-type Constraint_Name
(Started_value, Increment_value)
Example: Let’s implement AUTO INCREMENT OR
IDENTITY constraint to the column name of
CustomerId of the customer table created earlier,
assuming that the start value and increment value of the
constraint is 1 respectively.
The SQL code to implement this constraint is as follows.
37
USE SCHOOLDB
CREATE TABLE CUSTOMER
(
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE,
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
Country varchar(20) DEFAULT 'Norway',
AreaCode int NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL,
);
As shown the SQL code above, we use the
IDENTITY() for the CUSTOMER table
The IDENTITY(1,1) means the first value will be 1
38
and then it will increment by 1.
1.6 ALTER TABLE
is used to add, delete, or modify columns in an existing
table.
Syntax to add column in a table:
ALTER TABLE table_name
ADD column_name datatype
Syntax to delete a column in a table (notice that some
database systems don't allow deleting a column):
ALTER TABLE table_name
DROP COLUMN column_name
Syntax to change the data type of a column in a table:
ALTER TABLE table_name
ALTER COLUMN column_name datatype
Example 1: Let’s add a column by the name Citizen
to the CUSTOMER table created earlier using
ALTER STATEMENT. 39
The code below is the simple SQL code to add Citizen column to
the CUSTOMER table.
USE SCHOOLDB
ALTER TABLE CUSTOMER
ADD Citizen varchar (50)NULL;
Example 2: Delete or Drop the column you add previously from
the CUSTOMER table. Here is the simple SQL code to delete the
column name Citizen:
USE SCHOOLDB
ALTER TABLE CUSTOMER
DROP COLUMN Citizen;
Example 3: Change the data type of AreaCode column from int
to varchar in the CUSTOMER table created earlier. The simple
SQL code to perform this is as follows:
USE SCHOOLDB
ALTER TABLE CUSTOMER
ALTER COLUMN AreaCode varchar(50); 40
If we use CREATE TABLE and the table already exists in the
table we will get an error message, so if we combine CREATE
TABLE and ALTER TABLE we can create robust database
scripts that gives no errors, as the example shown below:
USE SCHOOLDB
if not exists (select * from dbo.sysobjects where id =
object_id(N'[CUSTOMER]') and
OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE CUSTOMER (
CustomerId int PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE,
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
AreaCode int NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL,
) 41
USE SCHOOLDB
GO
if exists(select * from dbo.syscolumns where id =
object_id(N'[CUSTOMER]') and OBJECTPROPERTY(id,
N'IsUserTable') = 1 and name = 'CustomerId')
ALTER TABLE CUSTOMER ALTER COLUMN CustomerId int
Else
ALTER TABLE CUSTOMER ADD CustomerId int
===============================================
USE SCHOOLDB
GO
if exists(select * from dbo.syscolumns where id =
object_id(N'[CUSTOMER]') and OBJECTPROPERTY(id,
N'IsUserTable') = 1 and name = 'CustomerNumber')
ALTER TABLE CUSTOMER ALTER COLUMN CustomerNumber
int
Else
ALTER TABLE CUSTOMER ADD CustomerNumber int
1.7 TRUNCATE STATEMENT
used to delete all data from a table in a very fast way.
It usually implies a subsequent COMMIT operation.
Syntax : TRUNCATE TABLE table_name;
Example: Let’s truncate all the data from the CUSTOMER table created
earlier. The following is a sample SQL code to truncate all the data from
the table:
USE SCHOOLDB
TRUNCATE TABLE CUSTOMER;
1. 8 RENAME STATEMENT
It is one of the alteration statement which is used to rename the
name of the existing table by the new one.
Syntax: ALTER TABLE table_name RENAME TO new_table_name;
Example: Let’s rename the CUSTOMER table we created earlier
by the new name EMPLOYEE. The following is a sample SQL
43
code.
USE SCHOOLDB
2. Data Manipulation Language (DML)
is the subset of SQL used to add, update and delete data.
The acronym CRUD refers to all of the major functions that
need to be implemented in a relational database application to
consider it complete.
But SELECT is a data query language though it is used as a
data manipulation language.
Each letter in the acronym can be mapped to a standard SQL
statement:
44
2.1 INSERT INTO
is used to insert a new row in a table.
it is possible to write the INSERT INTO statement in two
forms.
1) Without specifying the column names where the data will
be inserted, only their values:
Syntax: INSERT INTO table_name
VALUES (value1, value2, value3,...)
Example 1: Insert the following information in to
CUSTOMER table created earlier.
USE SCHOOLDB
INSERT INTO CUSTOMER
VALUES (44, 'Zelalem', 'Maseresha', 'ETHIOPIA', 'ETC202',
'Gonder', '+251918708990');
45
2) By specifying both the column names and the
values to be inserted:
Syntax:
INSERT INTO table_name (column1, column2,
column3,...)
VALUES (value1, value2, value3,...)
This form is recommended!
Example 2: Insert a value to the CUSTOMERS
table created using the second form of the INSERT
INTO Statement.
USE SCHOOLDB
INSERT INTO CUSTOMER(CustomerNumber, LastName,
FirstName, Country, AreaCode, Address, Phone)
VALUES (55, 'Teferi', 'Nigussie', 'Ethiopia', 'ETC203', 46
Insert Data Only in Specified Columns
It is also possible to only add data in specific
columns.
Example: Insert values in to only to columns such
as CustomerNumber, LastName, FirstName.
The following is a simple SQL code to insert
values in to only specified columns.
USE SCHOOLDB
INSERT INTO CUSTOMER (CustomerNumber,
LastName, FirstName)
VALUES ('133', 'Gebeyehu', 'Workineh');
Note:- You need at least to include all columns
that cannot be NULL.
47
2.2 UPDATE
is used to update existing records in a table.
Syntax:
UPDATE table_name
SET column1=value1, column2=value2,... columnN=valueN
WHERE some_column=some_value or [condition]
Notice that the WHERE clause in the UPDATE syntax.
specifies which record or records that should be updated.
If you omit the WHERE clause, all records will be updated!
Example 1: Update CUSTOMER table for column
AreaCode=ETC205 by BNC999 where CustomerNumber=77.
The following is the simple SQL code to perform this.
USE SCHOOLDB
UPDATE CUSTOMER
SET AreaCode='BNC999'
WHERE CustomerNumber=77;
48
Example 2: Update the value 22 in the CustomerNumber
column of the CUSTOMER table to 144 WHERE
CustomerId=7.
The following is the simple SQL statement to update the
request in the Example 2.
USE SCHOOLDB
UPDATE CUSTOMER
SET CustomerNumber=144
WHERE CustomerId=7;
49
2.3 DELETE
is used to delete rows in a table.
Syntax:
DELETE FROM table_name
WHERE some_column=some_value or [condition]
Notice that 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!
Example 1: Delete rows form the CUSTOMER table
where the CustomerId=8
The following is the simple SQL code to delete this
information.
USE SCHOOLDB
DELETE FROM CUSTOMER 50
WHERE CustomerId=8;
Delete All Rows:
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:
Syntax:
DELETE FROM table_name
Note:- Make sure to do this only when you really mean
it! You cannot UNDO this statement!.
Example 2: Delete all records from the CUSTOMER
table.
The following is the simple SQL code used to delete all
the records of the CUSTOMER information.
USE SCHOOLDB
DELETE FROM CUSTOMER; 51
3. Data Query Language (DQL)
is used to retrieve or read data from the database table.
3.1 SELECT STATEMENT
is used to fetch the data from the database table which
returns data in the form of result table.
These result tables are called result-sets.
The SELECT Statement
is used for retrieving rows from the database and
enables the selection of one or many rows or columns from
one or many tables in the database.
1) Syntax 1: The basic syntax is if you want to select only
specific columns you need.
SELECT column1, column2, columnN
FROM table_name;
Here column1, column2...are the fields of a table whose
values you want to fetch. 52
Example 1: Select records from the CUSTOMER table
by taking CustomerId, FirstName and LastName column
of the table.
Here is the simple SQL code to perform this operation.
USE SCHOOLDB
SELECT CustomerId, FirstName, LastName
FROM CUSTOMER;
The result set of the above SQL code is as follows:
53
2) Syntax 2: If you want to fetch all the records of the table in the
database, then you can use following syntax:
SELECT * FROM table_name;
The symbol “*” is used when you want to get all the columns or
records in the table.
Example 2: Select all of the records from the CUSTOMER table .
The following is the simple SQL code to perform this operation.
USE SCHOOLDB
SELECT * FROM CUSTOMER;
The Sample result set is as follows
54
3.1.1 SQL- Where Clause
SQL WHERE clause is used to specify a condition while
fetching the data from single table or joining with
multiple table.
If the given condition is satisfied then only it returns
specific value from the table.
You would use WHERE clause to filter the records and
fetching only necessary records.
The WHERE clause not only used in SELECT statement,
but it is also used in UPDATE, DELETE statement etc.
Syntax of SELECT statement with WHERE clause is as
follows:
SELECT column1, column2, columnN or *
FROM table_name
WHERE column-name, [condition] ;
55
Exampe 3: Select CustomerId, FirstName and Salary
fields from the CUSTOMER table where salary is greater
than 3000.
The SQL script is as follows:
USE SCHOOLDB
SELECT CustomerId, FirstName, Salary
FROM CUSTOMER
WHERE Salary > 3000;
The result set of the SQL statement is the following:
56
It is important to note that all the strings should be given
inside single quotes (‘ ') where as numeric values should
be given without any quote.
Activity
1) Write the SQL statement code to select CustomerId,
FirstName and Salary fields from the CUSTOMER table
for a customer’s FirstName is Daniel.
AND and OR Conjunctive Operators in Where Clause
The SQL AND and OR operators are:
used to combine multiple conditions to narrow data in
an SQL statement.
These two operators are called conjunctive operators.
These operators provide a means to make multiple
comparisons with different operators in the same SQL
statement. 57
A) The AND Operator:
allows the existence of multiple conditions or comparisons
it is used in an SQL statement's WHERE clause.
Syntax of AND operator with WHERE clause is as follows:
SELECT column1, column2, columnN
FROM table_name
WHERE column-name1,[condition1] AND column-
name2 [condition2]...AND column-nameN [conditionN];
You can combine N number of conditions using AND
operator.
For an action to be taken by the SQL statement, whether it
be a transaction or query, all conditions separated by the
AND must be TRUE.
Example 4: Select CustomerId, FirstName, LastName and
Salary fields from the CUSTOMER table where salary is
greater than 3000 and customer’s AreaCode is 'ETC209’. 58
The SQL statement to perform Example 4 operation and
condition is as follows.
USE SCHOOLDB
SELECT CustomerId, FirstName, LastName, Salary
FROM CUSTOMER
WHERE (AreaCode='ETC209')AND (Salary > 3000);
The result set of the above SQL select statement using
AND operator is as follows:
59
B) The OR Operator:
is used to combine multiple conditions in an SQL statement's
WHERE clause.
Syntax of OR operator with WHERE clause is as follows:
SELECT column1, column2, columnN
FROM table_name
WHERE column-name1[condition1] OR column-
name2[condition2]...OR column-nameN[conditionN]
You can combine N number of conditions using OR operator.
For an action to be taken by the SQL statement, whether it be
a transaction or query, only any ONE of the conditions
separated by the OR must be TRUE.
Example 5: Fetch CustomerId, FirstName, LastName and
Salary fields from the CUSTOMER table where salary is
greater than 3000 and customer’s Address is in Adama 60
The SQL statement to perform Example 5 operation and
condition is as follows.
USE SCHOOLDB
SELECT CustomerId, FirstName, LastName, Salary
FROM CUSTOMER
WHERE (Salary > 3000) OR (Address='Adama');
The result set of the above SQL select statement using OR
operator is as follows:
61
C) Combining AND & OR:
You can also combine AND and OR (use parenthesis to form
complex expressions).
Example: Let’s select all from the CUSTOMER table where the
conditions of LastName=‘Mulugeta' and (FirstName=‘Lijalem' or
FirstName=‘Mulugeta') is satisfied.
The following is the sample SQL code to perform AND and OR
operator together.
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE LastName='Mulugeta' AND (FirstName='Lijalem' OR
FirstName= 'Mulugeta');
And the result of this SQL statement is the following
62
The following are another operators that are used with the
WHERE clause, in SQL select statement.
63
D) LIKE Operator
is used to search for a specified pattern in a column.
Syntax:
SELECT column_name(s) or *
FROM table_name
WHERE column_name LIKE pattern
Example 6: Select all the records from CUSTOMER table where
their FirstName is like G.
The SQL code to perform this is as follows:
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE FirstName LIKE 'G%';
And the result set of the SQL select statement is the following .
64
Note: The "%" sign can be used to define wildcards
(missing letters in the pattern) both before and after the
pattern.
The following SQL select statement example implement
the “%” sign to define wildcards before and after the
pattern in the LIKE operator.
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE FirstName LIKE '%G%';
The result set of this SQL select statement is as
follows
65
You may also combine the LIKE operator with the NOT
keyword.
Example 7: Select all the records from CUSTOMER
table
Where FirstName NOT LIKE ‘%G%’.
The SQL Code is:
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE FirstName NOT LIKE '%G%'
The result set is also the following:
66
E) IN Operator
allows you to specify multiple values in a WHERE clause.
Syntax:
SELECT column_name(s) or *
FROM table_name
WHERE column_name IN (value1,value2,...)
Example 8: Select all the records from CUSTOMER table using IN
operator where AreaCode is ETC207, ETC208 and ETC209.
The SQL select statement is:
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE AreaCode IN (‘ETC207’, ‘ETC208’, ‘ETC209’);
And the result set is as follows:
67
F) BETWEEN Operator
used to select a range of data between two values.
The values can be numbers, text, or dates.
Syntax:
SELECT column_name(s) or *
FROM table_name
WHERE column_name BETWEEN value1 AND value2
Example 9: Select all the records from the CUSTOMER table
where salary is between 3000 and 6000.
The SQL select statement code is:
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE Salary
BETWEEN 3000 AND 6000;
68
G) The ORDER BY Keyword
use when you need data to appear in a specific order.
The data to appear might be in ASC or DESC order.
Syntax:
SELECT column1, column2....columnN or *
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
Example: Select all records from the CUSTOMER table
ordered by LastName where salary is greater than 4000 in
Descending order.
The following is a sample SQL code to perform this
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE Salary>4000
ORDER BY LastName DESC; 69
You can also sort by several columns, e.g. like this:
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE Salary>4000
ORDER BY LastName, Address;
If you use the “order by” keyword, the default order is
ascending (“asc”).
If you want the order to be opposite, i.e., descending,
then you need to use the “desc” keyword.
70
3.1.2 SELECT DISTINCT
In a table, some of the columns may contain duplicate
values.
This is not a problem, however, sometimes you will want
to list only the different (distinct) values in a table.
The DISTINCT keyword can be used to return only
distinct (different) values.
The syntax is as follows:
SELECT DISTINCT column1, column2....columnN
FROM table_name;
Example: Select all the distinct records from the
CUSTOMER table.
The following is a sample SQL code.
71
USE SCHOOLDB
SELECT DISTINCT AreaCode
FROM CUSTOMER;
The following is the result of the DISTINCT
select statement:
72
Wildcards
SQL wildcards can substitute for one or more characters
when searching for data in a database.
Note! SQL wildcards must be used with the SQL LIKE
operator.
With SQL, the following wildcards can be used:
73
Examples
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE LastName LIKE 'T_fe_i'
The result set of the above SQL code is looks like the following:
USE SCHOOLDB
SELECT * FROM CUSTOMER
WHERE CustomerNumber LIKE '[1]%'
The result set of the above SQL code is looks like the following:
74
SELECT TOP Clause
is used to specify the number of records to return.
very useful on large tables with thousands of records.
returning a large number of records can impact on performance.
Syntax:
SELECT TOP number | percent column_name(s) or *
FROM table_name
Example: Look at the following SQL query to select top 3 records
from the CUSTOMER table.
USE SCHOOLDB
SELECT TOP 3 * FROM CUSTOMER
The result test is the following:
75
You can also specify in percent:
USE SCHOOLDB
SELECT TOP 60 PERCENT * FROM CUSTOMER
This is very useful for large tables with thousands of
records
The result set of the above sample SQL code is the
following:
76
Alias
use when you want to give another name for a table or a
column.
This can be a good thing to do if you have very long or
complex table names or column names.
An alias name could be anything, but usually it is short.
SQL Alias Syntax for Tables:
SELECT column_name(s)
FROM table_name
AS alias_name
SQL Alias Syntax for Columns:
SELECT column_name AS alias_name
FROM table_name
77
Examples
Look at the following SQL query to implement alias to give new
name for the table and the column in Example1 and Example2
respectively in the EMPLOYEE table you create earlier.
Example1: SQL query to give alias name for the EMPLOYEE as
ALIASTHREE
USE SCHOOLDB
SELECT EmployeeId, EmployeeNumber, LastName,
FirstName,AreaCode, Address, Phone
FROM EMPLOYEE
AS ALIATHREE;
And the result set of the above SQL query is the following:
78
Example 2: SQL query to give alias name for column
name of LastName as ALIASTWO
USE SCHOOLDB
SELECT LastName AS ALIASTWO
FROM EMPLOYEE;
And the result set of the above SQL query is the
following:
79
Joins
used to select data from two or more tables, based on a relationship
between certain columns in these tables.
Get data from multiple tables in a single query using joins.
80
Example:
Given 2 tables:
SCHOOL
CLASS
The diagram is shown below:
81
Join Queries
is a query retrieving records from more than one table.
Records from different tables are usually joined on
related key field values.
The most efficient and effective forms of join are those
between directly related primary and foreign key fields.
There are a number of different types of joins:
1) Inner Join
is an intersection between two tables using matching field
values
returning records common to both tables only.
Within SQL code, joins are specified within the from
portion of the select statement.
The keyword join identifies the second table.
The on clause defines the common ground between the
two tables. 82
The JOIN is used to join the primary key in one table
with the foreign key in another table.
The default type of join is an inner join, so the keyword
inner is optional:
Syntax for INNER Join:
SELECT Table1.column-name, Table2.column-name
FROM Table1
INNER JOIN Table 2
on Table1.column=Table1.column
83
Let’s see the following SQL code to implement the inner
join:
SELECT SCHOOL.SchoolName, CLASS.ClassName
FROM SCHOOL
INNER JOIN CLASS ON SCHOOL.SchoolId =
CLASS.SchoolId
The result sets of this SQL code is in the following
84
2. Outer Joins
An inner join contains only the intersection of the two data
sets.
But an outer join extends the inner join by adding the
nonmatching data from the left or right data set.
Outer joins solve a significant problem for many queries
by including all the data regardless of a match.
Some of the data in the result set produced by an outer join
will look just like the data from an inner join.
There will be data in columns that come from each of the
data sources, but any rows from the outer-join table that do
not have a match in the other side of the join will return
data only from the outer-join table.
In this case, columns from the other data source will have
null values. 85
In SQL code, an outer join is declared by the keywords
left outer or right outer before the join.
Technically, the keyword outer is optional.
Syntax:
SELECT *
FROM Table1
LEFT | RIGHT [OUTER] JOIN Table2
ON Table1.column = Table2.column
Let’s see the following SQL Query to implement LEFT
OUTER join.
SELECT *
FROM SCHOOL
LEFT OUTER JOIN CLASS
ON SCHOOL.SchoolId = CLASS.SchoolId;
86
The result set of this SQL code is the following:
88
4. Data Control Language (DCL)
GRANT - Gives a privilege to user
REVOKE -Takes back privileges granted from user
89