SQL Server Lab Manual
SQL Server 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 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.
1
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.
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
2
- 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
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.
3
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
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.
4
Windows Installer 4.5 Update
if you were prompted to install the hotfix then you'll be asked to Restart, so lets do that...
5
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.
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)
6
but I choose to ignore that warning.
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.
7
setup support rulesthis is turn will do a quick test for setup support rules,
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.
8
accept the license terms and click next
9
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
I clicked next.
Feature Selection
I chose to Select All and left the path of the install as default.
10
Instance Configuration
I left these options as default
11
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
13
databases by instituting a policy of “Least Privileged Authority.” This means that internal accounts are
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
16
click next to see 'Ready to install' summary'
17
After dinner it was 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 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
19
ALTER DATABASE - modifies a database
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.
. Deleting a database
You can delete database by executing the DROP DATABASE statement.
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.
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:
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')
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:
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.
Deleting a column
Syntax:
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.
How you update a table name without affecting stored values in the table?
sp_RENAME'OldTable_name','Newtable_name'
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.
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.
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]>
25
Example. To Update column value ofsname to ALEMAYEHU where s_id =S02
update student set sname='ALEMAYEHU’,AGE=35where s_id=’S02’
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:
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
28
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]
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.
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
29
another table.
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 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.
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.
Employee table:
OR Operator Example
Now we want to select only employeeswhose department is ICT or their salaries are greater than 20000
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
31
E05 Abebe M 33 24000 ICT
E06 Begashaw M 43 12000 ICT
E07 Selam F 24 27000 SURVEYING
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:
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
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
32
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:
Example
selecttop 4*from emp selecttop 4 ename from emp
Now we want to select only 50% of the records in the table above.
We use the following SELECT statement:
selecttop 50percent*from emp
33
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
E04 Bekalu M 26 18000 SURVEYING
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%'
34
E_Id Ename Sex age salary Deprtment
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.
35
SQL BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
Example
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.
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:
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:
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
Smallest salary
12000
138000
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
Hassen 2000
Nibret 1700
Jerusalem 2000
40
GROUP BY More Than One Column
We can also use the GROUP BY statement on more than one column, like this:
The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.
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
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.
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
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
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
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
44
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:
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.
FROM table_name
45
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 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.
groupby EmpID)
46
groupby Dnum
orderby Dnum
where b .EmpID=a.ID )
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
47
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 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
48
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 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.
49
50