Chapter-1-: 1.1. What Is SQL?
Chapter-1-: 1.1. What Is SQL?
In most relational databases, SQL does have the capability to function in a limited
procedural fashion, allowing the programmer to determine partially how a database
is accessed. Traditionally, SQL procedural code is used to write what are called
stored procedures, triggers, database events, or database procedures. There are
other names for these code blocks, depending on the database in use. Procedural
SQL code is generally simplistic and can sometimes allow the inclusion of basic
programming constructs such as IF statements, CASE statements, and so on.
The basics of SQL consist of a number of parts. What a simple SQL statement can do
is categorized and explained below.
Query Statements:
Querying a database is performed with a single command called the SELECT
command. The SELECT command creates queries, and has various optional clauses
that include performing functions such as filtering and sorting. Queries are used to
retrieve data from tables in a database. There are various ways in which data can be
retrieved from tables and each of these is illustrated below.
Page 1 of 22
Database II
Basic query—the most simple of queries retrieves all records from a single
table.
Filtered query—A filtered query uses a WHERE clause to include or exclude
specific records.
Sorted query—sorting uses the ORDER BY clause to retrieve records in a
specific sorted order.
Aggregated query—The GROUP BY clause allows summarizing, grouping, or
aggregating of records into summarized record sets. Typically, aggregated
queries contain fewer records than the query would produce, if the GROUP
BY clause were not used. A HAVING clause can be used to filter in, or filter
out, records in the resulting summarized aggregated record set. In other
words, the HAVING clause filters the results of the GROUP BY clause, and not
the records retrieved before aggregation.
Join query—a join query joins tables together, returning records from
multiple tables. Joins can be performed in various ways, including inner joins
and outer joins.
Nested queries—a nested query is also known as a sub-query, which is a
query contained within another query (a parent or calling query). Nesting
implies that sub-queries can be nested in multiple layers and thus a sub-
query itself can also be a calling query of another sub-query.
Composite queries—a composite query is a query that merges multiple
query results together, most often using the UNION keyword.
Page 2 of 22
Database II
Page 3 of 22
Database II
Note: Using shorter alias names can help to keep SQL code more easily readable,
particularly for programmers in the future having to make changes. Maintainable
code is less prone to error and much easier to tune properly.
1.3.2. Filtering Data with the WHERE Clause
Statement: What it does
ASELECT
filteredcr_hr,
query title
uses the WHERE
FROM clause to include, orExtracts
course
exclude, specific
course credit records.
hour and
title of all courses that have a
WHERE cr_hr
Following are=some
3; demonstrative examples: credit hour of 3.
Extracts course credit hour and
SELECT cr_hr, title FROM course
title of all courses that have a
WHERE cr_hr != 3; credit hour different from 3.
SELECT s.fname, s.lname , d .title FROM It extracts student first name, last
student s JOIN department d ON s .department =d names and their department titles
.dep_code WHERE d.faculty =’technology’ ; under technology faculty.
SELECT cr_hr, title FROM course Extracts course credit hour and
WHERE cr_hr IN (2,3,4); title from courses that have a
credit hour of 2, 3, or 4.
Page 4 of 22
Database II
SELECT cr_hr, title FROM course WHERE NOT Extracts credit hour and title of INTRODICTION
cr_hr =3 AND title LIKE ‘Introduction%'; courses having a credit hour of other than 3.
SELECT title FROM course WHERE NOT cr_hr Extracts titles of all MAIN courses having a
=3 AND category =’MAIN’ OR title credit hour of other than 3 OR it extracts course
LIKE‘Introduction%'; whose title begins with ‘Introduction’.
Page 5 of 22
Database II
SELECT cr_hr, title FROM course Same as above; but it sorts in DESCENDING by credit
ORDER BY cr_hr DESC ; hour.
If there is a ‘WHERE’ clause, the GROUP BY clause comes after it. And if there is an
‘ORDER BY’ clause, the GROUP BY clause then comes before it.
Page 6 of 22
Database II
SELECT s.program, COUNT (*) FROM student s Extract the number of students in each
GROUP BY s.program; program (Masters, Degree, and TVET)
SELECT fname,COUNT (course ), SUM (cr_hr ) Extracts first name of all students along with
FROM student JOIN enrollment ON id=st_id the total number of courses each student took
JOIN course ON enrollment.course = and also the sum of credit hours of those
course.code GROUP BY fname; courses
Note: Above the ‘HAVING’ clause is used to filter data like the ‘WHERE’ clause.
A common programming error is to get the purpose of the WHERE and HAVING
clause filters mixed up. The WHERE clause filters records as they are read (as I/O
activity takes place) from the database. The HAVING clause filters aggregated
groups, after all database I/O activity has completed. Don’t use the HAVING clause
when the WHERE clause should be used, and vice versa.
Page 7 of 22
Database II
Inner Join
An intersection between two tables using matching field values, returning records
common to both tables only.
Cross join
This is also known mathematically as a Cartesian product. A cross join merges all
records in one table with all records in another table, regardless of any matching
values.
Outer join
It returns records from two tables as with an inner join, including both the
intersection between the two tables, plus records in one table that are not in the
other table. Any missing values are typically replaced with NULL values. Outer joins
can be of the following three forms:
Left outer join—all records from the left side table plus the intersection of
the two tables. Values missing from the right side table are replaced with
NULL values.
Right outer join—all records from the right side table plus the intersection
of the two tables. Values missing from the left side table are replaced with
NULL values.
Full outer join—the intersection plus all records from the right side table not
in the left side table, in addition to all records from the left side table not in
the right side table.
Self join
A self join simply joins a table to itself, and is commonly used with a table containing
a hierarchy of records. A self join does not require any explicit syntax other than
including the same table in the FROM clause twice.
Page 8 of 22
Database II
SELECT * FROM course WHERE course.code IN Extracts course information for which
(SELECT e.course FROM enrollment e) ; students are registered.
SELECT * FROM course WHERE course.code NOT IN Extracts course information for which NO
(SELECT e.course FROM enrollment e) ; student is registered.
Page 9 of 22
Database II
In the above syntax, ‘table’ is the name of the table that you are going to insert data.
F i le d1, fi e ld2, …., fi e ldN are list of fields in the table and va lue 1, va lue 2, …., va lue N
refers to the values that you are going to insert in the corresponding fields.
Page 10 of 22
Database II
INSERT INTO student (id, fname, lname) VALUES Inserts id, first name, and last name of
(‘scr/0558/90’, ‘Adem’, ‘Kedir’) ; one student.
INSERT INTO student VALUES (‘scr/0558/90’, Same as above but the field list is not
‘Adem’, ‘Kedir’) ; listed.
Page 11 of 22
Database II
This command is used to delete records in a table, which you can set criteria for
deletion. The syntax is:
D E L E T E F R O M tb l_Na me [ W H E RE … ] ;
1.5. Transactions
A transaction allows us to make change to the data in a relational database. To save
this change, the COMMIT command is used. And if you want to remove those changes
the transaction made to the data in the database, i.e. not to save the changes, the
ROLLBACK command is used.
When you use the explicit form of transactions, you use the global Transact-SQL
variable @@error to detect if there is an error during the execution of the transaction.
Page 12 of 22
Database II
Example 1:
USE mystud;
UPDATE student SET division=’extension’ WHERE division=’weekend’
IF (@@error <> 0) ROLLBACK;
Example 2:
USE mystud;
BEGIN TRANSACTION;
DELETE FROM student WHERE department=’dep10’ AND division=’weekend’;
COMMIT TRANSACTION;
Page 13 of 22
Database II
Views are usually used by administrators to implement security, down to the record
and field levels. In other words, a view can be used to restrict specific users to access
only specific records in a table. This is because a view contains a query. That query
can have a WHERE clause filter, restricting the records returned from underlying
tables.
Views are used to increase the security of the data in the database by increasing its
confidentiality.
With views, you can create a logical grouping of the rows in a table and expose each
logical group to the user that has permission to access it.
Page 14 of 22
Database II
Examples:
Page 15 of 22
Database II
General Overview
Database engine security system is composed of two different security subsystems:
In addition to Windows user accounts and logins, there are also Windows groups
and SQL Server roles. A Windows group is a collection of Windows user accounts.
Assigning a user account membership to a group gives the user all the permissions
granted to the group. Similarly, a role is a collection of logins.
Generally, the database security system revolves around the following basic
concepts:
Authentication
Authentication is the process of validating user credentials to prevent unauthorized
users from using the system. Authentication can be checked by requesting the user
to provide information such as username and password.
To configure the authentication mode (to make it either Windows or SQL server
mode), do the following:
Page 16 of 22
Database II
Data Encryption
Data encryption is the process of scrambling information so that it is not
understandable until it is decrypted by the intended recipient. This is made with a
help of encryption/decryption software.
Authorization
Authorization is the process that is applied after the identity of a user is verified
through authentication. During this process, the system determines what resources
the particular user can use. In other words, structural and system catalog
information about a particular entity (table, row etc) is now available only to a
principal. A principal is a user or a subject that has permission to access an entity.
Change Tracking
This means that every action of unauthorized user is tracked, i.e. followed up, and
documented on the system.
Page 17 of 22
Database II
Logins can be created using the create DDL statement or using the management
studio.
The following syntax is used to create a login using the CREATE DDL command:
The above statement creates a login with the name my_pc\user1. When you
create a login from an existing windows user account, the name should be composed
of the computer name and the user account name. Above, ‘my_pc’ is the name of the
computer and user1 is the name of the user account.
NOTE: To create a login, the current account you used to log in to the system must
have been granted for the action!
To create a login using the management studio, follow the steps below:
Page 18 of 22
Database II
Therefore, system users, which are authenticated to connect to the database server
instance, must have a database user account for each database they want to use.
You can use the CREATE USER statement or the management studio to work with
database users.
The above statement creates a database user named techno_dean from the
existing Windows user account named user1 on the computer named mypc.
Each database has its own specific users. Therefore, the CREATE USER statement
must be executed once for each database where a user account should exist. Also, a
SQL Server login can have only a single corresponding database user for a given
database.
Page 19 of 22
Database II
2.6. Schema
A schema is a collection of database objects (such as tables) that is owned by a user,
and having a name.
You can work with schemas using DDL or the management studio.
Using DDL, you can create a schema and assign a view to it as follows:
The above DDL creates a schema named cs_manager and makes the database user
techno_dean the owner of the schema. Next it creates and assigns a view named
techno_faculty to the schema. Finally, it gives a SELECT authorization to another
database user named cs_department and denies an UPDATE and DELETE activity or
permission on the view.
Page 20 of 22
Database II
2.7. Roles
When several users need to perform similar activities in a particular database, you
can add a database role, which specifies a group of database users that can access
the same objects of the database. These database users can be Windows user
accounts or SQL Server logins.
Note that roles are of two types: server roles and database roles. Server roles are
assigned activities related to the server and database roles specify activities related
to databases.
sysadmin: members of this role can perform any activity in the databases
under the current database server instance
dbcreator: can create and modify databases under the database server
securityadmin: can manage LOGINS and can also manage CREATE DATABASE
permissions
db_owner: users of this role can perform almost activities in the current
database.
db_accessadmin: members of this role can add/remove other database users
db_backupoperator: users who can backup the database
On top of server roles and database roles, you can create a new database role using
the management studio as follows:
Page 21 of 22
Database II
IV) Type a name for the new database role and assign an
owner for this role
V) Then, find database users which you want to have this
role from the bottom section of the dialogue box
VI) Finally, click OK
Page 22 of 22