0% found this document useful (0 votes)
16 views51 pages

SQL Server Lab Manual

The document is a lab manual for SQL, detailing its role in managing data within relational database management systems (RDBMS), particularly focusing on Microsoft SQL Server and its advantages over Microsoft Access. It covers installation requirements, hardware specifications, SQL commands for data manipulation and definition, and provides examples for creating and managing databases and tables. Additionally, it discusses the scalability, performance, and security features of SQL Server compared to simpler database systems.

Uploaded by

Tesfalegn Yakob
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
16 views51 pages

SQL Server Lab Manual

The document is a lab manual for SQL, detailing its role in managing data within relational database management systems (RDBMS), particularly focusing on Microsoft SQL Server and its advantages over Microsoft Access. It covers installation requirements, hardware specifications, SQL commands for data manipulation and definition, and provides examples for creating and managing databases and tables. Additionally, it discusses the scalability, performance, and security features of SQL Server compared to simpler database systems.

Uploaded by

Tesfalegn Yakob
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 51

Debre Markos University, Burie

Campus
Department of Computer Science
Fundamental of Database System SQL Lab Manual

Introduction
SQL (Structured Query Language) is a programming language designed for
managing data in relational database management systems (RDBMS).
It is a standard (main query) language for relational DBMSs, like Microsoft Access,
Microsoft SQL Server, and Oracle, that used to communicate with a database.
Microsoft SQL Server is designed to run on large multiprocessor servers. SQL Server is
commonly used as the backend system for websites and can support thousands of
concurrent users.
SQL Server is much more robust and scalable than a desktop databasemanagement
system such as Microsoft Access. Although SQL Server can also be run as a desktop
database system, it is most commonly used as a server database system.
Server based database systems are designed to run on a central server, so that multiple
users can access the same data simultaneously. The users normally access the database
through an application.
SQL Server is a more robust database management system. SQL Server was designed to
have many hundreds, or even thousands of users accessing it at any point in time.
Microsoft Access on the other hand, doesn't handle this type of load very well.
Access is more suited for desktop use with a small number of users accessing it
simultaneously. One reason you might choose to use Access over SQL Server is easy for
use. People are more likely to have Access on their desktop computer than SQL Server.
You'll generally only find SQL Server on developers' computers/servers or on production
server machines.
Another reason you might use Access instead of SQL Server is money. You might already
have installed Access as part of the Microsoft Office suite. Purchasing SQL Server would

1
be an extra expense that may not be necessary - depending on your situation. SQL
Server can also be quite expensive.
This makes SQL Server perfectly suited for database driven websites. You should never
use Access for a database driven website - unless it has a very small amount of traffic
(like you and a few of your friends). Even then, you may find yourself getting errors due
to multiple users trying to access the database at the same time.
SQL Server also contains some advanced database administration tools that enable
organizations to schedule tasks, receive alerts, optimize databases, configure security
accounts/roles, transfer data between other disparate sources, and much more.
The main benefits of SQL Server over Access are improved reliability, better
performance, reduced network traffic and increased scalability

Scalability

A file server system such as Access is designed for small workgroups and is scalable to
perhaps 10 concurrent clients. Above this level performance starts to degrade rapidly as
more users are added. With the SQL Server client/server architecture many hundreds, or
even thousands (with the appropriate infrastructure), of concurrent users can be
supported without significant performance degradation.

 Drawbacks

SQL Server is a (much) bigger and more complex than is Access. Although it is now
easier to manage than in the past it is less suitable for a company with no IT support
staff (in-house or outsourced) than is the simpler Access. It also costs more to implement
than does Access (you need to buy SQL Server licenses whereas the Access run-time
version is royalty free) and the development of a SQL Server system will usually take
longer and cost more than an equivalent Access system.

SQL is used to perform basic data management tasks, such as the insertion,
modification, and deletion of data from the tables using the standard SQL commands
such as "Select", "Insert", "Update", "Delete", "Create", and "Drop".

Hardware Requirements
A processor with high speed of data processing and memory of large size (RAM and Hard
disk space) is required to run the DBMS software.

2
Example: The Minimum hardware requirementsfor SQL Server 2008 installations
include:
. Processor
- Pentium 600 MHz or higher is required
- 1 GHz or higher is recommended.
. Memory
- 512 MB is required
- 1 GB or more is recommended
. Disk space
- Database components: 280 MB
- Analysis services: 90 MB
- Reporting services: 120 MB
- Integration services: 120 MB
- Client components: 850 MB
Operating System Requirements
The supported operating system for DBMS software may depends on the type and
version of the software.
Example: The Supported operating systems for SQL Server 2008 installations include:
- Windows 7
- Windows Server 2003 Service Pack 2
- Windows Server 2008
- Windows Server 2008 R2
- Windows Vista Service Pack 1
- Windows XP Service Pack 3

Install DBMS (SQL Server)


. To install SQL Server 2008 Express, you must have administrative rights on the
computer.
. The different editions/version of SQL Server share several common software
requirements such as Microsoft Windows installer and Microsoft .Net Framework.
Example: Before installing SQL Server 2008 Express SP1, first you have to install
Microsoft Windows installer 4.5 and

Microsoft.NET Framework version 3.5 SP1.

3
The SQL Server Installation Wizard provides a single feature tree to install all SQL Server
components such as:
 Database Engine
 Analysis Services
 Reporting Services
 Integration Services
 Master Data Services
 Data Quality Services
 Management tools
 Connectivity components
You can install each component individually or select a combination of the components listed
above.

Install SQL Server 2008 in Windows Server 2008


Insert the DVD or mount the iso (SQLFULL_ENU.iso), once done double click on setup.exe in case it doesn't
autorun.

If you get a requirements needed message click ok so that it can install them (updated .NET framework and
Windows Installer)
Microsoft .NET Framework 3.5 SP1 update
Accept the license agreement for the .NET update and click install

4
The actual installation seems to take a few minutes.... if it fails it will give you an error log, you can try
installing it again or read the installation issues readme.

5
Windows Installer 4.5 Update

Next you may be promted to install a hotfix (KB942288), click Ok.

if you were prompted to install the hotfix then you'll be asked to Restart, so lets do that...

after the restart and now that we've updated those two components run setup.exe again from the SQL 2008 iso (dvd).
You should see the following.

6
Planning phase

click on System Configuration Checker to check our system for any problems that may prevent SQL 2008
from installing/working.

In my case i got one warning (telling me that installing SQL server on a domain controller is not recommended)
but I choose to ignore that warning.

7
Clicking ok brings you back to the SQL 2008 main menu, here you can see many more options for your SQL
server (hardware requirements, security documentation, release notes, upgrade advisor and more).

Installation
Click on Installation in the left pane, in the new window that appears, choose the first option which is a new SQL
server stand-alone installation.

setup support rulesthis is turn will do a quick test for setup support rules,

8
click ok to continue at this point you can use the drop down menu to select a different SQL version (we dont need
to) or input your SQL Server product key, click next when done.

accept the license terms and click next

9
click install to install setup support files...

once again, I was presented with another setup support rules test result this time with two warnings, the domain
controller one (safe to ignore) and my windows firewall telling me that the appropriate ports should be opened

10
I clicked next.
Feature Selection
I chose to Select All and left the path of the install as default.

Instance Configuration

11
I left these options as default

Disk Space Requirements


The disk space requirements gave me a green ok arrow, so I clicked next to continue

Server Configuration
Note: if you need to change collation, or verify it then click on the Collation Tab.

12
Otherwise, click on Account Name to the right of SQL Server Agent and enter your the administrator/password
values

click next
Database Engine Configuration
You can adjust the user settings here depending on your security preferences
Quote
SQL Server 2008 continues the security hardening process by introducing more changes to the server and
database components. SQL Server 2008 leverages the User Account Control (UAC) found in Windows Vista
and Windows Server 2008.
The changes introduced in SQL Server 2008 further decrease the surface and attack areas for the server and its
databases by instituting a policy of “Least Privileged Authority.” This means that internal accounts are

13
protected and separated into operating system functions and SQL Server functions. These measures include:
The ability to provision one or more Windows principals into the Sysadmin server role inside SQL Server. This
option is available during SQL Server Setup.
The Surface Area Configuration (SAC) tool has been removed, and replaced by poliyc-based management and
changes in the Configuration Manager tool.
These changes will affect your security planning for SQL Server, and help you create a more complete security
profile for your system.
for the purpose of this guide, we will add the local administrator by clicking on Add Current User, if this or any
options confuse you then click on help in the bottom right corner of the installer.

For Analysis Services configuration, enter the same value (add current user, assuming you are doing this as local
administrator...)

14
for the Reporting Services configuration, I left the default value (native)

15
choose your Error and Usage reporting settings and click next

your installation Rules will get a quick check...

16
click next to see 'Ready to install' summary'

click install to start the installation...(time for lots of coffee..)

17
After dinner it was completed

one more click and then it's all completed.

18
What Can SQL do?
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views.
The foundation of every Relational Database Management System is a database object called table. Every
database consists of one or more tables, which store the database’s data/information. Each table has its own
unique name and consists of columns and rows.
The database table columns (called also table fields) have their own unique names and have a pre-defined data
types. Table columns can have various attributes defining the column functionality (the column is a primary
key, there is an index defined on the column, the column has certain default value, etc.).
While table columns describe the data types, the table rows contain the actual data for the columns

SQL DML and DDL

 SQL can be divided into two parts: The Data Manipulation Language (DML) and the Data Definition
Language (DDL).
 The query and update commands form the DML part of SQL:
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
 The DDL part of SQL permits database tables to be created or deleted. It also defines indexes (keys),
specifies links between tables, and imposes constraints between tables. The most important DDL statements
in SQL are:
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
19
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
 Creating and Deleting Databases
. Creating a Database
- When you create a database you need to use the Master database.
1. To create a database using New Database wizard:
- Right-click on Databases, and then select New Database.
- In Database name field, enter a “database name”.
- To create the database by accepting all default values, click OK; otherwise,
continue with the following optional steps.
- To change the owner name, click (…) to select another owner.

2. To create a database using “create database


statement”:
1. From the Standard bar, click “New Query”.
2. On the sql editor write “create database database_name”
3. Select the statement <create database database_name> and execute it to
create.

Example:Nowwe want to create a database called "my_db".


CREATE DATABASE my_db .This SQL statement creates my_db.

. Deleting a database
You can delete database by executing the DROP DATABASE statement.

Example: DROP DATABASE <database name>


Drop database my_db
Exercises: 1. Create a database called library.

2. Delete the database that you have already created.


 Creating, modifying and deleting Tables:
. Creating a table
20
The foundation of every Relational Database Management System is a database object called table. Every
database consists of one or more tables, which store the database’s data/information. Each table has its own
unique name and consists of columns and rows. Tables are the basic structure where data is stored in the
database. The database table columns (called also table fields) have their own unique names and have a pre-
defined data types. Table columns can have various attributes defining the column functionality (the column is
a primary key, there is an index defined on the column, the column has certain default value, etc.).

While table columns describe the data types, the table rows contain the actual data for the columns.

- When you create a table you need to use the current database.
- SQL Server databases store all of your data in tables.

The CREATE TABLE statement is used to create a table in a database.

SQL CREATE TABLE Syntax


CREATE TABLE table- name
(
column_name1 data_type (field size),column_name2(field size) data_type,column_name3 data_type(field
size),....
);
The data type specifies what type of data the column can hold.
SQL Server Data Types
Some of the common SQL data types are as follows
Data type Description
char(n) Fixed-length character string. Maximum 8,000 characters
varchar(n) Variable-length character string. Maximum 8,000 characters
varchar(max) Variable-length character string. Maximum 1,073,741,824 characters
Text Variable-length character string. Maximum 2GB of text data
Int Integer(number) data
Datetime Date & Time data types
Float Decimal types
CREATE TABLE Example
Now we want to create a table called "Employee" that contains five columns: E_Id, FirstName, LastName,
Address, and City.
CREATE TABLE Employee
(
E_Idint,

21
FirstNamevarchar(25),
LastNamevarchar(25),
Address varchar(25),
City varchar(25)
)

The E_Id column is of type int and will hold a number. The FirstName, LastName, Address, and City columns
are of type varchar with a maximum length of 25 characters.
The empty "Employee” table will now look like this:
E_Id FirstName LastName Address City

The empty table can be filled with data with the INSERT INTO statement.

Insert command
The SQL INSERT INTOstatement is used to enter or insert data in to the table.
The SQL INSERT INTO syntax has 2 main forms and the result of either of them is adding a new row into
the database table.
The first syntax form of the INSERT INTO SQL clause doesn't specify the column names where the data will
be inserted, but just their values:

INSERT INTO Table1 VALUES (value1, value2, value3…)

The second form of the SQL INSERT INTOcommand, specifies both the columns and the values to be
inserted in them:

INSERT INTO Table1 (Column1, Column2, Column3…) VALUES (Value1, Value2, Value3…)

 As you might already have guessed, the number of the columns in the second INSERT INTO syntax
form must match the number of values into the SQL statement, otherwise you will get an error.
 If we want to insert a new row into our Customers table, we are going to use one of the following 2
SQL statements:
Example
createtable customer(Fname varchar(20),Lname varchar(20),email varchar(20),DOB
datetime,phone int);

INSERT INTO Customers VALUES ('Abera', 'Solomon', 'aberas@yahoo.com’, 2/4/1968', '626 222 222')

INSERTINTO Customers (FirstName, LastName, Email, DOB, Phone)


VALUES('Abera','Solomon','aberas@yahoo.com','2/4/1986',626222222)

22
 The result of the execution of either of the 2 INSERT INTO SQL statements will be a new row added
to our Customers database table:
FirstName LastName Email DOB Phone
Abera Solomon aberas@yahoo.com 2/4/1968 626 222-2222
Selam Gobena selag@gmail.com 4/4/1974 323 455-4545
Paulos Berihun paulosb@yahoo.com 5/24/1978 416 323-3232
Jemal Seid jes@yahoo.com 20/10/1980 416 323-8888
Petros Hunachew petrh@gmail.com 1/1/1974 626 888-8888
 If you want to enter data for just a few of the table columns, you’ll have to use the second syntax form
of the SQL INSERT INTO clause, because the first form will produce an error if you haven’t supplied
values for all columns.
 To insert only the FirstName and LastName columns, execute the following SQL statement:

INSERT INTO Customers (FirstName, LastName)VALUES ('Abera', 'Solomon')

Modifying a table

You can modify the table by adding a new column and deleting a column from the table.
The type of information that you specify when you add a column is similar to the activity
that you perform when you create a table.

Adding a new column


Syntax:

- ALTER TABLE table_name ADD column_namedata typefield size

Eg. Altertable customer add address varchar(20)

Deleting a column
Syntax:

- ALTER TABLE table_nameDROP COLUMN column_name

Eg.Altertable customer dropcolumn address

23
. Deleting a Table
Deleting a table removes that table definition and all data, as well as the permission
specification for that table.
Before you delete a table, you should remove any dependencies between the table and
other objects.

Syntax: DROP TABLE table_name

Changing table name

 How you update a table name without affecting stored values in the table?
sp_RENAME'OldTable_name','Newtable_name'

Change Data Type Example


Now we want to change the data type of the column named "DateOfBirth" in the "employee" table.
We use the following SQL statement:
ALTER TABLE employee
ALTER COLUMN DateOfBirth year

Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a two-digit or four-digit
format.

. Generating Column Values


i. Identity Property

You can use the Identity property to create columns (referred to as identity columns)
that contains system generated sequential values identifying each row inserted into a
table.

Syntax: CREATE TABLE table


(
Column_name data type IDENTTY (seed, increment) NOT NULL
)

24
Example: Create table student
(
Student_idint identity (1,1) NOT NULL,
Student_name char (20)
)
Consider the following requirements for using the Identity property
. Only one identity column is allowed per table
. It must be used with integer data types.
. It cannot be updated
. It does not allow null values

Select statement
The Select statement is the most commonly used SQL command that allows you to
retrieve records from one or more tables in your database.
- The basic SELECT statement in sql has 3 clauses: SELECT, FROM and
WHERE
- The SELECT clause specifies the table columns that are retrieved.
- The FROM clause specifies the table or tables from which columns and rows are
returned.
- The WHERE clause specifies the condition restricting the query. You can restrict
the number of rows by using comparison operators, character strings, and logical
operators as search conditions.
- The WHERE clause is optional; if missing, all table rows are accessed.
Syntax of SQL SELECT Statement:
SELECT <column_list> FROM <table_name_list>< [WHERE Clause]><
[search_condition]>

 Table-name_listincludes one or more tables fromwhich the information is


retrieved.
 column_list includes one or more columns from which data is retrieved.
 The code within the brackets is optional.
Example: SELECT ID, Fname,Dname FROM STUDENT,DEPARTEMENT WHERE
Sex='Female'ANDDnumber=‘005’

25
The set clause
The set clause is used to updating values in rows of a table in a database.

SQL UPDATE Syntax


UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Example. To Update column value ofsname to ALEMAYEHU where s_id =S02
update student set sname='ALEMAYEHU’,AGE=35where s_id=’S02’

26
Before update After update
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:
DELETE FROM table_name
or
DELETE * FROM table_name
Example. Delete *from student.This statement delets all values of a table.

The SQL SELECT DISTINCT Statement


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 by removing duplicate rows
of a column
SQL SELECT DISTINCT Syntax
SELECT DISTINCT column_name(s)
FROM table_name
Example. To display distinct/different sname from table student
selectdistinct sname FROM sstudent

Snmae
1 ABEBE
2 ALEX
3 HANA
4 SELAM
5 BEKELE

Exercise
1. Create table whose name is employee with attributes like name, Id, sex,
salary,
2. Nationality and age.(Using different methods that we have seen).
3. Modify the employee table by adding a column named Qualification.
4. Modify the employee table by modifying a column named age.
5. Delete the table Employee.

27
Creating Constraints
Constraints are the preferred method of enforcing data integrity.

- You can create constraints by using the CREATE TABLE or ALTER TABLE statement.
- Constraints ensure that valid data values are entered in columns and the relationships
are maintained between tables.
You can add constraints to a table with existing data, and you can place constraints on
single or multiple columns:

. If the constraint applies to a single column, it is called a column-level constraint


. If a constraint references multiple columns, it is called a table-level constraint.

Consider the following facts when you implement or modify constraints:

i. You can create, change and drop constraints without having to drop and recreate a
table.
ii. You must build error-checking logic into your applications and transactions to test
whether a constraint has been violated.
iii. SQL Server verifies existing data when you add a constraint to a table.
iv. You must specify names for constraints when you create them, because SQL
Server provides complicated, system-generated names. Names must be unique to
the database object owner and follow the rules of SQL Server identifiers.

 Types of Constraints
- DEFAULT Constraints - CHECK Constraints
- PRIMARY KEY Constraints - UNIQUE Constraints
- FOREIGN KEY Constraints

1. DEFAULT Constraints
A default constraint enters a value in a column when one is not specified in an INSERT
statement.
Syntax: CONSTRAINT [constraint name] DEFAULT [constraint expression]

28
createtable Payroll(e_id int primarykey,ename varchar(20),sex char(1)constraint Df_sex
default'F')

2. CHECK Constraints

A check constraint restricts the data that users can enter into a particular column to
specific values.
A check constraint is a rule that identifies acceptable column values for data in a row
within a SQL Server table. A check constraint consists of a logical expression to identify
what is a valid expression.
Syntax: CONSTRAINT [constraint name] CHECK (logical expression)
Example
createtable Payroll(e_id int primary key,ename varchar(20),
salary moneyCONSTRAINT CK_Payroll_Salary CHECK (Salary < 150000.00))
or
createtable employee2(e_id intprimarykey,ename varchar(20),
salary money CHECK (Salary < 150000.00))

3. UNIQUE Constraints

A unique constraint specifies that two rows in a column cannot have the same value.

This constraint enforces entity integrity with a unique index.


Syntax: CONSTRAINT [constraint name] UNIQUE (column)
Example: createtable Payroll3(e_id intconstraint PK_epm_Id Unique(e_id),ename
varchar(20),sex char(1))
Or
createtable Payroll4(e_id intUnique,ename varchar(20),sex char(1))
4. PRIMARY KEY Constraints
A PRIMARY KEY constraint defines a primary key on a table that
uniquely identifies a row. It enforces entity integrity.
Syntax: CONSTRIANT (constraint name) PRIMARY KEY {column..}

ALTER TABLE Student ADD CONSTRAINT PK_Student PRIMARY KEY (StudentID);

Consider the following facts when you apply a PRIMARY KEY constraint:
 The values entered must be unique
 Null values are not allowed
 It creates a unique index on the specified columns.
5. FOREIGN KEY Constraints
A FOREIGN KEY constraint enforces referential integrity. The FOREGIN KEY
constraint defines a reference to a column with a PRIMARY KEY or UNIQUE
constraint in th same, or another table.
29
Syntax: CONSTRAINT [constraint name] FOREIGN KEY [column]
REFERENCES ref_table (ref_column)
This example uses a FOREIGN KEY constraint to ensure that department
identification in the student table is associated with a valid identification in
the department table.
ALTER TABLE Student ADD CONSTRAITNT FK_Student FOREIGN KEY (Dno)
REFERENCES Department (Dnumber)

Literals and data types


Literals are letters, numbers, or symbols that are used as specific values in a result set
(in output).

- Literals mean constants which are the values we write in a conventional form.
- You can include literals in the select list to make result sets more readable.

Syntax: SELECT column_name1 ‘string literal’, column_name2 ’string_literal’, … FROM


table_name

Example: SELECT firstname, lastname,’Identification number:’,employeeid FROM


employee
Output: Firstnamelastnameemployeeid
Nancy David Identification number : 1
Andrew Fuller Identification number : 2
Comparison operators
A comparison (or relational) operator is a mathematical symbol or a keyword which
is used to compare between two values.
- Comparison operators are used in conditions that compare one expression with
another. The result of a comparison can be TRUE, FALSE, or UNKNOWN.
- SQL Comparison operator is used mainly with the SELECT statement to filter data
based on specific conditions.

Comparison Description
operator
= equal to
<>, != is not equal to
< less than
> greater than
30
>= greater than or equal to
<= less than or equal to
"Equivalent to any member of" test, Equivalent to "=
In
ANY".
Not In Equivalent to "! = ANY".
All Compares a value with every value in a list
[Not] greater than or equal to x and less than or equal to
[Not] between
y.
Is [not]null Tests for nulls
Note: The != operator is converted to <> in the parser stage.

The AND & OR Operator

The AND operator displays a record if both the first condition and the second condition is true.

The OR operator displays a record if either the first condition or the second condition is true.

AND Operator Example

Employee table:

E_Id Ename Sex age Salary Deprtment


E02 Asmare M 25 15000 ICT
E03 Almaz F 23 12000 DRAFTING
E04 Bekalu M 26 18000 SURVEYING
E05 Abebe M 33 24000 ICT
E06 Begashaw M 43 12000 ICT
E07 Selam F 24 27000 SURVEYING
E08 Nardos F 27 15000 DRAFTING
E09 Zelalem M 23 15000 DRAFTING
Now we want to select only the employee whose age is greater than 25 and those salaries is below 15000
We use the following SELECT statement:

SELECT * FROM Employee WHERE age>25 and salary>15000

The result-set will look like this:

E_Id Ename Sex age salary Deprtment


E05 Abebe M 33 24000 ICT

OR Operator Example
Now we want to select only employeeswhose department is ICT or their salaries are greater than 20000
31
We use the following SELECT statement:
SELECT * FROM Employee WHERE department ='ICT' or salary > 20000
The result-set will look like this:
E_Id Ename Sex age salary Deprtment
E02 Asmare M 25 15000 ICT
E05 Abebe M 33 24000 ICT
E06 Begashaw M 43 12000 ICT
E07 Selam F 24 27000 SURVEYING

Combining AND & OR

You can also combine AND and OR (use parenthesis to form complex expressions).
Now we want to select only female DRAFTING employee or those employees whose age is grater than 30.
We use the following SELECT statement:
The result-set will look like this:

E_Id Ename Sex age salary Deprtment


E03 Almaz F 23 12000 DRAFTING
E05 Abebe M 33 24000 ICT
E06 Begashaw M 43 12000 ICT
E08 Nardos F 27 15000 DRAFTING
The ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by a specified column.
The ORDER BY keyword sort the records in ascending order by default.
If you want to sort the records in a descending order, you can use the DESC keyword.
SQL ORDER BY Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

Example
select*from emp orderby ename asc
The result-set will look like this:
E_Id Ename Sex age Salary Deprtment
E05 Abebe M 33 24000 ICT
E03 Almaz F 23 12000 DRAFTING
E02 Asmare M 25 15000 ICT
32
E06 Begashaw M 43 12000 ICT
E04 Bekalu M 26 18000 SURVEYING
E08 Nardos F 27 15000 DRAFTING
E07 Selam F 24 27000 SURVEYING
E09 Zelalem M 23 15000 DRAFTING
The result-set will look like this:
ORDER BY DESC Example
We use the following SELECT statement:
SELECT * FROM employee where department=’ICT’ORDER BY ename DESC
The result-set will look like this:

E_I Ename Sex age salary Deprtment


d
E06 Begashaw M 43 12000 ICT
E02 Asmare M 25 15000 ICT
E05 Abebe M 33 24000 ICT

The TOP Clause


The TOP clause is used to specify the number of records to return.
The TOP clause can be very useful on large tables with thousands of records. Returning a large number of
records can impact on performance.
Note: Not all database systems support the TOP clause.
SQL Server Syntax
SELECT TOP number|percentcolumn_name(s)
FROM table_name

Example
selecttop 4*from emp selecttop 4 ename from emp

Ename
E_Id Ename Sex age salary Deprtment
Asmare
E0 Asmare M 25 15000 ICT
2 Almaz
E03 Almaz F 23 12000 DRAFTING Bekalu
E04 Bekalu M 26 18000 SURVEYING Abebe
E05 Abebe M 33 24000 ICT

Now we want to select only 50% of the records in the table above.
We use the following SELECT statement:
selecttop 50percent*from emp
The result-set will look like this:
33
E_Id Ename Sex age Salary Deprtment
E02 Asmare M 25 15000 ICT
E03 Almaz F 23 12000 DRAFTING
E04 Bekalu M 26 18000 SURVEYING
E05 Abebe M 33 24000 ICT

The LIKE Operator

The LIKE operator is used to search for a specified pattern in a column.


SQL LIKE Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern

LIKE Operator Example


Now we want to select the employeeswhose ename that starts with "A" from the table above.
We use the following SELECT statement:
SELECT*FROM emp
WHERE ename LIKE'A%'
The "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
The result-set will look like this:
E_Id Ename Sex Age salary Deprtment
E02 Asmare M 25 15000 ICT
E03 Almaz F 23 12000 DRAFTING
E05 Abebe M 33 24000 ICT
Now we want to select employees whose enameends with an "e" from the "employee" table.
We use the following SELECT statement:
SELECT*FROM empWHERE ename LIKE'%e'
The result-set will look like this:
E_Id Ename Sex Age salary Deprtment
E02 Asmare M 25 15000 ICT
E05 Abebe M 33 24000 ICT

Now we want to select employees whose ename contains the pattern "ma" from employee table.
We use the following SELECT statement:
SELECT*FROM emp WHERE ename LIKE'%ma%'

The result-set will look like this:

E_Id Ename Sex age salary Deprtment

34
E02 Asmare M 25 15000 ICT
E03 Almaz F 23 12000 DRAFTING

The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax
SELECT column_name(s)
FROMtable_name
WHERE column_name IN (value1,value2,...)
Example
E_Id Ename sex age salary Deprtment
E02 Asmare M 25 15000 ICT
E03 Almaz F 23 12000 DRAFTING
E04 Bekalu M 26 18000 SURVEYING
E05 Abebe M 33 24000 ICT
E06 Begashaw M 43 12000 ICT
E07 Selam F 24 27000 SURVEYING
E08 Nardos F 27 15000 DRAFTING
E09 Zelalem M 23 15000 DRAFTING

Now we want to select employee with ename equal to "Abebe" or "Almaz" from employee table above.

We use the following SELECT statement:

SELECT*FROM emp WHERE ename IN('Abebe','Almaz')

The result-set will look like this:

E_Id Ename Sex age salary Deprtment


E03 Almaz F 23 12000 DRAFTING
E05 Abebe M 33 24000 ICT

The BETWEEN Operator

The BETWEEN operator selects a range of data between two values.


The values can be numbers, text, or dates.

35
SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2

Example

SELECT*FROM emp WHERE ename between'Abebe'and'Bekalu'

E_Id Ename Sex age salary Deprtment


E02 Asmare M 25 15000 ICT
E03 Almaz F 23 12000 DRAFTING
E04 Bekalu M 26 18000 SURVEYING
E05 Abebe M 33 24000 ICT
E06 Begashaw M 43 12000 ICT
NOT BETWEEN display the record outside the range
Example 2
SELECT*FROM emp WHERE ename not between'Abebe'and'Bekalu'
The result-set will look like this:
E_Id Ename Sex age salary Deprtment
E07 Selam F 24 27000 SURVEYING
E08 Nardos F 27 15000 DRAFTING
E09 Zelalem M 23 15000 DRAFTING

SQL Alias

You can give a table or a column another name by using an alias. 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
SELECT column_name AS alias_name
FROMtable_name
Example
select ename as'employee name'from emp

SQL aggregate Functions


36
SQL aggregate functions return a single value, calculated from values in a column.
Useful aggregate functions:
 AVG() - Returns the average value
 COUNT() - Returns the number of rows
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum

The AVG() Function


The AVG() function returns the average value of a numeric column.
SQL AVG() Syntax
SELECT AVG(column_name) FROM table_name
SQL AVG() Example
We have the following "employee" table:
E_Id Ename sex Age salary Deprtment
E02 Asmare M 25 15000 ICT
E03 Almaz F 23 12000 DRAFTING
E04 Bekalu M 26 18000 SURVEYING
E05 Abebe M 33 24000 ICT
E06 Begashaw M 43 12000 ICT
E07 Selam F 24 27000 SURVEYING
E08 Nardos F 27 15000 DRAFTING
E09 Zelalem M 23 15000 DRAFTING

Now we want to find the average value of the "employees’ salary" fields.We use the following SQL statement:
selectavg(salary) as 'average salary'from emp
The result-set will look like this:

Average salary
17250
Now we want to find employees whose salary is greater than the average salary value.
We use the following SQL statement:

SELECT eame ,salaryfrom employee WHERE salary>(SELECT AVG(salary) FROM employee)


The result-set will look like this:
Ename Salary

Bekalu 18000

37
Abbe 24000

Selam 27000

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:

SELECT COUNT(column_name) FROM table_name


Example selectcount(salary)'number of salary 'from emp
Number of employee
8

SQL COUNT(*) Syntax


The COUNT(*) function returns the number of records in a table:
SELECT COUNT(*) FROM table_name
Example.selectcount(*)from emp

No column name

8
SQL COUNT(DISTINCT column_name)
The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column:
Syntax
SELECT COUNT(DISTINCT column_name) FROM table_name
Example 1. selectcount(distinct salary)'number of unique salary 'from emp

No unique salary

Example 2.
selectcount(department)as'No of ICT employees 'from emp where department=’ICT’
No of ICT employee
3

Note:COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.
The MAX() Function
The MAX() function returns the largest value of the selected column.
SQL MAX() Syntax
SELECT MAX(column_name) FROM table_name
38
Example In above “employee" table: the maximum salary.

Largest salary
27000

The MIN() Function


The MIN() function returns the smallest value of the selected column.
SQL MIN() Syntax
SELECT MIN(column_name) FROM table_name

selectmin(salary)as'smallest salary'from employee

Smallest salary
12000

The SUM() Function


The SUM() function returns the total sum of a numeric column.
SQL SUM() Syntax
SELECT SUM(column_name) FROM table_name
Example
Now we want to find the sum of all employees" salary"
SELECT SUM(salary) AS ‘Total salary’ FROM employee
The result-set will look like this:
Total salary

138000

The Variance and Standard Deviation function

STDEVP: Returns the standard deviation for the population of all values in
expression. Stdevp ignores any NULL values.
Syntax: STDEVP( <expression> )
Example: selectVAR(Employee.Salary)fromdbo. Employee

VARP: Returns the variance for the population of all values in expression. Varp ignores
any NULL values. syntax: VARP( <expression> )
Example: selectVARP(Employee.Salary)fromdbo. Employee
The GROUP BY Statement

39
The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or
more columns.
SQL GROUP BY Syntax
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHEREcolumn_name operator value
GROUP BY column_name
Or

SELECT column_name, aggregate_function(column_name)


FROM table_name
GROUP BY column_name
Example
If we have the following "Ordesr" table:
O_Id O_Date O_Price Customer
1 20/05/2005 1000 Hassen
2 20/05/2005 1600 Nibret
3 23/05/2005 700 Hassen
4 30/05/2005 300 Hassen
5 30/05/2005 2000 Jerusalem
6 20/06/2005 100 Nibret
Now we want to find the total sum (total order) of each customer.
We will have to use the GROUP BY statement to group the customers as follows:
 SELECT Customer, SUM (OrderPrice)as'Sum O_price' FROM Orders GROUP BY Customer
The result will look like this:
Customer SUM(O_Price)

Hassen 2000

Nibret 1700

Jerusalem 2000

 SELECT Customer,SUM(O_Price)as'SUM O_price'FROM orders where


Customer='Hassen'GROUPBY Customer
The result-set will look like this:
Customer SUM(O_Price)
Hassen 2000

40
GROUP BY More Than One Column

We can also use the GROUP BY statement on more than one column, like this:

SELECT Customer,O_date,SUM(O_Price)FROM Orders GROUPBY Customer,O_date

The HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.

SQL HAVING Syntax


SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value(it is optional)
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
Example
Now we want to find if any of the customers have a total order price of less than 2000.
SELECT Customer,SUM(O_Price)as'Sum O_price'FROM Orders GROUPBY Customer
HAVINGSUM(O_Price)<2000
Or
SELECT Customer,SUM(O_Price)as'Sum O_price'FROM Orders where O_price <2000 GROUPBY
Customer HAVINGSUM(O_Price)<2000
The result-set will look like this:

Customer SUM of O_Price

Nibret 1700

We want to find if the customers Hassen orJerusalem" have a total order of more than 1500.
We add an ordinary WHERE clause to the SQL statement:
SELECT Customer,SUM(O_Price)as ‘Sum(O_price)’FROM Orders
WHERE Customer='Hassen'OR Customer='Jerusalem'
GROUPBY Customer
HAVINGSUM(O_Price)>1500

The result-set will look like this:

Customer SUM(O_Price)
Hassen 2000
Jerusalem 2000

41
The SQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.
Notice that each SELECT statement within the UNION must have the same number of columns. The columns
must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

SQL UNION Syntax


SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.

SQL UNION ALL Syntax


SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
PS: The column names in the result-set of a UNIONare always equal to the column names in the first
SELECT statement in the UNION.
Example
Look at the following tables:
Order1 order2
O_Id O_Date O_Price Customer O_Id O_Date O_Price Customer
1 20/05/2005 1000 Hassen 11 20/05/2005 1000 Habtamu
2 20/05/2005 1600 Nibret 22 20/05/2005 2600 Nigussie
3 23/05/2005 700 Hassen 33 23/05/2005 1700 Habtamu
4 30/05/2005 300 Hassen 44 30/05/2005 1300 Habtamu
5 30/05/2005 2000 Jerusalem 55 30/05/2005 22000 Jemal
6 20/06/2005 100 Nibret 66 20/06/2005 2100 Nigussie

select Customer from order1


union
select Customer from order2
Now we want to list all the differentcustomers in order andorder1 tables.
We use the following SELECT statement:
select Customer from orders
union
select Customer from order1
The result will look like this:
42
Customer
Habtamu
Hassen
Jemal
Jerusalem
Nibret
Nigussie

Note: This command cannot be used to list all orders in two tables. In the example above we have two
employees with equal names, and only one of them will be listed. The UNION command selects only distinct
values.
SQL UNION ALL Example
Now we want to list all employees in Norway and USA:
SELECT E_Name FROM order1
UNION ALL
SELECT E_Name FROM order2
Result

E_Name

Hassen
Nibret
Hassen
Hassen
Jerusalem
Nibret
Habtamu
Nigussie
Habtamu
Habtamu
Jemal
Nigussie

Combining with INTERSECT


INTERSECT returns all rows that are found in both tables.
Duplicate rows are eliminated unless ALL is specified.

43
If two table expressions are combined with the INTERSECT operator, the end result
consists of those rows that appear in the results of both table expressions.
Example: SELECT*FROM EMPLOYEE INTERSECTSELECT*FROM PROJECT;
- Just as with the UNION operator, duplicate rows are automatically removed from
the result.
Syntax:
SELECT column_name(s) FROM table_name1
intersect
SELECT column_name(s) FROM table_name2
SELECT*FROM orders INTERSECTSELECT*FROM order2;
Combining with EXCEPT

EXCEPT returns all rows those are in the result of query1 but not in the result of query2.
Again, duplicates are eliminated unless ALL is specified.
If two table expressions are combined with the EXCEPT operator, the end result consists
of only the rows that appear in the result of the first table expression but do not appear
in the result of the second.
Example: SELECT*FROMordersEXCEPTSELECT*FROMorder2
Populating a Table with Rows from Another Table

You can place the result set of any query into a new table by using the SELECT
INTOstatement.You can use the SELECT INTO statement to create a table and to insert
rows into the table in a single operation

- Use the SELECT INTO statement to populate new tables in a database with imported
data from another table.

Syntax:SELECT<select_list>INTO<new_table-name>FROM<sources_table_name>

WHERE<search_condition>

Note: - The SELECT INTO statement selects data from one table and inserts it into a
different table.
- The SELECT INTO statement is most often used to create backup copies of tables.
Example
SELECT O_ID,O_date,O_price,Customer INTO orders2
FROM order1
WHERE O_ID=55

44
Set operator and Theory

We conclude this chapter with a rather theoretical discussion of set operators. We give a
number of rules for working with multiple different set operators within one SELECT
statement. All the rules are based on general rules (laws) that apply to mathematical
operators and set theory. We define and explain each of these rules, and we use the
following symbols and definitions:

 Ti, it holds that the SELECT clauses are union compatible.


 The symbol TØ represents the empty result of a table expression.
 The symbol ∪ represents the UNION operator.
 The symbol ∩ represents the INTERSECT operator.
 The symbol – represents the EXCEPT operator.
 The symbol ∪A represents the UNION ALL operator.
 The symbol ∩A represents the INTERSECT ALL operator.
 The symbol –A represents the EXCEPT ALL operator.
 The symbol = means “is equal to.”
 The symbol ≠ means “is not always equal to.”
 The symbol θ represents a random set operator.
 The symbol Ø represents an empty result.

 All operators
ALL operator is used to select all records of a SELECT STATEMENT. It compares a value
to every value in a list or results from a query. The ALL must be preceded by the
comparison operators and evaluates to TRUE if the query returns no rows. For example,
ALL means greater than every value, means greater than the maximum value. Suppose
ALL (1, 2, 3) means greater than 3.

45
Syntax to use All operator: SELECT column_name(s)

FROM table_name

WHERE column_name =all(value1,value2,...)

Enample: SELECT LNAME, FNAME FROM EMPLOYEE

WHERE SALARY>ALL(SELECT SALARY FROM EMPLOYEE

WHERE Dnum=5);

 SOME operators
SOME operator is the same as ANY operator (SOME and ANY perform the same function).

SOME compares a value to each value in a list or results from a query and evaluates to
true if the result of an inner query contains at least one row.
SOME must match at least one row in the subquery and must be preceded by
comparison operators.
Example: SELECT ID,Fname,Lname FROM EMPLOYEE

WHERE ID =SOME(SELECT EmpID FROM DEPENDENTED

WHERE Gender='Female');
 EXISTS operator
The EXIST operator checks the existence of a result of a subquery. The
EXISTSsubquery tests whether a subquery fetches at least one row. When no data is
returned then this operator returns 'FALSE'.

- A valid EXISTSsubquery must contain an outer reference and it must be a


correlated subquery.
- You can use the EXISTS and NON EXISTS operators to determine whether data
exists in a list of values.
- Use the EXISTS and NOT EXISTS operators with correlated subqueries to restrict
the result set of an outer query to rows that satisfy the subquery.

Example: SELECT DepID ,Fname ,Gender FROM DEPENDENTED

WHEREexists(SELECT ID FROM EMPLOYEE

46
WHERE EMPLOYEE.ID =DEPENDENTED.EmpID and DEPENDENTED .Gender ='Female')
You can use the EXISTS operator with the groupbyas wel as order by clause to determine
whether data exists in a list of values.

Example: SELECT dnum,COUNT(*)'Number of employee who has dependent'FROM


EMPLOYEE

WHERE salary<3000 andexists(SELECT EmpID FROM DEPENDENTED

WHERE EMPLOYEE.ID =DEPENDENTED.EmpID

groupby EmpID)

groupby Dnum

orderby Dnum

4.3. Correlated subqueries

In a SQLdatabasequery, a correlated sub-query (also known as a synchronized


subquery) is a sub-query (a query nested inside another query) that uses values from the
outer query in its WHERE clause.
- Correlated subquery is one that is executed after the outer query is executed. So
correlated subqueries take an approach opposite to that of the normal subqueries.
- In a correlated subquery, the inner query uses information from the outer query
and executes once for every row in the outer query.
- A practical use of a correlated subquery is to transfer data from one table to
another.
Syntax for correlated subquery: selectcolumn_list from table_name a
wheresearch_condition (selectcolumn_list from table_name b
wherea.column_name_a=.column_name_b)
Example: find out the name of all EMPLOYEES who has less or equal to two dependent
using correlated subquery.

select fname from EMPLOYEE a where 2<=(selectCOUNT(*)from DEPENDENTED b

where b .EmpID=a.ID )

47
What is the difference between Windows Authentication and SQL Authentication?

SQL Authentication

SQL Authentication is the typical authentication used for various database systems,
composed of a username and a password. Obviously, an instance of SQL Server can have
multiple such user accounts (using SQL authentication) with different usernames and
passwords. In shared servers where different users should have access to different
databases, SQL authentication should be used. Also, when a client (remote computer)
connects to an instance of SQL Server on other computer than the one on which the
client is running, SQL Server authentication is needed. Even if you don't define any SQL
Server user accounts, at the time of installation a root account - sa - is added with the
password you provided. Just like any SQL Server account, this can be used to log-in
localy or remotely, however if an application is the one that does the log in, and it should
have access to only one database, it's strongly recommended that you don't use
the sa account, but create a new one with limited access. Overall, SQL authentication is
the main authentication method to be used while the one we review below - Windows
Authentication - is more of a convenience.

Windows Authentication
When you are accessing SQL Server from the same computer it is installed on, you
shouldn't be prompted to type in an username and password. And you are not, if you're
using Windows Authentication. With Windows Authentication, the SQL Server service
already knows that someone is logged in into the operating system with the correct
credentials, and it uses these credentials to allow the user into its databases. Of course,
this works as long as the client resides on the same computer as the SQL Server, or as

48
long as the connecting client matches the Windows credentials of the server. Windows
Authentication is often used as a more convenient way to log-in into a SQL Server
instance without typing a username and a password, however when more users are
envolved, or remote connections are being established with the SQL Server, SQL
authentication should be used.

Windows Authentication is trusted because the username and password are checked
with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is
the only verifier participating in the transaction.

Windows Authentication is used when your user is tied up with the Windows Domain and
you can validate the requested user against your domain controller or Active Directory.
You should choose Windows authentication if your user accounts are maintained by a
domain controller or within Active Directory and there are no firewall issues.
The main benefit of using Windows authentication is that it can be coupled with IIS
authentication so that you don't have to write any custom code. Compared to other
authentication mechanisms, Windows authentication does not pass the user credentials
over the wire. Windows authentication also provides a seamless user experience.
Therefore Windows authentication should be used wherever possible.

When you configure ASP.NET for Windows authentication, it can be coupled with IIS
authentication where IIS authenticates your application's users by using Basic
authentication, Integrated Windows authentication, Digest authentication, or Client
Certificate authentication. Both Integrated Windows authentication and Client Certificate
authentication provide strong authentication, but Integrated Windows authentication is
recommended unless you have a PKI infrastructure and your clients have certificates.

SQL Server Authentication is more storing the user information in the database and
when user returns you pick there user name and password to validate against the stored
49
information in SQL Server database. This approach is taken in the internet application
where they can store some information during the signin and validate when they return
back.

50
51

You might also like