Basic Structured Queru Language
Basic Structured Queru Language
STEP 2: Double click on the setup.exe file. After a few seconds a dialog box appears:
This will disappear from the screen and then the main installation page appears:
STEP 3: Click on the Installation hyperlink on the left hand side of the screen:
STEP 4 : Click on the "New Server stand-alone installation" link on the right side of the screen:
The following dialog appears on the screen whilst the install program prepares for installation:
After a minute or so (the timing will vary according to your system), the following screen appears:
STEP 5 (optional): If any checks have failed, click on the Show details button or "View detailed report link" to find
out the cause, correct it, and then click on the Re-run button to perform the checks again.
STEP 6: Product key
If all checks have passed, click on the OK button. After a few moments, the option to select the edition and to enter
the license key (or “product key”) will appear. Note that the product key box may already be populated, depending
on which edition you have. Don’t enter the product key we’ve shown here, it won’t work on your system!:
The following screen will appear whilst Windows Installer prepares itself for the installation. This will take a short
while:
For most installations, keep the default settings. Click on the Next button.
STEP 12: Disk Space Requirements
This screen just tells you if you have sufficient disk space on the drive you’re installing to, and what’s going to be
installed where.
Click on Next.
STEP 13: Server Configuration. This step allows you to set up the service accounts that will be used to run SQL
Server. If you have created Windows NT or Active Directory accounts for use with services, use these.
If not, then just to get the installation up and working, use the built-in Network Service account for all three services
listed (this account does not require a password).
This allows SQL Server to start up after installation. However, it can be easily changed later to another account
through the Services applet (Control Panel -> Administrator Tools -> Services):
In addition, remember to change the Startup Type to Automatic, for all three services. This automatically starts the
SQL Server database engine, SQL Agent and SQL Browser services when the server is re-booted.
The first service runs the SQL Server database engines executable process. The other two services allow scheduled
jobs to run after installation (and after a re-boot), and allow the SQL Server to be found by clients on the network.
Finally, click on Next.
STEP 14: Database Engine Configuration – Account Provision.
This screen allows you to set up database engine security.
Change the Authentication Mode to Mixed Mode unless you are certain you only need Windows-only
authentication.
Many third party applications rely on SQL Server logins to operate correctly, so if you are setting up a
server for a third party application, rather than one developed in-house, enabling Mixed Mode
authentication is a good idea.
If you pick Mixed Mode security, you must also enter a password for the sysadmin account (sa).
Enter and confirm a secure password for the sa account and keep it somewhere safe.
Note that you MUST also provide a Windows NT account on the local machine as a SQL Server administrator. If
you do not want Windows system administrators to be able walk up to the box and login to SQL Server, create a
new, local, dummy Windows user and add this account instead. Otherwise, add in the local administrator account, or
your own Windows account on the domain in which the SQL Server will reside.
STEP 15: Database Engine Configuration – Data Directories. Click on the Data Directories tab.
Change the directories to specify which drives in your system will be used for the various types of database files.
Generally it’s advisable to put the User database directory and User log directory on separate physical drives for
performance, but it will depend on how Windows has been configured and how many disk drives you have
available.
If you are installing on a single drive laptop or desktop, then simply specify:
Data root directory C:\Program Files\Microsoft SQL Server
User database
C:\Data
directory
User log directory C:\Logs
Temp DB directory C:\TempDB
Temp Log
C:\TempDB
directory
Backup directory C:\Backups
Do not click on the FILESTREAM tab unless you know you need to change these options, as it is not generally
required for most installations, but can easily be changed by using sp_configure 'filestream_access_level', ''after
SQL Server has been installed.
Click on Next.
…followed by:
Check 2: Does Management Studio Work? Check Management Studio works by firing it up.
Click on NO when you see this dialog box:
Check 3: Can you run a basic query against the new SQL Server?
Check SQL Server works by running a simple query from Management Studio:
Enter the query shown below and hit F5 to run it:
- To create the database by accepting all default values, click OK; otherwise, continue with the following
optional steps.
. Deleting a database
You can delete database by executing the DROP DATABASE statement.
Example: DROP DATABASE <database name>
Exercises: 1. Create a database called library.
2. Delete the database that you have already created.
Creating, modifying and deleting Tables:
. Creating a table
- When you create a table you need to use the current database.
- SQL Server databases store all of your data in tables.
Syntax: CREATE TABLE table_name
(
<Column_Name 1> <data type> <field size> <constraints>,
<Column_Name 2> <data type> <field size> <constraints>,
. . .
<Column_Name n > <data type> <field size> <constraints>
);
. 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.
Syntax: - ALTER TABLE <table_name> ADD <column_name> <data type> <field size> <constraint>
- ALTER TABLE <table_name> DROP COLUMN <column_name>
. 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
. 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
)
Example: Create table student
(
Student_id int 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
Exercise
1. Create table whose name is employee with attributes like name, Id, sex, salary, Nationality and age.
2. Modify the employee table by adding a column named Qualification.
3. Modify the employee table by modifying a column named age.
4. Delete the table Employee.
1.4 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_list includes one or more tables from which 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'AND Dnumber=‘cou005’
1.4.1 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: Firstname lastname employeeid
Nancy David Identification number : 1
Andrew Fuller Identification number : 2
Data type is a constraint that specifies the type of data stored in a table field.
* Common examples of data type in MS-Access are:
- Auto-number, Text, Number, Date/Time, Currency, Yes/No, and so on.
* Common examples of data type in MS-SQL server are:
- Char, varchar, int, float, double, datetime, and so on.
1.4.2 Expressions
An Expression is a combination of symbols and operators that the SQL Server Database Engine evaluates to obtain
a single data value.
. Operands are values or variables, whereas operators are symbols that represent particular actions.
- Operators can be used to join two or more simple expressions into a complex expression.
. Every expression consists of at least one operand and can have one or more operators.
Example: - In the expression, SELECT ((5+5) * (5+5)), 5 is an operand, and +, * are operators.
- In database systems, you use expressions to specify which information you want to retrieve.
These types of expressions are called queries.
The INSERT statement allows the user to specify explicit attribute names that correspond to the values provided in
the INSERT command. This is useful if a relation has many attributes.
Syntax: Insert into<TABLE_NAME>(column1,column2,column3)
values('value1'<for_column 1>,'value2'<for_column 2>'value 3'<for_column 3);
- The SET clause is used to assign new values to one or more columns.
- The search condition (WHERE clause) specifies which rows in the table are to be updated. If no search
condition is specified, all rows will be updated.
Example: UPDATE PROJECT
SET PLOCATION = 'Tana beles', DNUM = 5
WHERE PNUMBER=10;
Updating a primary key value may propagate to the foreign key values of records in other relations if such a
referential triggered action is specified in the referential integrity constraints.
How you update a table name without affecting stored values in the table?
sp_RENAME 'OldTable_name','Newtable_name'
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.
1.6. Combining table Expressions
With the help of set operators, the results of individual table expressions can be combined. This type of combination
is called UNION. SQL supports other set operators besides the UNION operator.
Here is the complete list:
UNION
UNION ALL
INTERSECT
INTERSECT ALL
EXCEPT
EXCEPT ALL
1.7. Combining tables with union
The UNION operator is used to combine the result-set of two or more SELECT statements.
- Each SELECT statement within the UNION must have the same number of columns and similar data types.
- Also, the columns in each SELECT statement must be in the same order.
Syntax: SELECT <column_name_list> FROM <table_name> UNION SELECT <column_name_list>
FROM <table_name>
Example: select fname,ID from EMPLOYEE union select dname,dnumber from DEPARTEMENT
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
1.8. Rules for using UNION
The following rules must be applied to use the UNION operator:
. The SELECT clauses of all relevant table expressions must have the same number of expressions
. Each SELECT statement within the UNION must have similar data types. If this applies, the table
expressions are union compatible.
. An ORDER BY clause can be specified only after the last table expression. The sorting is performed on the
entire end result; after all intermediate results have been combined.
. The SELECT clauses should not contain DISTINCT because SQL automatically removes duplicate rows when
using UNION.
1.9. Combining with INTERSECT
INTERSECT returns all rows that are both in the result of query1 and in the result of query2. Duplicate rows are
eliminated unless ALL is specified.
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 INTERSECT SELECT * FROM PROJECT;
- Just as with the UNION operator, duplicate rows are automatically removed from the result.
1.10. 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 * FROM EMPLOYEE EXCEPT SELECT * FROM PROJECT;
Just as with the UNION operator, duplicate rows are automatically removed from the result.
1.11. Keeping duplicate rows
All previous examples made it clear that duplicate rows are automatically removed from the end result if one of the
set operators UNION, INTERSECT, or EXCEPT is used. Removing duplicate rows can be suppressed by using the ALL
version of these operators. We illustrate this with the UNION ALL operator.
If two table expressions are combined with the UNION ALL operator, the end result consists of the resulting rows
from both of the table expressions. The only difference between UNION and UNION ALL is that when you use UNION,
the duplicate rows are automatically removed, and when you use UNION ALL, they are kept.
1.12. Set operators and NULL values
SQL automatically removes duplicate rows from the result if the set operators UNION, INTERSECT, and EXCEPT are
specified. That is why the following (somewhat peculiar) SELECT statement produces only one row, even if both
individual table expressions have one row as their intermediate result:
SELECT PLAYERNO, LEAGUENO
FROM PLAYERS
WHERE PLAYERNO = 27
UNION
SELECT PLAYERNO, LEAGUENO
FROM PLAYERS
WHERE PLAYERNO = 27
having clause
Use the HAVING clause on columns or expressions to set conditions on the groups included in a result set.
The HAVING clause sets conditions on the GROUP BY clause in much the same way that the WHERE clauses
interacts with the SELECT statement.
Example: SELECT dnum ,count(*)'number of employee' FROM EMPLOYEE
WHERE exists (SELECT dname FROM DEPARTEMENT
WHERE EMPLOYEE.Dnum =DEPARTEMENT.Dnumber)
group by Dnum
having COUNT(*)>2
4.4. Correlated subqueries
In a SQL database query, 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: select column_list from table_name a
where search_condition (select column_list from table_name b
where a.column_name_a=b.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<=(select COUNT(*) from DEPENDENTED b
where b .EmpID=a.ID )