We will see about Sql and MS Sql Server in this post.
SQL stands for Structure Query Language. SQL Server is developed by Microsoft. Sql Server is a relational database management system (RDBMS) and also ORDBMS. It is used for the basic functions of storing, retrieving data as required by other applications. It can run on the same computer or on another computer across a network. Sql server is platform dependent and case-insensitive language.
You will find the pdf document at the end of the post.
In MS SQL Server,there are two types of databases available.
- System databases
- User Databases
System databases are created automatically when we install MS SQL Server. Following is a list of system databases −
- Master – It is a System Configuration Database.
- Model – It is used as Configuration Database for Services
- MSDB – It is used as a template for new users.
- Tempdb – It is used to provide temporary database for workable. Tempdb is always dropped & recreated every time sql restarts. It is better not to store important data in it.
- Resource – It is hidden System Configuration Database that provides system object to other databases. It was introduced in 2005 version.
- Distribution – It is used for Replication feature only.
User databases are created by users like (Admins, developers and testers who have access to create databases).
SQL data type specifies the type of data of any object. In Sql server each column, variable and statement has related data type in SQL.
SQL Server consist of six categories of data types.
Exact Numeric Data Types
|decimal||-10^38 +1||10^38 -1|
|numeric||-10^38 +1||10^38 -1|
Approximate Numeric Data Types
|float||-1.79E + 308||1.79E + 308|
|real||-3.40E + 38||3.40E + 38|
Date and Time Data Types
|datetime||Jan 1, 1753||Dec 31, 9999|
|smalldatetime||Jan 1, 1900||Jun 6, 2079|
|date||Stores date E.g May 7, 1994|
|time||Stores time like 10:15 A.M.|
Character Strings Data Types
|char||Space taken is fixed and can’t shrink or grow dynamically.|
|varchar||Dynamically the length grows or shrink as per need.|
An operator is a reserved word or a character used primarily in an SQL statement’s WHERE clause to perform different operations. Which we will see shortly.Operators are used to specify conditions in an SQL statement.
- Arithmetic operators
- Comparison operators
- Logical operators
- Operators used to negate conditions
SQL Arithmetic Operators:
Assume variable a holds 10 and variable b holds 20, then:
|+||Addition – Adds values on either side of the operator||a + b|
|–||Subtraction – Subtracts right hand operand from left hand operand||a – b|
|*||Multiplication – Multiplies values on either side of the operator||a * b|
|/||Division – Divides left hand operand by right hand operand||b / a|
|%||Modulus – Divides left hand operand by right hand operand and returns remainder||b % a|
SQL Comparison Operators:
|=||Checks whether the two operands are having equal value or not, if yes then condition becomes true.||(a = b)|
|!=||Checks whether the two operands are having equal value or not, if values are not equal then condition becomes true.||(a != b)|
|Checks whether the two operands are having equal value or not, if values are not equal then condition becomes true.||(a b)|
|>||Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.||(a > b)|
|<||Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.||(a < b)|
|>=||Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.||(a >= b)|
|<=||Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.||(a <= b)|
|!<||Checks if the value of left operand is not less than the value of right operand, if yes then condition becomes true.||(a !< b)|
|!>||Checks if the value of left operand is not greater than the value of right operand, if yes then condition becomes true.||(a !> b)|
SQL Logical Operators & Predicates:
Here is a list of all the logical operators and predicates available in SQL.
|ALL||The ALL operator is used to compare a value to all values in another value set.|
|AND||The AND operator allows the existence of multiple conditions in an SQL statement’s WHERE clause.|
|ANY||The ANY operator is used to compare a value to any applicable value in the list according to the condition.|
|BETWEEN||The BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.|
|EXISTS||The EXISTS operator is used to search for the presence of a row in a specified table that meets certain criteria.|
|IN||The IN operator is used to compare a value to a list of literal values that have been specified.|
|LIKE||The LIKE operator is used to compare a value to similar values using wildcard operators.|
|NOT||The NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.|
|OR||The OR operator is used to combine multiple conditions in an SQL statement’s WHERE clause.|
|IS NULL||The NULL operator is used to compare a value with a NULL value.|
|UNIQUE||The UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).|
[NOTE]: IN, BETWEEN & LIKE falls under predicates.
Categories of T-Sql
- Data Definition Language:
It consist of statements for object definitions.
E.g: CREATE, ALTER, DROP
- Data Manipulation Language:
It consist of statements for querying and modifying data.
E.g: SELECT, INSERT, UPDATE, DELETE
- Date Control Language:
It consist statements for security purpose and it’s mostly used by DBA.
E.g: GRANT, REVOKE, DENY
Data Definition Language
Now, before creating a table you should select a database in which you will work on. The database can either be selected from the System database like, Master, Model etc or you can create your own database.
To create the database make sure you have the admin rights for creating it & all the databases name should be unique.
Creating the Database:
Syntax: create database Database_name;
Example: create database Student;
After creating the database its time to use/select that database on which you are going to work.
Using/Selecting the Database:
Syntax: use Database_name;
Example: use Student;
In this way you will be able to work on specific database.
Now that the database is ready and in use, its time to create a new table.
Creating a Table:
Now before creating a table you should know about constraints. These constraints allow the data in your table to comply certain properties. These properties are nothing but constraints.
List of Constraints:
- Primary key: All values to be unique.
- Foreign key: Used for reference.
- Unique key: Accept first null value.
- Identity: Values are given by system.
- Not null: Does not accept null values.
- Check: Checks for the valid condition and returns true if the condition is matched.
- Default: Default value is given.
Creating Table with constraints:
create table Table_name ( variable_1 data_type constraint, ...... )
create table Product ( Sr_no int identity(100,1), //Here 100 is Starting value & 1 is the incremental value Product_id int primary key, Product_name varchar(20), // Here 20 is the length Store_id int foreign key references Stores(Store_id), //"Stores"is the another table Store_name varchar(20) not null, Quantity int check(Quantity > 10), // It checks whether the value of quantity is > 10 Rate int default 100, // The default value of rate is set to 100 )
When you want to change the data type of specific column or add a new column or delete a column, then you can use alter statement.
- alter table Table_name alter column column_name new_datatype; // Altering column data type
- alter table Table_name add column_name datatype; // Adding new column in the specified table
- alter table Table_name drop column column_name; // Dropping a column from a table
- alter table Product alter column Product_id varchar(20);
- alter table Student add Roll_no int;
- alter table Student drop column Roll_no;
Dropping a Table:
To completely delete the table records and its structure, drop statement is used.
drop table Table_name;
drop table Student;
Deleting the database from the database list.
drop database Database_name;
drop database Student;
Data Manipulation Language
Data manipulation language or DML is used to retrieve, modify, add and delete records.
DML consist of SELECT, INSERT, UPDATE, DELETE Statements. Lets see them in detail.
Insert statement is to insert records in the table. While inserting a new record in the table the definition should not be violated.
insert into table_name values(...,...,...,...);
If the values are to be inserted in particular column then it can be mentioned as follows;
insert into table_name (column_name1,column_name2) values(...,...,...,...);
The brackets for the column_names is optional and into is also optional.
insert into Student values(53,'Gaurav','BE',2016);
now, for specific columns
insert into Student (id,name) values(53,'xyz');
[NOTE] Now here onward ‘column_list’ means, list of columns like ‘column_name1, column_name2,…,column_nameN’.
Update statement is to update the existing records.
update Table_name set statement where condition;
update Student set id=55, name='Gaurav' where id=53;
The delete statement deletes the records but the structure of the table is maintained.
Unlike drop statement which removes not only records but also the structure.
delete * from Table_name; delete column_list from Table_name; delete * from view_name; // Check about Views in detail below. But its better to stay with the flow.
delete * from Student; delete year, marks from Student; delete * from Student_view;
Select statement retrieves the data from the table, view etc and displays it as a Result Table.
select column_name1, column_name2,...,Column_nameN from Table_name;
If you want to select all the records then;
select * from Table_name;
Where clause in Select statement:
If you want to apply condition in the select statement, only then where clause is used.
select column_list from Table_name where condition;
select * from Student where marks>50;
Select Into statement:
The Select Into statement selects records from one table and inserts into another table.
select column_list into new_table from Table_name1; select column_list into new_table from Table_name1 where condition; select column_list into new_table in 'file_name.mdb' from Table_name1 where condition;
select * into Student_backup from Student where marks>60; select * into Student_backup in 'backup.mdb' from Student where marks>60;
To select distinct values from a column of a table Distinct is used.
select distinct (column_name) from Table_name where condition;
select distinct (name) from Studentwhere condition;
Clause expression in select statement:
select column_list case column_name when expression1 then expression2 when expression3 then expression4 when expression5 then expression6 else expression7 end as column_name_alias from table_name;
select p_id,p_name,category_id case category_id when 1 then 'Solid' when 2 then 'Liquid' when 3 then 'Gases' else 'Unknown category' end as category_name from table_name;
Merging columns using Select statement:
Merging or concatenation can be achieved via + sign.
select column1 +' '+ column2 from Table_name;
select id +' '+ name from Student;
Selecting top or upper values:
Top is used to get the upper values from the record.
select top n column_list from Table_name; // To select top n number of records select top n% column_list from Table_name; // To select top n percent of records
select top 10 * from Student; select top 10% *from Student;
Calculations in select statement:
To make basic calculations like sum, sub, mul,div between columns.
select column1, column2, column3, (column2+column3) as column_alias from Table_name;
Here addition of two columns is performed which needs to be given a name, therefore aliasing is used.
select id, name, sem1, sem2, (sem1+sem2) as total_marks from Student;
Like clause in select statement:
Like clause is used to check character string against a pattern.
The wildcard used in like clause are:
%: Represents string of any length
_: Represents single character
^: Represents single char not in the list
–: Matches string within specified range
: Represents single character in supplied list
lets see them in detail.
select column_list from Table_name where column1 like 'Sa%'; //Finds string starting with Sa select column_list from Table_name where column1 like '%na'; //Finds string ending with na select column_list from Table_name where column1 like '[GSP]%'; select column_list from Table_name where column1 like '[G-P]%'; //Gives result starts with G and ends with P select column_list from Table_name where column1 like 'Ga_'; //Third char to be any select column_list from Table_name where column1 like '_pa'; //First char to be any select column_list from Table_name where column1 like '^a'; // Matching string beginning other than 'a'
Using AND & OR with select statement:
The AND and OR operators are used to combine multiple conditions to narrow record. These two operators are called conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the same sql statement.
select column_list from Table_name where condition AND condition; select column_list from Table_name where condition OR condition;
select * from Student where marks>50 AND subject='Maths'; select * from Student where marks>50 OR total>75;
Group by & Order by clause:
Group by clause is used with the select statement to arrange the identical records in a group. The group by clause is followed by where clause and precedes order by clause.
The order by clause is used to sort the data in ascending or descending order, by default it is ascending order.
select column_list from table_name where condition group by column_name order by column_name;
select * from Student where marks>50 group by total_sem order by name, total_sem;
Index is just like a reference which is used by the database search engine to speed up the data retrieval process.An index speeds up the Select queries and where clause, but may slow down the data input via Insert and Update statement.
Basic create index: create index index_name on tale_name; Single column index: It is created based on only one column of the table. create index index_name on table_name (column_name); Composite index: It is an index on two or more columns of the table. create index index_name on table_name (column1,column2); Unique index: Unique index does not allow duplicate data to be inserted. Preserves data integrity. create unique index index_name on table_name (column_name); Drop: To drop the index. drop index index_name;
When should indexes not to be used: [From tutorial site]
Although indexes are intended to enhance a database’s performance, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered:
- Indexes should not be used on small tables.
- Tables that have frequent, large batch update or insert operations.
- Indexes should not be used on columns that contain a high number of NULL values.
- Columns that are frequently manipulated should not be indexed.
Union combines rows in comparison joins combines columns from different sources.
Union removes duplicate rows.
select query 1 union select query 2;
select country, city from Product union select country, city from Customer;
Union all is just like union but it does not apply filter for duplicate input rows i.e union all returns a result set with duplicate rows (all rows from both the tables).
select query 1 union all select query 2;
select country, city from Product union all select country, city from Customer;
Returns only distinct rows that appear in both result sets.
select query 1 intersect select query 2;
select country, city from Product intersect select country, city from Customer;
Returns only distinct rows that appear in both result sets.
select query 1 except select query 2;
select country, city from Product except select country, city from Customer;
Views are named table expressions, whose definitions are stored in a metadata in sql server database.
Views don not persistently store data.
The definition of view is unpacked at runtime and the source objects are queried.
Creating simple view:
create view view_name as select query;
create view Student_view as select id, name from Student where marks>70;
Displaying data of created view:
select column_list from view_name;
Creating complex views:
Before going with complex views please refer to the topic of JOINS which is given below.
create view Student_view as select s.fname,s.lname,s.id,p.address from Student as s join Personal_info as p on s.fname=p.dname;
DML in Views:
insert into view_name column_list values (,,,); update view_name set expression where condition; delete column_list from view_name where condition; select column_list from view_name;
Retrieve data from two or more tables based on data relationship between the tables is called join. Well in simple words, Join is used to combine records from two or more tables in a database by using values common to each other.
Types of Joins:
- Inner Join
- Outer Join
- Left Outer Join
- Right Outer Join
- Full Join
- Self Join
- cartesian Join
Inner join is also referred as an Equijoin.
The Inner join creates a new result table by combining column values of two tables based upon the join-predicate. The query compares each row of table1 with each row of table2 to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column values for each matched pair of rows of table1 and table2 are combined into a result row.
select column_list from table1 inner join table2 on table1.common_col=table2.common_col;
select o.order_id, c.customer_name, o.order_date from Orders as o inner join Customers as c on o.customer_id=c.customer_id order by c.customer_name;
Left Outer Join:
Left outer joins returns all the values from the left table and matched values from the right table or no values are taken from right table if there is no matching predicate.
In left outer join if there is no matching records in right table, the join will still return all rows from the left table.
select column_list from table1 left outer join table2 on table1.common_col=table2.common_col;
select column_list from table1 left join table2 on table1.common_col=table2.common_col;
Right Outer Join:
Right outer joins returns all the values from the right table and matched values from the left table or no values are taken from left table if there is no matching predicate.
In right outer join if there is no matching records in left table, the join will still return all rows from the right table.
select column_list from table1 right outer join table2 on table1.common_col=table2.common_col;
select column_list from table1 right join table2 on table1.common_col=table2.common_col;
Full joins combines the results of both the left and right outer join.
Full joins contains all records from both the tables and fill in NULL vales as well.
select column_list from table1 full join table2 on table1.common_col=table2.common_col;
In self join a table is joined to itself, to compare rows in same table.
At least one alias of a table is required to differentiate between the two.
Self join creates two instances of the same table using from clause.
select column_list from table1 a self join table1 b on a.common_col=b.common_col;
Cartesian Join or Cross Join:
The cartesian join or cross join returns the cartesian product of the sets of records from the two or more joined tables. Thus, it is similar to an inner join where the join-condition always evaluates to True or where the join-condition is absent from the statement.
select table1.column1, table2.column2... from table1, table2 [, table3 ];
Returns only a part of the string.
select substring(‘Microsoft sql server’, 11, 3);
Provides metadata about the number of characters.
select len(‘string’)as length;
select len(‘MS SQL SERVER ‘)as length;
output: length 13
Provides metadata about the bytes stored in a string.
select datalength(‘string’)as length;
select datalength(‘MS SQL SERVER ‘)as length;
output: length 20
Returns a number representing the position of a string within another string.
select charindex( ‘part of string, to get its position’,’string’)as alias_name;
select charindex(‘SQL’,’MS SQL SERVER’)as result;
output: result 4
Replacing one set of characters with another set within a string.
select replace(‘string’,’part of the string’,’to be replaced with’)as alias_name;
select replace(‘MS XYL SERVER’,’XYZ’,’SQL’)as length;
output: MS SQL SERVER
Upper() & Lower():
Converts the string in upper case or lower case.
select upper(‘string’)as alias_name;
select lower(‘string’)as alias_name;
select upper(‘hello’)as up; //Output: HELLO
select lower(‘HELLO’)as low; //Output: hello
left() & Right():
Left():This function will extract characters from the left part of a given string (text) value. The given value can either be a String or a Column of a table.
left (string_value, number_of_characters);
Right():This function will extract characters from the right part of a given string (text) value. The given value can either be a String or a Column of a table.
Allows to format an input value to a character string.
Aggregate functions are
sum: Sums up the values of given column,
avg: Gives the average of given column,
min: Gives the minimum of given column,
max: Gives the maximum value of given column,
count: Counts up the values of given column.
select sum(column_name)as alias_name from table_name; select avg(column_name)as alias_name from table_name; select min(column_name)as alias_name from table_name; select max(column_name)as alias_name from table_name; select count(column_name)as alias_name from table_name;
Used defined functions:
Create Function fngetfullname ( @f_name varchar(20), @l_name varchar(20) ) Returns varrchar(50) As Begin Return (select @first_name+' '+@last_name from Student;) End
Output: select dbo.fngetfullname(f_name,l_name) as name, std from Student;
Inline Table Valued function:
create function getstudent() returns table as Begin return(select * from student;) end
Output: select * from getstudent();
Multi-statement Table valued function:
create function getmulstudent() returns @stud table ( id int, fname varchar(20), lname varchar(20) ) as Begin --Inserting data insert into @stud select s.id,s.firstname, lastname from Student as s; --Updating data update @stud set fname='kumar' where id=120; return end
Output: select * from getmulstudent();
Stored procedure is used to save time from writing same code again and again.
create procedure procedure_name as begin query end
create procedure stud1&2 as begin select * from Student1; select * from Student2; end
alter procedure procedure_name as begin query end
Creating Stored Procedure with parameters:
create procedure procedure_name parameter_list as begin query end
create procedure stud1&2 @sp_id int, @sp_rollno, as begin select * from Student1 where id=@sp_id; select * from Student2 where rollno=@sp_rollno; end
Output: stud1&2 @sp_id=123, @sp_rollno=57
drop procedure procedure_name;
drop procedure stud1&2;
Here is the link to download the whole post on SQL: SQL.pdf