SQL Server
SQL Server
Introduction:
SQL Server is a software, developed by Microsoft, which is an RDBMS Product.
It is a Platform Dependent.
It is both GUI and command-based software.
It supports SQL (SEQUEL) language which is an IBM product.
Usage of SQL Server:
It is used to create and Maintain the Database.
It is used to Integrate the Data using SSRS.
It used to analyse the data through analysis services (SSAS).
It is used to generate the reports through Reporting services (SSRS)
SQL Server Instance
An instance is an installation of SQL Server.
An instance is an exact copy of the same software.
If we install 'n' times, then 'n' instances will be created.
There are two types of instances in SQL Server a) Default b) Named.
Only one default instance will be supported in one Server.
Multiple named instances will be supported in one Server.
Default instance will take the server name as Instance name.
Default instance service name is MSSQLSERVER.
16 instances will be supported in 2000 version.
50 instances will be supported in 2005 and later versions.
SQL Datatype:
SQL Datatype will define the type of value can be stored into the Table column.
Suppose If we want to store only integer values then we can define the datatype as Int.
SQL data types can be broadly divided into following categories.
Numeric data types such as int, tinyint, bigint, float, real etc.
Date and Time data types such as Date, Time, Datetime etc.
Character and String data types such as char, varchar, text etc.
Unicode character string data types, for example nchar, nvarchar, ntext etc.
Binary data types such as binary, varbinary etc.
Point to remember in case of assigning the Datatypes:
Not all data types are supported by every relational database vendor. For example,
Oracle database doesn’t support DATETIME and MySQL doesn’t support CLOB
data type. So while designing database schema and writing sql queries, make sure to
check if the data types are supported or not.
Every relational database vendor has it’s own maximum size limit for different data
types, you don’t need to remember the limit. Idea is to have the knowledge of what
data type to be used in a specific scenario.
SQL Numeric Data Types:
DATATY FROM TO
PE
bit 0 1
tinyint 0 255
smallint -32,768 32,767
int -2,14,74,83,648 2,14,74,83,647
bigint - 92,23,37,20,36,85,47,70,000
92,23,37,20,36,85,47,70,000
decimal 1E+38 10^38 -1
numeric 1E+38 10^38 -1
float -1.79E + 308 1.79E + 308
real -3.40E + 38 3.40E + 38
DATATYP DESCRIPTION
E
DATE Stores date in the format YYYY-MM-DD
TIME Stores time in the format HH:MI:SS
DATETIM Stores date and time information in the format YYYY-MM-DD HH:MI:SS
E
TIMESTA Stores number of seconds passed since the Unix epoch (‘1970-01-01
MP 00:00:00’ UTC)
YEAR Stores year in 2 digit or 4 digit format. Range 1901 to 2155 in 4-digit
format. Range 70 to 69, representing 1970 to 2069.
SQL Character and String Data Types:
DATATYPE DESCRIPTION
CHAR Fixed length with maximum length of 8,000 characters
VARCHAR Variable length storage with maximum length of 8,000 characters
VARCHAR(m Variable length storage with provided max characters, not supported in
ax) MySQL
TEXT Variable length storage with maximum size of 2GB data
DATATYPE DESCRIPTION
NCHAR Fixed length with maximum length of 4,000 characters
NVARCHAR Variable length storage with maximum length of 4,000 characters
NVARCHAR(m Variable length storage with provided max characters
ax)
NTEXT Variable length storage with maximum size of 1GB data
Exercises:
1) Which Version of the SQL server We are using?
4) What is the Difference between Char, Varchar and Nchar, Nvarchar Datatypes?
7) What is the difference between Float and Numeric Decimal in Sql server?
Float and Real Datatypes does not store exact values for many numbers.The
storing Values can be extremely closed.
Numeric/Decimal are fixed precision data types. It will store the values with
exact precision and scale.
If you need to store the data where small difference does not matter, then we
can use Float or Real. But if you need have an exact data then we go for
Numeric decimal.
SQL Statements:
SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.
Allows users to access data in the relational database management systems.
Allows users to describe the data.
Allows users to define the data in a database and manipulate that data.
Allows to embed within other languages using SQL modules, libraries & pre-
compilers.
Allows users to create and drop databases and tables.
Allows users to create view, stored procedure, functions in a database.
Allows users to set permissions on tables, procedures and views.
SQL Commands:
The Following are the SQL Commands Used to Interact with the Database.
1) DDL (Data Definition Language)
2) DML (Data Manipulation Language)
3) DRL (Data Retrieve Language)
4) DCL (Data Control Language)
5) TCL (Transaction Control Language)
DDL Commands:
1) Create: It is used Creates a New Table in the Database.
2) Alter: It is used to modify the existing object such as Table Structure.
3) Drop: it is used to Drop the existing object such as table, view etc.
4) Truncate: It is used to delete the data from table permanently.
DML Commands:
1) Insert: It is used to insert the records into the existing Table.
2) Update: It is used update the Whole data or selected data in a table.
3) Delete: it used to delete the completed data or selected Data from a table.
4) Merge: It is used perform any of the above operation based on the condition.
DRL Commands:
1) Select: It is used to retrieve the data from the table.
DCL Commands:
1) Grant: it gives the privileges to the user
2) Revoke: it will take back the privileges granted to the User.
TCL Commands:
1) Commit: It saves the Work done.
2) Rollback: it restores the database into original state till the last committed
transactions.
3) Save Transaction: Set the Save point within a transaction.
Table Creation:
Tables are used to store the Data in the Database.
Tables are uniquely named in the Database.
Each table contains one more Column
Emp Table Creation Structure:
CREATE TABLE emp
(
empno INT,
enameVARCHAR(10),
job VARCHAR(9),
mgr INT NULL,
hiredate DATETIME,
salNUMERIC(7,2),
comm NUMERIC(7,2) NULL,
dept INT
)
Dept Table Structure:
CREATE TABLE dept
(
deptno INT NOT NULL,
dnameVARCHAR(14),
locVARCHAR(13)
)
Update:
Syntax to update the all rows of a table
Update emp Set Comm=0
Syntax to update the specific rows of a table:
Update emp set comm=0 where sal>5000
Delete:
Syntax to delete all the from a table:
Delete from emp;
Syntax to delete selected data from a table:
Delete from emp where comm Is null;
Exercises:
1) How to rename the Table in sql server
Sql server does not have any direct statement to rename the table. However we
have the stored procedure named ‘SP_Rename’ is used to rename the table.
INSERT ALL
INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
INTO table_name(column1, column2, column_n) VALUES (expr1, expr2, expr_n)
INTO table_name (column1, column2, column_n) VALUES (expr1, expr2, expr_n)
SELECT * FROM dual;
Inserting the Data into Multiple Tables:
INSERT ALL
INTO suppliers (supplier_id, supplier_name) VALUES (30, 'Google')
INTO suppliers (supplier_id, supplier_name) VALUES (31, 'Microsoft')
INTO customers (age, name, address) VALUES (29, 'Luca Warsi', 'New York')
SELECT * FROM dual;
Multiple Records inserting in SQL Server:
Exercises on DDL:
1) Write a Query to add the column to an existing table.
2) Write a query to drop column from an existing table.
3) Write a query to rename the column from sal to salary.
4) Change the size of the datatype of the deptno column to 2.
5) Change the Datatype of the Dname to varchar
6) Increase the size of the empno to 4 from emp table.
7) Reduce the location size to 15 from Dept table.
8) Reduce the size of the job to 10 from Emp table
9) Change the datatype of the MGR to int.
10) Salary Should accept 5 integers and 2 decimals
11) Comm should accept 5 integers and 2 decimals.
SQL Operators:
An operator is a reserved word, or a character used primarily in an SQL statement's
WHERE clause to perform operation(s), such as comparisons and arithmetic operations.
These Operators are used to specify conditions in an SQL statement. The following are the
types of operators we have in sql Server.
1) Arithmetic Operator
2) Comparison Operators
3) Relational Operators
4) Logical Operators
Arithmetic Operators:
Addition(+): Adds values on the either side of the operator
Subtraction(-): Subtract Right hand Operand from left hand Operand
Multiplication(*): Multiples the Values on either side of the Operator
Division(/):Division the Left hand Operand by Right Hand operand.
%(Modulus): Divides Left hand operand by right hand operand on returns remainder.
Exercises on Arithmetic Operators:
1) Write a Query to get the Total Salary of the Employees.
2) Write a query to get the total Salary of the Employees without Commission
3) Write a query to get the Annual Salary of an employee.
4) Write a query to get the Experience of the Employee.
5) Write a query to get the experience of the employee in years.
6) List the employees whose comm is more than their salary.
7) Write a query to print the Even numbers.
8) Write a query to print the Odd Numbers.
9) I have a table with n number of records and want to load Half of the records into one
table and remaining half into another table. How could we achieve it?
Logical operators:
Logical operators combine the result of two component conditions to produce a single
result. The logical operators are
A) And b) or c) not
And operator:
Eg: select empno, ename, sal from emp where sal>=1000 and deptno=10;
Or operator:
Eg: select empno, sal, deptno from emp where sal>=1000 or deptno=10;
Not operator:
7) IN Operator: It matches the values in the list.IN condition is used to help reduce the
need to use multiple OR conditions in a SELECT, INSERT, UPDATE, or DELETE
statement. The Operator can be used on any datatype.
9) Between: Between is used to display the rows based on the range of values. The
lower limit should be declared first.
10) Like:
19) Display the details of the employees who are belongs to dept 10 and 20.
20) Display the details of employees who are not belongs to dept 10 and 20.
21) Display the Employees whose salary is more than 2000 after giving the 20%
increment.
Select * from emp where sal+(Sal*20/100)>2000
22) Display the details of the employees and their salaries and whose salary is not in
range on 1500 and 3000
23) Display the details of employees whose commission amount is greater than the salary
increased by 10%.
24) Display Empno,Ename from emp whose ename starts with M.
25) Display Empno,Ename from emp whose ename starts with M.
26) Display Empno,Ename from emp whose ename is having second letter O.
27) Display Empno,Ename from emp whose ename is not having second letter O.
28) Display the list of employees whose name start with SM.
29) Display the list of employees whose name ends with S.
30) Display the list of employees whose name not ends with S.
31) Display the list of employees whose name having length in 4 characters.
32) Display the details of the employees who joined in the feb 1981.
33) Display the details of employees who joined in the 1981
34) Display the details of employees who joined in the Jan month of every year.
35) Display the details of employees who joined in 12th of every month.
Handling Null Values:
1) The NULL is the term used to represent a missing value. A NULL value in a table is a
value in a field that appears to be blank.
2) A field with a NULL value is a field with no value. It is very important to understand
that a NULL value is different than a zero value or a field that contains spaces
3) One value is Not equal to another null
4) Null+anything is null
The following are the Null Handling functions in SQL server:
1) IsNull
2) Coalesce
3) Nullif
IsNull:
The ISNULL() function is used to replace NULL with the specified replacement
value. This function contains only two arguments.
Syntax: IsNull(Expr1,Expr2)
If Expr1 is null then Expr2 Else Expr1 end.
Coalesce:
The Coalesce() function returns the first non-null value among its arguments. This
function doesn’t limit the number of arguments, But they must all be of the same datatype.
Coalesce () function is equivalent to the following case expression.
Synatax:Coalesce(Expr1,Expr2..Exprn)
Case when Expr1 is not null then Exp1
When Expr2 is not null Then Exp2
Else Expn
NullIf:
Returns a null value if the two specified expressions are equal. NULLIF returns the
first expression if the two expressions are not equal. If the expressions are equal, NULLIF
returns a null value of the type of the first expression.
Syantax: NullIf(Expr1,expr2)
e.g.
SELECT NULLIF(‘MakeFlag’, ‘MakeFlag’)AS ‘Null if Equal’
Output : NULL
SELECT NULLIF(‘FinishedGoodsFlag’, ‘MakeFlag’)AS ‘Null if Equal’
Output:FinishedGoodsFlag
Difference between ISNULL () and Coalesce() Functions?
1) The coalesce () function is based on the ANSI SQL Standard Whereas ISNULL is a
T-SQL Function.
2) The ISNULL function contains only two arguments whereas Coalesce () function
contains multiple arguments.
3) ISNULL is a Function where as Coalesce is an Expression.
Difference between ISNULLand NULLIF:
4) ISNULL is used to replace value of expression, if it comes to NULL.
5) NULLIF returns NULL if both of the strings are equal else returns first string.
Difference between count(*) and count(column Name
Count(*) will give you the total record count irrespective of the null values whereas
Count(ColumnName) will give you the count by excluding Nulls.
Difference between count(*) and Count(1)
Count(*) will perform on all the column and rows of a table
Count(1) will perform on a single column of a table
Examples:
1) Write a query to get the total salary of the employee
2) Write a query to get percentage of commission in stake
3) Display the list of employees who are not having managers
4) Display the list of the employees who are having managers
5) Display the list of employees who is not receiving commission.
6) Display the list of employees who is receiving commission.
Set Operators:
Set operators are used to join the results of two (or more) SELECT statements. The
SET operators available in Oracle 11g are UNION, UNION ALL, INTERSECT and MINUS.
UNION:
UNION is used to combine the results of two or more Select statements. However it will
eliminate duplicate rows from its result set. In case of union, number of columns and datatype
must be same in both the tables.
First Table:
ID Name
1 krishna
2 kishore
3 murali
Second Table:
ID Name
3 murali
4 kishore
5 ramu
Union SQL Query:
Select ID,Name,Cast(Mobile as Varchar(100)) from first;
Union
Select ID,Name,Mobile from second;
Result:
ID NAME
1 Krishna
2 Kishore
3 Murali
4 Kishore
5 Ramu
UNION ALL:
This operation is similar to Union. But it also shows the duplicate rows.
First Table:
ID Name
1 Krishna
2 Kishore
3 Murali
Second Table:
ID Name
3 Murali
4 Kishore
5 Ramu
Result:
ID NAME
1 Krishna
2 Kishore
3 Murali
3 Murali
4 Kishore
5 Ramu
Intersect:
Intersect operation is used to combine two SELECT statements, but it only returns the
records which are common from both SELECT statements. In case of Intersect the number
of columns and data type must be same.
First Table:
ID Name
1 Krishna
2 Kishore
3 Murali
Second Table:
ID Name
3 Murali
4 Kishore
5 Ramu
Result:
ID NAME
3 Murali
Minus:
Minus operator displays the rows which are present in the first query but absent in the
second query, with no duplicates and data arranged in ascending order by default.
First Table:
ID Name
1 Krishna
2 Kishore
3 Murali
Second Table:
ID Name
3 Murali
4 Kishore
5 Ramu
Note:
Same number of columns must be selected by all participating SELECT statements.
Column names used in the display are taken from the first query.
Performance wise, UNION ALL shows better performance as compared to UNION
because resources are not wasted in filtering duplicates and sorting the result set.
Exercises:
1) Display the Emp details from emp Table.
2) Display the Dept details from Dept table,
3) Display the Empno, Ename, Job, Sal for all employees from employee table.
4) Display the Department Name,Loacation of all the Departments from dept table.
5) Display the Unique departments in Dept table.
6) Display the unique dept with Jobs
7) Display the Details of employees and salary increased by 15% and expressed as
Whole number and label them as a Newcolumn.in addition to this display the increase
of salary over the Previous year.
8) Display the Names of employees working as a manager and drawing salary more than
2000.
9) Display the Names of employees who are working as CLERK, Salesman or Analyst
and Drawing salary more than 2000.
10) Display the names of the employees who are working in the Company for past five
years.
11) Display the List of employees who have joined the company before 31st Jan 1981 or
30th NOV 1981.
12) Display the details of employees whose salary is between 1500 and 5000 and are
Managers.
13) Display the details of employees whose salary is more than 2000 or deptno=20.
14) Display the details of the employees belongs to either deptno 10 or 20 or Managers.
15)