Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Monday, June 8, 2020

SQL Server Functions

SELECT USER_NAME();
SELECT SYSTEM_USER;
SELECT SESSION_USER;
SELECT CURRENT_USER;
SELECT PATINDEX('%schools%', 'W3Schools.com');
SELECT QUOTENAME('abcdef');
SELECT QUOTENAME('abcdef', '()');
SELECT REPLICATE('SQL', 5);
SELECT REVERSE('SQL Tutorial');
SELECT STR(65);
SELECT ASCII('Ajeet');
SELECT CHAR(65);
SELECT UPPER('Ajeet');
SELECT LOWER('Ajeet');
SELECT SUBSTRING('SQL Tutorial', 5, 5) AS ExtractString;

Wednesday, October 2, 2019

T-SQL and SSMS

By Ajeet Kumar

WHAT IS T-SQL(Transact-SQL)

T-SQL is a Microsoft proprietary database language used for SQL Server. It is a procedural language unlike 4th generation language SQL and is used to extend the capability of the SQL. The procedural language like C provides different features control of flow of the program like loop, conditional statements etc. and T-SQL provides all such features apart from the features of SQL.We can declare variables in T-SQL, and they can be used in different blocks of T-SQL script. T-SQL is organized into blocks of codes. Each block begins and ends with BEGIN and END keywords respectively.The statements are written inside the blocks and each statement terminates with semi-colon. The variables can be declared outside or inside the block.

BEGIN
  • Declare variables
  • T-SQL statements
END

SSMS(SQL Server Management Studio)

SSMS, a client tool is used to connect with an instance of the SQL server and write T-SQL scripts. You can download SSMS separately for the SQL Server from the Microsoft download site. We can connect with more than one instance of SQL Server.

To run the SSMS, we can use the Run dialog as shown below. Type SSMS in the text box.


If the path of the execution file is properly set-up, SSMS will run and will ask for the login credentials as shown below:


You can choose the server name from the combobox or can use localhost to run the local server. The local server is denoted by period sign also.


To authenticate, we can use windows password or can use the SQL Server password.


You can use other options. Click Options button to use them.


When the login is successful, we find the SSMS interface. In the left hand side, Object Explorer window appears with all the database objects.
Explore different objects of the SQL Server to get acquainted with them.



The new connections can be established and the current connection can be disconnected as well. This is shown below.

We can create database manually without using script. Right click by selecting the Databases object as shown.



To write a query, we open code window for query by clicking New Query.



Procedural languages’ Features in T-SQL
There are some of the following procedural features of T-SQL which enables programmers to control the flow of program execution. They are as below:
  1. Break
  2. Continue
  3. While
  4. If else
  5. Return
  6. Throw
  7. Try catch
  8. Begin end
Variables in T-SQL

The concept of variable in T-SQL is about an object which can hold a single data value of a specific data type. To declare a variable, we use declare statement and to initialize value to the variable we use set statement. We can declare more than one variable in a single statement using comma separator.
The scope of variable is within the batch. We use the USE statement to activate a database. We can use SELECT @varlocal or SET @varlocal to assign a value to variable but using SET statement is recommended. Some examples are as follows:

EXAMPLE: SELECT STATEMENTS TO INITIALIZE VARIABLES

use testdb

DECLARE @var1 varchar (30);
SELECT @var1 'Ajeet Kumar';
SELECT @var1 AS 'Developer';

EXAMPLE: SET STATEMENTS TO INITIALIZE VARIABLES

Begin

       declare @number1 int;
       declare @number2 int;
       declare @result int;
       set @number1 = 200;
       set @number2 = 300;
       set @result = @number1 + @number2;
       print cast (@result asvarchar (20));

End;

EXAMPLE: IF ELSE IN T-SQL TO BRANCH THE FLOW OF PROGRAM

IF DB_ID()= 1 
PRINT N'The current database is master.';
ELSEIF DB_ID()= 2
       PRINT N 'The current database is tempdb.';
ELSEIF DB_ID()= 3
       PRINTN 'The current database is model.';
ELSEIF DB_ID()= 4
       PRINTN 'The current database is msdb.';
else
PRINT N 'The current database is testdb.';
GO

print DB_ID()

GO STATEMENT

The GO statement is used to separate one batch from another. The important point is to remember that GO statement is actually not part of T-SQL. Therefore, we don't use semicolon after GO statement. If semicolon is used after it, error will be generated.

UNDERSTANDING BEGIN END BLOCK IN SQL SERVER

The concept of BEGIN END block in SQL Server is very much similar to usage of curly braces { and } in programming languages like JAVA. The begin end block is used to declare variables and t-SQL statements. We can use nested BEGIN END block very much like nested curly braces in java.
All the statements written in a begin end block are executed successfully. In case of failure entire block is discarded. Without begin end block the following t-SQL script will be infinite loop.

EXAMPLE: WHILE IN T-SQL TO BRANCH THE FLOW OF PROGRAM

DECLARE @Iteration Integer = 0 
WHILE @Iteration <10 
BEGIN 
    SELECT FirstName, MiddleName
    FROM dbo.DimCustomer WHERE LastName = 'Adams'; 
SET @Iteration += 1 

END;
In the above example, begin end block is executed again and again. In each iteration, the value of iteration variable is increased, and the current value is passed to the conditional expression of WHILE statement. Without begin end block, while block will have SELECT statement to execute for infinite times. The SET statement never will be executed.

SCHEMA

Schema is adatabase object which is owned by a database user. Schema is an independent entity in SQL server. It means that a user can be authorized for a schema and the rights can be revoked as well. The ownership of schema is transferable as well as distributable. A schema can be owned by more than one user at the same time. Schemas can be thought as namespaces or containers which contain database objects. It means that database objects can be moved into a schema and can be removed from a schema. Schemas provide security features to the database objects and this is the primary importance of schema. We cannot access database objects of a schema unless we are authorized for the schema of the objects. In SQL server database, there are two types of schemas.
  • In-built schemas and
  • User-defined schemas
The in-built schemas in SQL Server are SYS . We can create user defined schema as well. A database can have more than one schema. Basically, schema is used to partition the database objects into different namespaces. Schemas provide security to the database and in the object explorer, they are under the Security.

Each schema object has a unique name and schema id. Creating a schema is very easy. We use the CREATE SCHEMA <schema name> to create a schema. We also can provide the owner name to a schema.

CREATE SCHEMA <schema name> AUTHORIZATION <owner name>
We cannot delete a schema if it contains any database object.
Remark: before 2005, schema was tied with the owner and deleting owner led to deletion of schema as well. The database objects owner and database user were same. Now schema is independent of user, group or role.

We can query the SYS schema as follows:
  • select*from sys.all_objects
  • select*from sys.schemas
CREATESCHEMAMySchema AUTHORIZATION Ajeet
CREATETABLEMobiles (ModelIDint, Priceint, Modelvarchar(20)) 
GRANTSELECTONSCHEMA::MySchemaTOTom
    DENY SELECTONSCHEMA::MySchemaTOJohn; 
GO 

STORED PROCEDURE

Static or Embedded SQL are SQL statements in an application that do not change at runtime and, therefore, can be hard coded into the application. Dynamic SQL is SQL statements that are constructed at run time; for example, the application may allow users to enter their own queries.
Stored procedure is a database object like table, views, queries etc.
Stored procedure is basically a SQL script which is stored in a database server. Before executing the stored procedure, the database engine creates an execution plan and the plan is stored in plan cache. The cached plan is reused in consequent executions.
We know that querying a database tables is one of the most important operations. No matter whether you have a desktop application or web-based application, you may require displaying data, storing and updating data in the tables of the database. The stored procedures facilitate the dynamic approach to carry out these operations.
Stored procedures the database objects like tables, queries, views etc. They are SQL scripts and can be executed with or without parameters. They can use input parameters which are consumed/used the stored procedures and may return output parameters which can be used later.
The client application gives the input parameter to the stored procedure and the stored procedure in turn returns data in following three ways:

  1. Output parameter
  2. Return statement
  3. Select statement
When a stored procedure is created in the SQL Server management studio (SSMS), it appears in the Object Explorer pane.
It is a good practice to qualify the schema in the stored procedure during its creation.
The syntax of stored procedure
The stored procedure can be used to create a database object e.g. table but creating a view or trigger or another stored procedure is not allowed in the stored procedure.

BODY of SP
You can declare variable inside the body of stored procedure. The declaration of variable begins with @ symbol followed by datatype. Multiple variables can be declared in a single line using comma delimiter.
Initialization of the variable is done using set keyword in the assignment statement.
Output parameter is used in the stored procedure parameter. Output keyword is used after the datatype of the parameterized variable. The output parameter is assigned value inside the body of the stored procedure. To get the values of the output parameter during EXEC statement, we should declare the variables for the output parameters with compatible datatype before the EXEC statement. The order of the output parameters matters in the exec statement.

DYNAMIC SQL

Dynamic SQL is a technique of writing SQL query which includes one or more variables in the SQL query and the values of the variables are decided at the run-time on the fly during execution.
To write a dynamic SQL, we use parameterized stored procedure. Each variable in a stored procedure is defined which begins with @ symbol. In SQL server, we write a stored procedure as follows:

CREATEPROCEDUREdbo.uspGetModel @modelvarchar(75)
AS
BEGIN
SELECT * FROMPerson.MobilesWHEREModel= @model
END
GO

The parameters are written just after the name of the stored procedure and datatype of each parameter is written after it.

EXECUTION OF SP
Executing SQL Stored Procedure from Another Stored Procedure

TYPES OF SP
  1. User Defined Stored procedure: The user defined stored procedures are created by users and stored in the current database.
  2. System Stored Procedure: The system stored procedures have names prefixed with sp_. They are used to manage SQL Server administrative tasks. The system stored procedures are stored in the master and MSDB databases.
  3. Temporary Stored procedures: The temporary stored procedures’ names are prefixed with the # symbol. Temporary stored procedures are stored in the TEMPDB databases. These temporary procedures are automatically dropped when the connection terminates between client and server.
  4. Remote Stored Procedures: The remote stored procedures are created and stored in remote server databases. These remote procedures can be accessed by the users who have the appropriate permission
  5. Extended Stored Procedures: These are Dynamic-link libraries (DLL's) that are executed outside the SQL Server environment. They are identified by the prefix xp_

ADVANTAGES OF SP
  • 1.       The most important advantage of the stored procedure is this that it promotes code re-usability.
  • 2.       The code maintenance is better by using stored procedures. We can encapsulate the business logic inside the stored procedures and can change when the business requirement changes.
  • 3.       The stored procedure can be encrypted and hence it provides security of data. Only those who are authorized to execute the stored procedures can execute them.
  • 4.       The stored procedure is stored at appropriate server database in secure manner. They reduce unnecessary network traffic and boost the performance of application for which the stored procedure and database is being used.
  • 5.       Execution plans can be reused, staying cached in SQL Server's memory, reducing server overhead.
DATABASE PRINCIPALS
The SQL Server provides a software layer which deals with security of the SQL Server. The database and the server are two major units in the SQL server and the security is provided at these layers in using principals. PRINCIPALS are the individuals, groups, and processes which are granted access to SQL Server. SECURABLES are the server, database, and objects the database contains.
The SQL server SA login is a server level principal. The default database of SA is master.

Continued... 






Friday, June 7, 2019

SQL- Query

EXAMPLE – 01 SELECT ALL FIELDS USING WILDCARD * (MENTALLY READ * AS ‘ALL FIELDS’)

SELECT *
FROM Mobiles;

The merits/demerits of wildcard * are as follow:
1.       It works even if the field names are changed
2.       It works even if any field is deleted
3.       It works even if a new field is added

EXAMPLE – 02 SELECT ALL FIELDS BY MENTIONING THEM

SELECT ID, Region, Brand, Color, Units, Price

FROM Mobiles;

EXAMPLE – 03 SELECT ONLY DESIRED FIELDS
SELECT Region, Brand, Units, Price
FROM Mobiles;

EXAMPLE – 04 REORDER THE FIELDS

SELECT Brand, Color, Region, Price, Units
FROM Mobiles;

EXAMPLE – 05 NOT DISTINCT VALUES OF FIELD WITHOUT DISTINCT KEYWORD

SELECT Region
FROM Mobiles;

EXAMPLE – 06 SORT FIELD USING ORDER BY CLAUSE

SELECT Region
FROM Mobiles
ORDER BY Region;

EXAMPLE – 07 DISTINCT VALUES OF FIELD

SELECT DISTINCT Region
FROM Mobiles
ORDER BY Region;

EXAMPLE – 08 DISTINCT RECORDS USING DISTINCTROW KEYWORD

SELECT DISTINCTROW Region
FROM Mobiles
ORDER BY Region;

EXAMPLE – 09 REPEATING THE FIELDS DOES NOT THROW ERROR
SELECT Brand, Brand, Region, Price, Units, Units
FROM Mobiles;

REMARKS: The output will contain another label for duplicate fields.




EXAMPLE – 10 CALCULATED FIELDS
SELECT Brand, Region, Price, Units, Price*Units
FROM Mobiles;

EXAMPLE – 11 MAKING SENSE BY RELABELING FIELDS USING AS KEYWORD
SELECT Brand, Region As Area, Price, Units, Price*Units As Revenue
FROM Mobiles;

EXAMPLE – 12 RELABELING FIELD WITH SPACE BY WRITING INSIDE []
SELECT Brand, Region, Price, Units, Price*Units As [Total Revenue]
FROM Mobiles;

EXAMPLE – 13 CONSTANT OR EXPRESSION AS FIELDS
SELECT Brand, Region, Price, Units,  2016 AS YEAR, Price*1.2 As [Price After Rise by 20%]
FROM Mobiles;

EXAMPLE – 14 RENAME FIELD TO AVOID CIRCULAR REFERENCE
SELECT Brand, Region, Price*1.2 AS PRICE, Units
FROM Mobiles;

Note: The above query throws error as shown below:

SELECT Brand, Region, Price*1.2 AS NEWPRICE, Units
FROM Mobiles;

WHERE CLAUSE TO SUBSET RECORDS
Filter recordset using various comparison operators such as =, >, >=,<,<=,<>, like, in, is null, is not null, between and etc.

EXAMPLE – 15 SUBSETTING RECORDSET USING WHERE CLAUSE
SELECT Brand, Region, Price, Units, Price*Units As [Total Revenue]
FROM Mobiles
WHERE Region='South';

REMARK: If you copy-paste code in Access SQL code window, note that the quote character is correct. If the quote-character is not proper, it will throw error as shown below. In fact, it is not an error but the query is converted into parametric query. The ‘South’ becomes a parameter or variable which value is assigned to Region field when user enters a value:



EXAMPLE – 16 FILTERING RECORDSET USING WHERE CLAUSE
SELECT Brand, Region, Price, Units, Price*Units As [Total Revenue]
FROM Mobiles
WHERE Region=’south’;

EXAMPLE – 17 FILTERING RECORDSET USING WHERE CLAUSE
SELECT Brand, Region, Price, Units, Price*Units As [Total Revenue]
FROM Mobiles
WHERE Region=’SOUTH’;

EXAMPLE – 18 PARAMETRIC QUERY
SELECT Brand, Region, Price, Units, Price*Units As [Total Revenue]
FROM Mobiles
WHERE Region= [Enter the Region];

EXAMPLE – 19 FILTERING RECORDSET USING WHERE CLAUSE
SELECT Brand, Region, Price, Units
FROM Mobiles
WHERE Region=’South’ OR Region=’WEST’ OR Region=’NORTH’;

EXAMPLE – 20 FILTERING RECORDSET USING IN OPERATOR
SELECT Brand, Region, Price, Units
FROM Mobiles
WHERE Region IN (’South’,’NORTH’,’WEST’);

EXAMPLE – 21 FILTERING RECORDSET USING IN OPERATOR
SELECT Region, Brand, Price, Units
FROM Mobiles
WHERE Region IN (’South’,’NORTH’,’WEST’);

EXAMPLE – 22 FILTERING RECORDSET USING COMPARISON OPERATOR =
SELECT Brand, Region, Price, Units
FROM Mobiles
WHERE Price = 20000;

EXAMPLE – 23 FILTERING RECORDSET USING COMPARISON OPERATOR <
SELECT Brand, Region, Price, Units, Price*Units As [Total Revenue]
FROM Mobiles
WHERE Price < 20000;

EXAMPLE – 24 FILTERING RECORDSET USING COMPARISON OPERATOR <=
SELECT Brand, Region, Price, Units
FROM Mobiles
WHERE Price <= 20000;

EXAMPLE – 25 FILTERING RECORDSET USING COMPARISON OPERATOR >=
SELECT Brand, Region, Price, Units
FROM Mobiles
WHERE Price >= 20000;

EXAMPLE – 26 FILTERING RECORDSET USING COMPARISON OPERATOR <>
SELECT Brand, Region, Price, Units
FROM Mobiles
WHERE Price <> 20000;

EXAMPLE – 27 FILTERING RECORDSET USING BETWEEN AND OPERATOR
SELECT Brand, Region, Price, Units, Price*Units As [Total Revenue]
FROM Mobiles
WHERE Price BETWEEN 20000 AND 30000;

EXAMPLE – 28 FILTERING RECORDSET USING WHERE CLAUSE
SELECT Brand, Region, Price, Units
FROM Mobiles
WHERE COLOR IS NULL;

EXAMPLE – 29 FILTERING RECORDSET USING WHERE CLAUSE
SELECT Brand, Region, Price, Units
FROM Mobiles
WHERE COLOR IS NOT NULL;

EXAMPLE – 30 FILTERING RECORDSET USING WHERE CLAUSE
SELECT Brand, Region,Color, Price, Units
FROM Mobiles
WHERE COLOR LIKE "Bl*"

EXAMPLE – 31 FILTERING RECORDSET USING WHERE CLAUSE
SELECT Brand, Region, Color, Price, Units
FROM Mobiles
WHERE COLOR NOT LIKE "Bl*"
EXAMPLE – 32 FILTERING RECORDSET USING WHERE CLAUSE
Brand name begins with either D or E or H
SELECT Brand, Region, Color, Price, Units
FROM Mobiles
WHERE Brand LIKE "[d-h]*"

UNDERSTANDING GROUP BY CLAUSE
SELECT Region, Brand, Color
FROM Mobiles
GROUP BY Region, Brand;


The question is why does the above query throw error?
Answer: When the records are grouped using Region and Brand, the individual existence of Color is lost. For example, if the Mobile table has 100 records and after grouping using Region and Brand, the records are reduced to 70 (say), the individual 100 values of Color can no longer exists. Either we get the aggregated result of color and in this case we must include the COLOR field also in the GROUP BY CLAUSE or we should apply some aggregate function on COLOR if COLOR is not included in the GROUP BY clause. As a rule, whenever you include a column in table, it must exist in the GROUP BY clause or it must be argument of any aggregate function. This is shown in below query:
SELECT Region, Brand, Count(Color) As [Color Count]
FROM Mobiles


GROUP BY Region, Brand;
ANOTHER EXAMPLE
SELECT *
FROM Mobiles
GROUP BY Region, Brand;


Even if you include all fields in GROUP BY Clause, it will throw error. The explanation is as given above.
SELECT *
FROM Mobiles
GROUP BY ID, Region, Brand, Color, Price, units;



When GROUP BY clause is used, SELECT clause should have an aggregate function or one or more GROUP BY variables or a combination of both. For example,
SELECT Count(*) As [Region Wise Record Counts]
FROM Mobiles
GROUP BY Region;


You can also write
SELECT Region, Count(*) As [Region Wise Record Counts]
FROM Mobiles
GROUP BY Region;



You can apply projection on grouped records:
SELECT Region
FROM Mobiles
GROUP BY Region, Brand;
But below is incorrect:
SELECT Color
FROM Mobiles
GROUP BY Region, Brand;


But below is CORRECT:
SELECT COUNT(Color)
FROM Mobiles
GROUP BY Region, Brand;
SELECT Variable must be part of GROUP BY variable. The following query will return error:


SELECT Region
FROM Mobiles
GROUP BY Brand, Color;
The corrected query is
SELECT Region
FROM Mobiles
GROUP BY Region, Brand, Color;
The following query has error:
SELECT count(*) "Total Records"
FROM Mobiles;



The corrected query is
SELECT count(*) As "Total Records"
FROM Mobiles;
To avoid double quotes in label, modify the query as follows:
SELECT count(*) as [Total Records]
FROM Mobiles;

The same output is possible using following query as well:
SELECT count([ID]) as [Total Records]
FROM Mobiles;

To find out the duplicate records
SELECT Region, Brand, Color, Units, Price
FROM Mobiles
GROUP BY Region, Brand, Color, Units, Price
HAVING COUNT(*)>1;



SELECT Mobiles.Units, [Units]/(SELECT Sum(Units) FROM Mobiles) AS [% Units]
FROM Mobiles;

SELECT Mobiles.Units, [Price]*[Units] As [Calculated Revenue]
FROM Mobiles;

SELECT SUM( [Price]*[Units] ) As [Sum of Calculated Revenue]
FROM Mobiles;

Single Level Grouping:
SELECT Region, SUM( [Price]*[Units] ) As [Region Wise Revenue]
FROM Mobiles
GROUP BY Region;

Multi Level Grouping:
SELECT Region, Brand, SUM( [Price]*[Units] ) As [Region Brand Wise Revenue]
FROM Mobiles
GROUP BY Region, Brand;

The following is correct query but not meaningful report is generated.
SELECT SUM( [Price]*[Units] ) As [Region Brand Wise Revenue]
FROM Mobiles
GROUP BY Region, Brand;
TOP N QUERIES
To find out the top 5 sales revenue(Incorrect):
SELECT TOP 5 Region, Brand , SUM( [Price]*[Units] ) As [Top Revenue]
FROM Mobiles
GROUP BY Region, Brand;
To find out the top 5 sales revenue(Correct):
SELECT TOP 5 Region, Brand , SUM( [Price]*[Units] ) As [Top Revenue]
FROM Mobiles
GROUP BY Region, Brand
ORDER BY SUM( [Price]*[Units] ) DESC;

DOMAIN FUNCTIONS
1.       Find total records in Mobiles table
SELECT DCOUNT("[ID]","MOBILES") AS [TOTAL RECORDS]
2.       Find total records of ACER brand mobiles in Mobiles table
SELECT DLOOKUP("[ID]","MOBILES","[BRAND]='ACER'")
3.       Find brand name which ID is 77 in Mobiles table
SELECT DLOOKUP("[BRAND]","MOBILES","[ID]=77")
4.       Find average price of mobiles of all brands
SELECT DAVG("[PRICE]","MOBILES")
5.       Find average price of mobiles of ACER brand
SELECT DAVG("[PRICE]","MOBILES", "[BRAND]='ACER'")
6.       Find total price of mobiles of ACER brand
SELECT DSUM("[PRICE]","MOBILES", "[BRAND]='ACER'")
7.       Find total revenue from mobiles of ACER brand SELECT DSum("[PRICE]*[UNITS]","MOBILES","[BRAND]='ACER'") AS [ACER TOTAL REVENUE];
8.       Find minimum price of Acer mobiles
SELECT DMIN("[PRICE]","MOBILES", "[BRAND]='ACER'")
9.       Find maximum price of Acer mobiles
SELECT DMAX("[PRICE]","MOBILES", "[BRAND]='ACER'")
10.   Find record ID of Acer mobiles which appears first time in the table
SELECT DFIRST("[ID]","MOBILES", "[BRAND]='ACER'")
11.   Find record ID of Acer mobiles which appears last time in the table
SELECT DLAST("[ID]","MOBILES", "[BRAND]='ACER'")
12.   Find variance of units sold of Acer mobiles
SELECT DVAR("[UNITS]","MOBILES", "[BRAND]='ACER'")
13.   Find number of units sold of Acer mobiles which are sold at more than 30000
SELECT DCOUNT("[ID]","MOBILES", "[PRICE]>30000")
14.   Find number of units sold of Acer mobiles which are sold between 30000 and 40000
SELECT DCOUNT("[ID]","MOBILES", "[PRICE] BETWEEN 30000 AND 40000")
15.   SELECT DCOUNT("[SALE]","TABLE1","[DATES]>#1/1/2016#") AS [TOTAL SALES AFTER JAN1]

Remarks: Note that all the Domain functions arguments are written inside quotes.



Hot Topics