Exam Note SQL
Exam Note SQL
The SQL Server ISNULL () function replaces NULL with a specified value. The following shows the syntax of the ISNULL
() function: ISNULL (expression, replacement)
COALESCE ()
The SQL Server COALESCE expression accepts a number of arguments, evaluates them in sequence, and returns the
first non-null argument. The following illustrates the syntax of the COALESCE expression:
CASE ()
The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else
statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the
value in the ELSE clause. If there is no ELSE part and no conditions are true, it returns NULL. The CASE expression has
two formats: simple CASE expression and searched CASE expression.
SELECT
CASE order_status
WHEN 1 THEN 'Pending’
WHEN 2 THEN 'Processing’
WHEN 3 THEN 'Rejected’
WHEN 4 THEN 'Completed’
END AS order_status,
COUNT(order_id) order_count
FROM orders
WHERE YEAR (order_date) = 2018
GROUP BY order_status;
SELECT
SUM(CASE WHEN order_status = 1 THEN 1 ELSE 0 END) AS 'Pending’,
SUM(CASE WHEN order_status = 2 THEN 1 ELSE 0 END) AS 'Processing’,
SUM(CASE WHEN order_status = 3 THEN 1 ELSE 0 END) AS 'Rejected’,
SUM(CASE WHEN order_status = 4 THEN 1 ELSE 0 END) AS 'Completed’,
COUNT(*) AS 'Total'
FROM Orders
WHERE YEAR(order_date) = 2018;
UNION vs JOIN
The join such as INNER JOIN or LEFT JOIN combines
columns from two tables while the UNION
combines rows from two queries. In other words, join
appends the result sets horizontally while union appends
the result set vertically. The following picture illustrates
the main difference between UNION and JOIN:
SELECT
first_name,
last_name
FROM staffs
UNION
SELECT
first_name,
last_name
FROM customers;
SELECT City
FROM Customers
UNION ALL
SELECT City
FROM Suppliers
ORDER BY City;
INTERSECT
The SQL Server INTERSECT combines result sets of two or more queries and returns distinct rows that are
output by both queries.
Similar to the UNION operator, the queries in the
syntax above must conform to the following rules:
Both queries must have the same number and
order of columns.
The data type of the corresponding columns
must be the same or compatible.
The following picture illustrates the INTERSECT
operation:
In this illustration, we had two result sets T1 and T2:
T1 result set includes 1, 2, and 3.
T2 result set includes 2, 3, and 4.
The intersection of T1 and T2 result sets returns the distinct rows which are 2 and 3.
Example-
SELECT city
FROM customers
INTERSECT
SELECT city
FROM stores
ORDER BY city;
The first query finds all cities of the customers and the second query finds the cities of the stores. The whole
query, which uses INTERSECT, returns the common cities of customers and stores, which are the cities
output by both input queries.
EXCEPT
The EXCEPT operator in SQL is used to retrieve all the
unique records from the left operand (query), except the
records that are present in the result set of the right operand
(query). In other words, this operator compares the distinct
values of the left query with the result set of the right query.
If a value from the left query is found in the result set of the
right query, it is excluded from the final result. For better
understanding consider two tables with records as shown in
the image −
If we perform the EXCEPT operator on the above two tables to retrieve the names, it will display the distinct
records only from the first table which are not in common with the records of the second table.
Here, "Dev" is common in both tables. So, the EXECPT operator will eliminate it and retrieves only "Sara" and
"Jay" as output.
Example-
SELECT product_id
FROM products
EXCEPT
SELECT product_id
FROM order_items
ORDER BY product_id
STRING
MS SQL Server String functions can be applied on string value or will return string value or numeric data.
Following is the list of String functions with examples:
CHAIRINDEX () LEN ()
Search for "t" in string "Customer", and return position: Return the length of a string:
LEFT () RIGHT ()
Extract 3 characters from a string (starting from left): Extract 3 characters from a string (starting from right):
Input SELECT LEFT('SQL Tutorial', 3) AS ExtractString; Input SELECT LEFT('SQL Tutorial', 3) AS ExtractString;
Output SQL Output ial
SUBSTRING ()
Extract 3 characters from a string, starting in position 1:
LOWER () UPPER ()
Convert the text to lower-case: Convert the text to upper-case:
Input SELECT LOWER('SQL Tutorial is FUN!'); Input SELECT LOWER('SQL Tutorial is FUN!');
Output sql tutorial is fun! Output SQL TUTORIAL IS FUN!
LTRIM() RTRIM()
Remove leading spaces from a string: Remove leading spaces from a string:
Input SELECT LTRIM(' SQL Tutorial') AS LeftTrimmedString; Input SELECT LTRIM('SQL Tutorial ') AS RightTrimmedString;
Output SQL Tutorial Output SQL Tutorial
REPLACE()
REVERSE()
Replace "T" with "M":
Reverse a string:
Input SELECT REVERSE('SQL Tutorial');
Input SELECT REPLACE('SQL Tutorial', 'T', 'M');
Output lairotuT LQS
Output SQL MuMorial
STUFF()
STR()
Delete 3 characters from a string, starting in position 1, and then
Return a number as a string:
insert "HTML" in position 1:
Input SELECT STR(185);
Input SELECT STUFF('SQL Tutorial', 1, 3, 'HTML');
Output 185
Output HTML Tutorial
PATINDEX()
QUOTENAME() Return the position of a pattern in a string:
Return a Unicode string with bracket delimiters (default): Input SELECT PATINDEX('%schools%', 'W3Schools.com');
Input SELECT QUOTENAME('abcdef'); Output 3
Output [abcdef]
FORMAT()
Format a date:
Input
DECLARE @d DATETIME = '12/01/2018'; CONCAT()
SELECT FORMAT (@d, 'd', 'en-US') AS 'US English Result', Add two strings together:
FORMAT (@d, 'd', 'no') AS 'Norwegian Result', Input SELECT CONCAT('W3Schools', '.com');
FORMAT (@d, 'd', 'zu') AS 'Zulu Result'; Output W3Schools.com
Output
US English Result Norwegian Result Zulu Result
12/1/2018 01.12.2018 12/1/2018
DATE
GETDATE() DATEADD()
Return the current database system date and time: Add one year to a date, then return the date:
Input SELECT GETDATE(); Input SELECT DATEADD(year, 1, '2017/08/25') AS DateAdd;
Output 2024-11-26 23:47:55.177 Output 2018-08-25 00:00:00.000
DATEPART() DATEIF()
Return a specified part of a date: Return the difference between two date values, in years:
Input SELECT DATEPART(year, '2017/08/25') AS DatePartInt; Input SELECT DATEDIFF(year, '2017/08/25', '2011/08/25') AS DateDiff;
Output 2017 Output -6
CONVERT()
It will display the date and time in different formats.
Example: The following queries will return the date and time
in different format in MS SQL Server.
SELECT CONVERT(VARCHAR(19),GETDATE())
SELECT CONVERT(VARCHAR(10),GETDATE(),10)
SELECT CONVERT(VARCHAR(10),GETDATE(),110)
AGGREGATE
An aggregate function performs a calculation one or more values and returns a single value. The aggregate
function is often used with the GROUP BY clause and HAVING clause of the SELECT statement.
AVG()
The following statement use the AVG() function to return the average list price of all products in the products
table:
First, the ROUND function returns the rounded average list price. And then the CAST function converts the
result to a decimal number with two decimal places.
COUNT()
The following statement uses the COUNT() function to return the number of products whose price is greater
than 500:
In this example:
First, the WHERE clause gets products whose list price is greater than 500.
Second, the COUNT function returns the number of products with list prices greater than 500.
MAX()
The following statement uses the MAX() function to return the highest list price of all products:
MIN()
Similarly, the following statement uses the MIN() function to return the lowest list price of all products:
SELECT MIN(list_price) max_list_price
FROM products
SUM()
The following statement uses the SUM() function to calculate the total stock by product id in all warehouses:
SELECT
product_id,
SUM(quantity) stock_count
FROM stocks
GROUP BY product_id
ORDER BY stock_count DESC
The % (percent) wildcard- The following example finds the customers whose last name starts with the
letter z:
SELECT customer_id, first_name, last_name
FROM customers
WHERE last_name LIKE 'z%'
ORDER BY first_name
The following example returns the customers whose last name ends with the string er:
SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE last_name LIKE '%er'
ORDER BY first_name
The following statement retrieves the customers whose last name starts with the letter t and ends with
the letter s:
SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE last_name LIKE 't%s'
ORDER BY first_name
The following example returns the customers whose last name ends with the string er:
SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE last_name LIKE '%er'
ORDER BY first_name
The following statement retrieves the customers whose last name starts with the letter t and ends
with the letter s:
SELECT
customer_id,
first_name,
last_name
FROM customers
WHERE last_name LIKE 't%s'
ORDER BY first_name
The square brackets with a caret sign (^) followed by a range e.g., [^A-C] or character list e.g., [ABC] represent
a single character that is not in the specified range or character list. For example, the following query returns
the customers where the first character in the last name is not the letter in the range A through X:
The following statement uses the CAST() function to convert the monthly sales in 2017 to integer
values.
SELECT
MONTH(order_date) month,
CAST(SUM(quantity * list_price * (1 - discount)) AS INT) amount
FROM orders o
INNER JOIN order_items i ON o.order_id = i.order_id
WHERE YEAR(order_date) = 2017
GROUP BY MONTH(order_date)
ORDER BY month
The CONVERT() function converts a value (of any type) into a specified datatype.
Consider the orders and customers tables from the BikeStores Database. The following statement shows
how to use a subquery in the WHERE clause of a SELECT statement to find the sales orders of the
customers located in New York:
Correlated Subqueries:
A correlated subquery is a subquery that uses the values of the outer query. In other words, the correlated
subquery depends on the outer query for its values. Moreover, a correlated subquery is executed repeatedly,
once for each row evaluated by the outer query. The correlated subquery is also known as a repeating
subquery. Consider the following products table from the BikeStores database.
Table Variables:
Table variables are kinds of variables that allow you to
hold rows of data, which are similar to temporary tables.
In this example:
First, we defined cte_sales_amounts as the name of the common table expression. the CTE returns a
result that that consists of three columns staff, year, and sales derived from the definition query.
Second, we constructed a query that returns the total sales amount by sales staff and year by querying
data from the orders, order_items and staffs tables.
Third, we referred to the CTE in the outer query and select only the rows whose year are 2018.
Noted that this example is solely for the demonstration purpose to help you gradually understand how
common table expressions work. There is a more optimal way to achieve the result without using CTE.
Next time, if you want to get the same result set, you can save this query into a text file, open it, and execute
it again. SQL Server provides a better way to save this query in the database catalog through a view.
A view is a named query stored in the database catalog that allows you to refer to it later.
So, the query above can be stored as a view using the CREATE VIEW statement as follows:
Later, you can reference to the view in the SELECT statement like a table as follows:
Advantages of views:
Generally speaking, views provide the following advantages:
1. Security:
You can restrict users to access directly to a table and allow them to access a subset of data via views.
For example, you can allow users to access customer name, phone, email via a view but restrict them
to access the bank account and other sensitive information.
2. Simplicity:
A relational database may have many tables with complex relationships e.g., one-to-one and one-to-
many that make it difficult to navigate.
However, you can simplify the complex queries with joins and conditions using a set of views.
3. Consistency:
Sometimes, you need to write a complex formula or logic in every query.
To make it consistent, you can hide the complex queries logic and calculations in views.
Once views are defined, you can reference the logic from the views rather than rewriting it in separate
queries.
BETWEEN
The BETWEEN operator is a logical operator that allows you to specify a range to test.
The following illustrates the syntax of the BETWEEN operator:
The following query finds the products whose list prices are between 149.99 and 199.99:
To get the products whose list prices are not in the range of 149.99 and 199.99, you use the NOT
BETWEEN operator as follows:
The following query finds the orders that customers placed between January 15, 2017 and January 17, 2017:
Notice that to specify a literal date, you use the format ‘YYYYMMDD‘ where YYYY is 4-digits year e.g., 2017,
MM is 2-digits month e.g., 01 and DD is 2-digits day e.g., 15.
ALIASES
When you use the SELECT statement to query data from a table, SQL Server uses the column names as the
column headings for the output. See the following example:
A table can be given an alias which is known as correlation name or range variable.
Similar to the column alias, table alias can be assigned either with or without the AS keyword:
NULLIF
In this session, you will learn how to use the SQL Server NULLIF expression to return NULL if the first
argument equals to the second one. The NULLIF expression accepts two arguments and returns NULL if two
arguments are equal. Otherwise, it returns the first expression.
IF ELSE
IF STATEMENT
DECLARE @sales INT
SELECT @sales
IF @sales > 1000000
BEGIN
PRINT 'Great! The sales amount in 2018 is greater than 1,000,000'
END
SELECT @sales;
IF @sales > 10000000
BEGIN
PRINT 'Great! The sales amount in 2018 is greater than 10,000,000';
END
ELSE
BEGIN
PRINT 'Sales amount in 2017 did not reach 10,000,000';
END
NESTED IF...ELSE
IF (@x > 0)
BEGIN
IF (@x < @y)
PRINT 'x > 0 and x < y';
ELSE
PRINT 'x > 0 and x >= y';
END
WHILE LOOP
SQL WHILE loop provides us with the advantage to execute the SQL statement(s) repeatedly until the
specified condition result turn out to be false. Let’s take an example of using the SQL Server WHILE statement
to understand it better. The following example illustrates how to use the WHILE statement to print out
numbers from 1 to 5:
If you want to copy the partial data from the source table, you use the WHERE clause to specify which rows
to copy. Similarly, you can specify which columns from the source table to copy to the destination table by
specifying them in the select list.
Using SQL Server SELECT INTO to copy table within the same database example:
The SELECT INTO statement creates a new table and inserts rows from the query into it.
The following SELECT INTO statement creates the destination table and copies rows, which satisfy the
WHERE condition, from the source table to the destination table:
In this syntax, the statement inserts rows returned by the query into the target_table.
The query is any valid SELECT statement that retrieves data from other tables. It must return the values that
are corresponding to the columns specified in the column_list.
The TOP clause part is optional. It allows you to specify the number of rows returned by the query to be
inserted into the target table. If you use the PERCENT option, the statement will insert the percent of rows
instead. Note that it is a best practice to always use the TOP clause with the ORDER BY clause.
STORED PROCEDURES
SQL Server stored procedures are used to group one or more Transact-SQL statements into logical units. The
stored procedure is stored as a named object in the SQL Server Database Server. When you call a stored
procedure for the first time, SQL Server creates an execution plan and stores it in the cache. In the
subsequent executions of the stored procedure, SQL Server reuses the plan to execute the stored procedure
very fast with reliable performance.
In this syntax:
The uspProductList is the name of the stored procedure.
The AS keyword separates the heading and the body of the stored procedure.
If the stored procedure has one statement, the BEGIN and END keywords surrounding the statement
are optional. However, it is a good practice to include them to make the code clear.
Note that in addition to the CREATE PROCEDURE keywords, you can use the CREATE PROC keywords to
make the statement shorter.
To compile this stored procedure, you execute it as a normal SQL statement in SQL Server Management
Studio as shown in the following picture:
You can find the stored procedure in the Object Explorer, under Programmability > Stored Procedures as
shown in the following picture:
Sometimes, you need to click the Refresh button to manually update the database objects in the Object
Explorer.
Second, change the body of the stored procedure by sorting the products by list prices instead of product
names:
Deleting a stored procedure
SQL Server Stored Procedure Parameters (Creating a stored procedure with one parameter)
Variables
A variable is an object that holds a single value of a specific type e.g., integer, date, or varying character string.
We typically use variables in the following cases:
As a loop counter to count the number of times a loop is performed.
To hold a value to be tested by a control-of-flow statement such as WHILE.
To store the value returned by a stored procedure or a function
Declaring a variable
To declare a variable, you use the DECLARE statement. For example, the following statement declares a
variable named @model_year:
Output Parameters
Advantage of Stored Procedures
1. Better Performance –
The procedure calls are quick and efficient as stored procedures are compiled once and stored in
executable form.Hence the response is quick. The executable code is automatically cached, hence
lowers the memory requirements.
2. Higher Productivity –
Since the same piece of code is used again and again so, it results in higher productivity.
3. Ease of Use –
To create a stored procedure, one can use any Java Integrated Development Environment (IDE). Then,
they can be deployed on any tier of network architecture.
4. Scalability –
Stored procedures increase scalability by isolating application processing on the server.
5. Maintainability –
Maintaining a procedure on a server is much easier than maintaining copies on various client
machines, this is because scripts are in one location.
6. Security –
Access to the Oracle data can be restricted by allowing users to manipulate the data only through
stored procedures that execute with their definer’s privileges.