Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Tutorials SQL Server by Amit Sir

SQl notes

Uploaded by

Kashish Agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Tutorials SQL Server by Amit Sir

SQl notes

Uploaded by

Kashish Agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Compiled By : Amit Srivastava

DBMS TUTORIAL

SQL Server: SELECT Statement


This SQL Server tutorial explains how to use the SELECT statement in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) SELECT statement is used to retrieve records from one or more tables in a SQL Server database.

Syntax
In its simplest form, the syntax for the SELECT statement in SQL Server (Transact-SQL) is:

SELECT expressions
FROM tables
[WHERE conditions];

However, the full syntax for the SELECT statement in SQL Server (Transact-SQL) is:

SELECT [ ALL | DISTINCT ]


[ TOP (top_value) [ PERCENT ] [ WITH TIES ] ]
expressions
FROM tables
[WHERE conditions]
[GROUP BY expressions]
[HAVING condition]
[ORDER BY expression [ ASC | DESC ]];f

Parameters or Arguments
ALL
Optional. Returns all matching rows.
DISTINCT
Optional. Removes duplicates from the result set. Learn more about the DISTINCT clause
TOP (top_value)
Optional. If specified, it will return the top number of rows in the result set based on top_value. For example, TOP(10)
would return the top 10 rows from the full result set.
PERCENT
Optional. If specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value).
For example, TOP(10) PERCENT would return the top 10% of the full result set.
WITH TIES
Optional. If specified, then rows tied in last place within the limited result set are returned. This may result in more rows be
returned than the TOP parameter permits.
expressions
The columns or calculations that you wish to retrieve. Use * if you wish to select all columns.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
GROUP BY expressions
Optional. It collects data across multiple records and groups the results by one or more columns.
HAVING condition
Optional. It is used in combination with the GROUP BY to restrict the groups of returned rows to only those whose the
condition is TRUE.
ORDER BY expression
Compiled By : Amit Srivastava
Optional. It is used to sort the records in your result set. ASC sorts in ascending order and DESC sorts in descending
order.

Example - Select all fields from one table


Let's look at how to use a SQL Server SELECT query to select all fields from a table.

SELECT *
FROM inventory
WHERE quantity > 5
ORDER BY inventory_id ASC;

In this SQL Server SELECT statement example, we've used * to signify that we wish to select all fields from the inventory table
where the quantity is greater than 5. The result set is sorted by inventory_id in ascending order.

Example - Select individual fields from one table


You can also use the SQL Server SELECT statement to select individual fields from the table, as opposed to all fields from the
table.
For example:

SELECT inventory_id, inventory_type, quantity


FROM inventory
WHERE inventory_id >= 555
AND inventory_type = 'Software'
ORDER BY quantity DESC, inventory_id ASC;

This SQL Server SELECT example would return only the inventory_id, inventory_type, and quantity fields from the inventory table
where the inventory_id is greater than or equal to 555 and the inventory_type is 'Software'. The results are sorted by quantity in
descending order and then inventory_id in ascending order.

Example - Select fields from multiple tables


You can also use the SQL Server SELECT statement to retrieve fields from multiple tables by using a join.
For example:

SELECT inventory.inventory_id, products.product_name, inventory.quantity


FROM inventory
INNER JOIN products
ON inventory.product_id = products.product_id
ORDER BY inventory_id;

This SQL Server SELECT example joins two tables together to gives us a result set that displays the inventory_id, product_name,
and quantity fields where the product_id value matches in both the inventory and products table. The results are sorted
by inventory_id in ascending order.

Example - Using TOP keyword


Let's look at a SQL Server example, where we use the TOP keyword in the SELECT statement.
For example:

SELECT TOP(3)
inventory_id, inventory_type, quantity
Compiled By : Amit Srivastava
FROM inventory
WHERE inventory_type = 'Software'
ORDER BY inventory_id ASC;

This SQL Server SELECT example would select the first 3 records from the inventory table where the inventory_type is 'Software'. If
there are other records in the inventory table that have a inventory_type value of 'Software', they will not be returned by the SELECT
statement.

Example - Using TOP PERCENT keyword


Let's look at a SQL Server example, where we use the TOP PERCENT keyword in the SELECT statement.
For example:

SELECT TOP(10) PERCENT


inventory_id, inventory_type, quantity
FROM inventory
WHERE inventory_type = 'Software'
ORDER BY inventory_id ASC;

This SQL Server SELECT example would select the first 10% of the records from the full result set. So in this example, the SELECT
statement would return the top 10% of records from the inventory table where the inventory_type is 'Software'. The other 90% of the
result set would not be returned by the SELECT statement.

SQL Server: FROM Clause


This SQL Server tutorial explains how to use the FROM clause in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) FROM clause is used to list the tables and any joins required for the query in SQL Server.

Syntax
The syntax for the FROM clause in SQL Server (Transact-SQL) is:

FROM table1
[ { INNER JOIN
| LEFT OUTER JOIN
| RIGHT OUTER JOIN
| FULL OUTER JOIN } table2
ON table1.column1 = table2.column1 ]

Parameters or Arguments
table1 and table2
The tables used in the SQL statement. The two tables are joined based on table1.column1 = table2.column1.

Note

• There must be at least one table listed in the FROM clause in SQL Server (Transact-SQL).
• If there are two or more tables listed in the FROM clause, these tables are generally joined in the FROM clause using
INNER or OUTER joins. Although the tables can also be joined using the old syntax in the WHERE clause, we
recommend using new standards and including your join information in the FROM clause.
Compiled By : Amit Srivastava
Example - With one table

It is difficult to explain the syntax for the SQL Server FROM clause, so let's look at some examples.
We'll start by looking at how to use the FROM clause with only a single table.
For example:

SELECT *
FROM employees
WHERE first_name = 'Jane';

In this SQL Server FROM clause example, we've used the FROM clause to list the table called employees. There are no joins
performed since we are only using one table.

SQL Server: Comparison Operators


This SQL Server tutorial explores all of the comparison operators used to test for equality and inequality, as well as the more
advanced operators in SQL Server (Transact-SQL).

Description
Comparison operators are used in the WHERE clause to determine which records to select. Here is a list of the comparison
operators that you can use in SQL Server (Transact-SQL):

Comparison Operator Description

= Equal

<> Not Equal

!= Not Equal

> Greater Than

>= Greater Than or Equal

< Less Than

<= Less Than or Equal

!> Not Greater Than

!< Not Less Than

IN ( ) Matches a value in a list

NOT Negates a condition

BETWEEN Within a range (inclusive)


Compiled By : Amit Srivastava

Comparison Operator Description

IS NULL NULL value

IS NOT NULL Non-NULL value

LIKE Pattern matching with % and _

EXISTS Condition is met if subquery returns at least one row


There are many comparison operators in SQL Server and Transact-SQL. Let's explore how to use the more common operators.

Example - Equality Operator


In SQL Server, you can use the = operator to test for equality in a query.
For example:

SELECT *
FROM employees
WHERE first_name = 'Jane';

In this example, the SELECT statement above would return all rows from the employees table where the first_name is equal to
Jane.

Example - Inequality Operator


In SQL Server, you can use the <> or != operators to test for inequality in a query.
For example, we could test for inequality using the <> operator, as follows:

SELECT *
FROM employees
WHERE first_name <> 'Jane';

In this example, the SELECT statement would return all rows from the employees table where the first_name is not equal to Jane.
Or you could also write this query using the != operator, as follows:

SELECT *
FROM employees
WHERE first_name != 'Jane';

Both of these queries would return the same results.

Example - Greater Than Operator


You can use the > operator in SQL Server to test for an expression greater than.

SELECT *
FROM employees
WHERE employee_id > 3000;

In this example, the SELECT statement would return all rows from the employees table where the employee_id is greater than
3000. An employee_id equal to 3000 would not be included in the result set.

Example - Greater Than or Equal Operator


Compiled By : Amit Srivastava
In SQL Server, you can use the >= operator to test for an expression greater than or equal to.

SELECT *
FROM employees
WHERE employee_id >= 3000;

In this example, the SELECT statement would return all rows from the employees table where the employee_id is greater than or
equal to 3000. In this case, n employee_id equal to 3000 would be included in the result set.

Example - Less Than Operator


You can use the < operator in SQL Server to test for an expression less than.

SELECT *
FROM employees
WHERE employee_id < 500;

In this example, the SELECT statement would return all rows from the employees table where the employee_id is less than 500.
An employee_id equal to 500 would not be included in the result set.

Example - Less Than or Equal Operator


In SQL Server, you can use the <= operator to test for an expression less than or equal to.

SELECT *
FROM employees
WHERE employee_id <= 500;

In this example, the SELECT statement would return all rows from the employees table where the employee_id is less than or equal
to 500. In this case, n employee_id equal to 500 would be included in the result set.

Example - Advanced Operators

SQL Server: IN Condition


This SQL Server tutorial explains how to use the IN condition in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) IN condition is used to help reduce the need to use multiple OR conditions in a SELECT, INSERT,
UPDATE, or DELETE statement.

Syntax
The syntax for the IN condition in SQL Server (Transact-SQL) is:

expression IN (value1, value2, .... value_n);

OR

expression IN (subquery);

Parameters or Arguments
expression
Compiled By : Amit Srivastava
A value to test.
value1, value2,.. value_n
The values to test against expression.
subquery
This is a SELECT statement whose result set will be tested against expression. If any of these values
matches expression, then the IN condition will evaluate to true.

Note

• The SQL Server IN condition will return the records where expression is value1, value2..., or value_n.
• The SQL Server IN condition is also called the SQL Server IN operator.

Example - With string


Let's look at a SQL Server IN condition example using string values.
The following is a SQL Server SELECT statement that uses the IN condition to compare string values:

SELECT *
FROM employees
WHERE last_name IN ('Smith', 'Anderson', 'Johnson');

This SQL Server IN condition example would return all rows from the employees table where the last_name is either 'Smith',
'Anderson', or 'Johnson'. Because the * is used in the SELECT, all fields from the employees table would appear in the result set.
The above IN example is equivalent to the following SELECT statement:

SELECT *
FROM employees
WHERE last_name = 'Smith'
OR last_name = 'Anderson'
OR last_name = 'Johnson';

As you can see, using the SQL Server IN condition makes the statement easier to read and more efficient.

Example - With Numeric


Next, let's look at a SQL Server IN condition example using numeric values.
For example:

SELECT *
FROM employees
WHERE employee_id IN (1, 2, 3, 4, 10);

This SQL Server IN condition example would return all employees where the employee_id is either 1, 2, 3, 4, or 10.
The above IN example is equivalent to the following SELECT statement:

SELECT *
FROM employees
WHERE employee_id = 1
OR employee_id = 2
OR employee_id = 3
OR employee_id = 4
OR employee_id = 10;
Compiled By : Amit Srivastava

Example - Using NOT operator


Finally, let's look at an IN condition example using the SQL Server NOT operator.
For example:

SELECT *
FROM employees
WHERE first_name NOT IN ('Sarah', 'John', 'Dale');

This SQL Server IN condition example would return all rows from the employees table where the first_name is not 'Sarah', 'John', or
'Dale' Sometimes, it is more efficient to list the values that you do not want, as opposed to the values that you do want.
The above IN example is equivalent to the following SELECT statement:

SELECT *
FROM employees
WHERE first_name <> 'Sarah'
AND first_name <> 'John'
AND first_name <> 'Dale';

SQL Server: NOT Condition


This SQL Server tutorial explains how to use the NOT condition in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) NOT condition, also called the NOT Operator, is used to negate a condition in a SELECT, INSERT,
UPDATE, or DELETE statement.

Syntax
The syntax for the NOT condition in SQL Server (Transact-SQL) is:

NOT condition

Parameters or Arguments
condition
The condition to negate.

Note

• The SQL Server NOT condition requires that the opposite of the condition must be met for the record to be included in the
result set.

Example - Combine With IN condition


The SQL Server NOT condition can be combined with the IN condition.
For example:

SELECT *
FROM employees
Compiled By : Amit Srivastava
WHERE first_name NOT IN ( 'John', 'Dale', 'Susan' );

This SQL Server NOT example would return all rows from the employees table where the first_name is not 'John', 'Dale', or 'Susan'.
Sometimes, it is more efficient to list the values that you do not want, as opposed to the values that you do want.

Example - Combine With IS NULL condition


The SQL Server NOT condition can also be combined with the IS NULL condition.
For example,

SELECT *
FROM employees
WHERE last_name IS NOT NULL;

This SQL Server NOT example would return all records from the employees table where the last_name does not contain a NULL
value.

Example - Combine With LIKE condition


The SQL Server NOT condition can also be combined with the LIKE condition.
For example:

SELECT employee_id, last_name, first_name


FROM employees
WHERE last_name NOT LIKE 'A%';

By placing the SQL Server NOT Operator in front of the LIKE condition, you are able to retrieve all employees
whose last_name does not start with 'A'.

Example - Combine With BETWEEN condition


The SQL Server NOT condition can also be combined with the BETWEEN condition. Here is an example of how you would combine
the NOT Operator with the BETWEEN condition.
For example:

SELECT *
FROM employees
WHERE employee_id NOT BETWEEN 200 AND 250;

This SQL Server NOT example would return all rows from the employees table where the employee_id was NOT between 200 and
250, inclusive. It would be equivalent to the following SQL Server SELECT statement:

SELECT *
FROM employees
WHERE employee_id < 200
OR employee_id > 250;

Example - Combine With EXISTS condition


The SQL Server NOT condition can also be combined with the EXISTS condition.
For example,

SELECT *
FROM employees
Compiled By : Amit Srivastava
WHERE NOT EXISTS (SELECT *
FROM contacts
WHERE employees.last_name = contacts.last_name
AND employees.first_name = contacts.first_name);

This SQL Server NOT example would return all records from the employees table where there are no records in the contacts table
for the matching last_name and first_name.

SQL Server: BETWEEN Condition


how to use the BETWEEN condition in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) BETWEEN condition is used to retrieve values within a range in a SELECT, INSERT, UPDATE, or
DELETE statement.

Syntax
The syntax for the BETWEEN condition in SQL Server (Transact-SQL) is:

expression BETWEEN value1 AND value2;

Parameters or Arguments
expression
A column or calculation.
value1 and value2
These values create an inclusive range that expression is compared to.

Note

• The SQL Server BETWEEN condition will return the records where expression is within the range
of value1 and value2 (inclusive).

Example - With Numeric


Let's look at some SQL Server BETWEEN condition examples using numeric values. The following numeric example uses the
BETWEEN condition to retrieve values within a numeric range.
For example:

SELECT *
FROM employees
WHERE employee_id BETWEEN 25 AND 100;

This SQL Server BETWEEN example would return all rows from the employees table where the employee_id is between 25 and
100 (inclusive). It is equivalent to the following SELECT statement:

SELECT *
FROM employees
WHERE employee_id >= 25
AND employee_id <= 100;
Compiled By : Amit Srivastava

Example - With Date


Next, let's look at how you would use the SQL Server BETWEEN condition with Dates. The following date example uses the
BETWEEN condition to retrieve values within a date range.
For example:

SELECT *
FROM employees
WHERE start_date BETWEEN '2014/05/01' AND '2014/05/31';

This SQL Server BETWEEN condition example would return all records from the employees table where the start_date is between
May 1, 2014 and May 31, 2014 (inclusive). It would be equivalent to the following SELECT statement:

SELECT *
FROM employees
WHERE start_date >= '2014/05/01'
AND start_date <= '2014/05/31';

Example - Using NOT Operator


The SQL Server BETWEEN condition can also be combined with the SQL Server NOT operator. Here is an example of how you
would combine the BETWEEN condition with the NOT Operator.
For example:

SELECT *
FROM employees
WHERE employee_id NOT BETWEEN 2000 AND 2999;

This SQL Server BETWEEN example would return all rows from the employees table where the employee_id was NOT between
2000 and 2999, inclusive. It would be equivalent to the following SELECT statement:

SELECT *
FROM employees
WHERE employee_id < 2000
OR employee_id > 2999;

SQL Server: IS NULL Condition


This SQL Server tutorial explains how to use the IS NULL condition in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) IS NULL condition is used to test for a NULL value.

Syntax
The syntax for the IS NULL condition in SQL Server (Transact-SQL) is:

expression IS NULL

Parameters or Arguments
Compiled By : Amit Srivastava
expression
The value to test whether it is a NULL value.

Note

• If expression is a NULL value, the condition evaluates to TRUE.


• If expression is not a NULL value, the condition evaluates to FALSE.

Example - With SELECT Statement


Let's look at how to use the IS NULL condition in a SELECT statement in SQL Server.
For example:

SELECT *
FROM employees
WHERE last_name IS NULL;

This SQL Server IS NULL example will return all records from the employees table where the last_name contains a null value.

Example - With INSERT Statement


Let's look at how to use the IS NULL condition in an INSERT statement in SQL Server.
For example:

INSERT INTO employees


(employee_id, last_name, first_name)
SELECT contact_id, last_name, first_name
FROM contacts
WHERE first_name IS NULL;

This SQL Server IS NULL example will insert records into the employees table records from the contacts table where
the first_name contains a null value.

Example - With UPDATE Statement


Lets' look at an example of how to use the IS NULL condition in an UPDATE STAEMENT in SQL Server.
For example:

UPDATE employees
SET first_name = 'Unknown'
WHERE first_name IS NULL;

This SQL Server IS NULL example will update records in the employees table where the first_name contains a null value.

Example - With DELETE Statement


Let's look at an example of how to use the IS NULL condition in a DELETE STATEMENT in SQL Server.
For example:

DELETE FROM employees


WHERE last_name IS NULL;
Compiled By : Amit Srivastava
This SQL Server IS NULL example will delete all records from the employees table where the last_name contains a null value.

SQL Server: IS NOT NULL Condition


This SQL Server tutorial explains how to use the IS NOT NULL condition in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) IS NOT NULL condition is used to test for a NOT NULL value.

Syntax
The syntax for the IS NOT NULL condition in SQL Server (Transact-SQL) is:

expression IS NOT NULL

Parameters or Arguments
expression
The value to test where it is a non-NULL value.

Note

• If expression is NOT a NULL value, the condition evaluates to TRUE.


• If expression is a NULL value, the condition evaluates to FALSE.

Example - With SELECT Statement


Let's look at an example of how to use the IS NOT NULL condition in a SELECT statement in SQL Server.
For example:

SELECT *
FROM employees
WHERE last_name IS NOT NULL;

This SQL Server IS NOT NULL example will return all records from the employees table where the last_name does not contain a
null value.

Example - With INSERT Statement


Let's look at an example of how to use the IS NOT NULL condition in an INSERT statement in SQL Server.
For example:

INSERT INTO contacts


(contact_id, last_name, first_name)
SELECT employee_id, last_name, first_name
FROM employees
WHERE last_name IS NOT NULL;

This SQL Server IS NOT NULL example will insert records into the contacts table where the last_name does not contain a null value
in the employees table.
Compiled By : Amit Srivastava

Example - With UPDATE Statement


Let's look at an example of how to use the IS NOT NULL condition in an UPDATE statement in SQL Server.
For example:

UPDATE employees
SET status = 'Active'
WHERE last_name IS NOT NULL;

This SQL Server IS NOT NULL example will update records in the employees table where the last_name does not contain a null
value.

Example - With DELETE Statement


Let's look at an example of how to use the IS NOT NULL condition in a DELETE statement in SQL Server.
For example:

DELETE FROM employees


WHERE status IS NOT NULL;

This SQL Server IS NOT NULL example will delete all records from the employees table where the status does not contain a null
value.

SQL Server: LIKE Condition


This SQL Server tutorial explains how to use the LIKE condition in SQL Server (Transact-SQL) to perform pattern matching with
syntax and examples.

Description
The SQL Server (Transact-SQL) LIKE condition allows wildcards to be used in the WHERE clause of a SELECT, INSERT,
UPDATE, or DELETE statement. This allows you to perform pattern matching.

Syntax
The syntax for the LIKE condition in SQL Server (Transact-SQL) is:

expression LIKE pattern [ ESCAPE 'escape_character' ]

Parameters or Arguments
expression
A character expression such as a column or field.
pattern
A character expression that contains pattern matching. The patterns that you can choose from are:

Wildcard Explanation

% Allows you to match any string of any length (including zero length)

_ Allows you to match on a single character

[] Allows you to match on any character in the [ ] brackets (for example, [abc]
Compiled By : Amit Srivastava

Wildcard Explanation

would match on a, b, or c characters)

Allows you to match on any character not in the [^] brackets (for example,
[^]
[^abc] would match on any character that is not a, b, or c characters)
escape_character
Optional. It allows you to test for literal instances of a wildcard character such as % or _.

Example - Using % wildcard (percent sign wildcard)


The first SQL Server LIKE example that we will look at involves using the % wildcard (percent sign wildcard).
Let's explain how the % wildcard works in the SQL Server LIKE condition. We want to find all of the employees
whose last_name begins with 'B'.
For example:

SELECT *
FROM employees
WHERE last_name LIKE 'B%';

You can also using the % wildcard multiple times within the same string. For example,

SELECT *
FROM employees
WHERE last_name LIKE '%o%';

In this SQL Server LIKE condition example, we are looking for all employees whose last_name contains the letter 'o'.

Example - Using _ wildcard (underscore wildcard)


Next, let's explain how the _ wildcard (underscore wildcard) works in the SQL Server LIKE condition. Remember that _ wildcard is
looking for only one character.
For example:

SELECT *
FROM employees
WHERE first_name LIKE 'Ad_m';

This SQL Server LIKE condition example would return all employees whose first_name is 4 characters long, where the first two
characters is 'Ad' and the last character is 'm'. For example, it could return employees whose first_name is 'Adam', 'Adem', 'Adim',
'Adom', 'Adum', etc.
Here is another example:

SELECT *
FROM employees
WHERE employee_number LIKE '123_';

You might find that you are looking for an employee_number, but you only have 3 of the 4 digits. The example above, would retrieve
potentially 10 records back (where the missing value could equal anything from 0 to 9). For example, it could return employees
whose employee numbers are:
1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239
Compiled By : Amit Srivastava

Example - Using [ ] wildcard (square brackets wildcard)


Next, let's explain how the [ ] wildcard (square brackets wildcard) works in the SQL Server LIKE condition. Remember that what is
contained within the square brackets are characters that you are trying to match on.
For example:

SELECT *
FROM employees
WHERE first_name LIKE 'Sm[iy]th';

This SQL Server LIKE condition example would return all employees whose first_name is 5 characters long, where the first two
characters is 'Sm' and the last two characters is 'th', and the third character is either 'i' or 'y'. So in this case, it would match on either
'Smith' or 'Smyth'.

Example - Using [^] wildcard (square brackets with ^ wildcard)


Next, let's explain how the [^] wildcard (square brackets with ^ wildcard) works in the SQL Server LIKE condition. Remember that
what is contained within the square brackets are characters that you do NOT want to match on.
For example:

SELECT *
FROM employees
WHERE first_name LIKE 'Sm[^iy]th';

This SQL Server LIKE condition example would return all employees whose first_name is 5 characters long, where the first two
characters is 'Sm' and the last two characters is 'th', and the third character is neither 'i' or 'y'. So in this case, it would match on
values such as 'Smath', 'Smeth', 'Smoth', etc. But it would not match on either 'Smith' or 'Smyth'.

Example - Using NOT Operator


Next, let's look at how you would use the SQL Server NOT Operator with wildcards.
Let's use the % wilcard with the NOT Operator. You could also use the SQL Server LIKE condition to find employees
whose last_name does not start with 'B'.
For example:

SELECT *
FROM employees
WHERE last_name NOT LIKE 'B%';

By placing the NOT Operator in front of the SQL Server LIKE condition, you are able to retrieve all employees
whose last_name does not start with 'B'.

Example - Using Escape Characters


It is important to understand how to "Escape Characters" when pattern matching. These examples deal specifically with escaping
characters in SQL Server.
Let's say you wanted to search for a % or a _ character in the SQL Server LIKE condition. You can do this using an Escape
character.
Please note that you can only define an escape character as a single character (length of 1).
For example:

SELECT *
FROM employees
WHERE secret_hint LIKE '123!%455' ESCAPE '!';
Compiled By : Amit Srivastava
This SQL Server LIKE condition example identifies the ! character as an escape character. This statement will return all employees
whose secret_hint is 123%455.
Here is another more complicated example using escape characters in the SQL Server LIKE condition.

SELECT *
FROM employees
WHERE secret_hint LIKE 'H%!%' ESCAPE '!';

This SQL Server LIKE condition example returns all employees whose secret_hint starts with H and ends in %. For example, it
would return a value such as 'Help%'.
You can also use the escape character with the _ character in the SQL Server LIKE condition.
For example:

SELECT *
FROM employees
WHERE secret_hint LIKE 'H%!_' ESCAPE '!';

This SQL Server LIKE condition example returns all employees whose secret_hint starts with H and ends in _. For example, it would
return a value such as 'Help_'.

SQL Server: EXISTS Condition


This SQL Server tutorial explains how to use the EXISTS condition in SQL Server (Transact-SQL) with syntax and examples.
The SQL Server (Transact-SQL) EXISTS condition is used in combination with a subquery and is considered to be met if the
subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Syntax
The syntax for the EXISTS condition in SQL Server (Transact-SQL) is:

WHERE EXISTS ( subquery );

Parameters or Arguments
subquery
The subquery is a SELECT statement. If the subquery returns at least one record in its result set, the EXISTS clause will
evaluate to true and the EXISTS condition will be met. If the subquery does not return any records, the EXISTS clause will
evaluate to false and the EXISTS condition will not be met.

Note

• SQL statements that use the EXISTS condition are very inefficient since the sub-query is RE-RUN for EVERY row in the
outer query's table. There are more efficient ways to write most queries, that do not use the EXISTS condition.

Example - With SELECT Statement


Let's look at a simple example.
The following is a SELECT statement that uses the EXISTS condition:

SELECT *
FROM employees
WHERE EXISTS (SELECT *
Compiled By : Amit Srivastava
FROM contacts
WHERE employees.last_name = contacts.last_name
AND employees.first_name = contacts.first_name);

This SQL Server EXISTS condition example will return all records from the employees table where there is at least one record in
the contacts table with a matching last_name and first_name.

Example - With SELECT Statement using NOT EXISTS


The SQL Server EXISTS condition can also be combined with the NOT operator.
For example,

SELECT *
FROM employees
WHERE NOT EXISTS (SELECT *
FROM contacts
WHERE employees.last_name = contacts.last_name
AND employees.first_name = contacts.first_name);

This SQL Server EXISTS example will return all records from the employees table where there are no records in the contacts table
for the matching last_name and first_name.

Example - With INSERT Statement


The following is an example of an INSERT statement that uses the EXISTS condition:

INSERT INTO contacts


(contact_id, contact_name)
SELECT supplier_id, supplier_name
FROM suppliers
WHERE EXISTS (SELECT *
FROM orders
WHERE suppliers.supplier_id = orders.supplier_id);

Example - With UPDATE Statement


The following is an example of an UPDATE statement that uses the EXISTS condition:

UPDATE suppliers
SET supplier_name = (SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id)
WHERE EXISTS (SELECT customers.name
FROM customers
WHERE customers.customer_id = suppliers.supplier_id);

Example - With DELETE Statement


The following is an example of a DELETE statement that uses the EXISTS condition:
Compiled By : Amit Srivastava

DELETE FROM contacts


WHERE EXISTS (SELECT *
FROM employees
WHERE employees.last_name = contacts.last_name);

SQL Server: WHERE Clause


This SQL Server tutorial explains how to use the WHERE clause in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) WHERE clause is used to filter the results from a SELECT, INSERT, UPDATE, or DELETE
statement.

Syntax
The syntax for the WHERE clause in SQL Server (Transact-SQL) is:

WHERE conditions;

Parameters or Arguments
conditions
The conditions that must be met for records to be selected.

Example - With Single condition


It is difficult to explain the syntax for the SQL Server WHERE clause, so let's look at some examples.
We'll start by looking at how to use the WHERE clause with only a single condition.
For example:

SELECT *
FROM employees
WHERE first_name = 'Jane';

In this SQL Server WHERE clause example, we've used the WHERE clause to filter our results from the employees table. The
SELECT statement above would return all rows from the employees table where the first_name is 'Jane'. Because the * is used in
the SELECT, all fields from the employees table would appear in the result set.

Example - Using AND condition


Let's look at how to use the WHERE clause with the AND condition.
For example:

SELECT *
FROM employees
WHERE last_name = 'Anderson'
AND employee_id >= 3000;
Compiled By : Amit Srivastava
This SQL Server WHERE clause example uses the WHERE clause to define multiple conditions. In this case, this SELECT
statement uses the AND condition to return all employees that have a last_name of 'Anderson' and the employee_id is greater than
or equal to 3000.

Example - Using OR condition


Let's look at how to use the WHERE clause with the OR condition.
For example:

SELECT employee_id, last_name, first_name


FROM employees
WHERE last_name = 'Johnson'
OR first_name = 'Danielle';

This SQL Server WHERE clause example uses the WHERE clause to define multiple conditions, but instead of using the AND
condition, it uses the OR condition. In this case, this SELECT statement would return all employee_id, last_name,
and first_name values from the employees table where the last_name is 'Johnson' or the first_name is 'Danielle'.

Example - Combining AND & OR conditions


Let's look at how to use the WHERE clause when we combine the AND & OR conditions in a single SQL statement.
For example:

SELECT *
FROM employees
WHERE (state = 'California' AND last_name = 'Smith')
OR (employee_id = 82);

This SQL Server WHERE clause example uses the WHERE clause to define multiple conditions, but it combines the AND
condition and the OR condition. This example would return all employees that reside in the state of 'California' and
whose last_name is 'Smith' as well as all employees whose employee_id is equal to 82.
The parentheses determine the order that the AND and OR conditions are evaluated. Just like you learned in the order of operations
in Math class!

Example - Joining Tables


Let's look at how to use the WHERE clause when we join multiple tables together.
For example:

SELECT employees.employee_id, contacts.last_name


FROM employees
INNER JOIN contacts
ON employees.employee_id = contacts.contact_id
WHERE employees.first_name = 'Sarah';

This SQL Server WHERE clause example uses the WHERE clause to join multiple tables together in a single SELECT statement.
This SELECT statement would return all rows where the first_name in the employees table is 'Sarah'. And the employees
and contacts tables are joined on the employee_id from the employees table and the contact_id from the contacts table.

SQL Server: ORDER BY Clause


This SQL Server tutorial explains how to use the ORDER BY clause in SQL Server (Transact-SQL) with syntax and examples.
Compiled By : Amit Srivastava

Description
The SQL Server (Transact-SQL) ORDER BY clause is used to sort the records in your result set. The ORDER BY clause can only
be used in SELECT statements.

Syntax
The syntax for the ORDER BY clause in SQL Server (Transact-SQL) is:

SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];

Parameters or Arguments
expressions
The columns or calculations that you wish to retrieve.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. The conditions that must be met for the records to be selected.
ASC
Optional. It sorts the result set in ascending order by expression (default, if no modifier is provider).
DESC
Optional. It sorts the result set in descending order by expression.

Note

• If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will be sorted by expression in
ascending order. This is equivalent to ORDER BY expression ASC.

Example - Sorting without using ASC/DESC attribute


The SQL Server ORDER BY clause can be used without specifying the ASC or DESC value. When this attribute is omitted from the
ORDER BY clause, the sort order is defaulted to ASC or ascending order.
For example:

SELECT last_name
FROM employees
WHERE employee_id > 1000
ORDER BY last_name;

This SQL Server ORDER BY example would return all records sorted by the last_name field in ascending order and would be
equivalent to the following ORDER BY clause:

SELECT last_name
FROM employees
WHERE employee_id > 1000
ORDER BY last_name ASC;

Most programmers omit the ASC attribute if sorting in ascending order.

Example - Sorting in descending order


Compiled By : Amit Srivastava
When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause.
For example:

SELECT last_name
FROM employees
WHERE first_name = 'Sarah'
ORDER BY last_name DESC;

This SQL Server ORDER BY example would return all records sorted by the last_name field in descending order.

Example - Sorting by relative position


You can also use the SQL Server ORDER BY clause to sort by relative position in the result set, where the first field in the result set
is 1. The next field is 2, and so on.
For example:

SELECT last_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY 1 DESC;

This SQL Server ORDER BY would return all records sorted by the last_name field in descending order, since the last_name field is
in position #1 in the result set and would be equivalent to the following ORDER BY clause:

SELECT last_name
FROM employees
WHERE last_name = 'Anderson'
ORDER BY last_name DESC;

Example - Using both ASC and DESC attributes


When sorting your result set using the SQL Server ORDER BY clause, you can use the ASC and DESC attributes in a
single SELECT statement.
For example:

SELECT last_name, first_name


FROM employees
WHERE last_name = 'Johnson'
ORDER BY last_name DESC, first_name ASC;

This SQL Server ORDER BY would return all records sorted by the last_name field in descending order, with a secondary sort
by first_name in ascending order.

SQL Server: AND Condition


This SQL Server tutorial explains how to use the AND condition in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) AND condition (also called the AND Operator) is used to test for two or more conditions in a
SELECT, INSERT, UPDATE, or DELETE statement.
Compiled By : Amit Srivastava

Syntax
The syntax for the AND condition in SQL Server (Transact-SQL) is:

WHERE condition1
AND condition2
...
AND condition_n;

Parameters or Arguments
condition1, condition2, ... condition_n
All of the conditions that must be met for the records to be selected.

Note

• The SQL Server AND condition allows you to test 2 or more conditions.
• The SQL Server AND condition requires that all of the conditions (ie: condition1, condition2, condition_n) must be met for
the record to be included in the result set.

Example - With SELECT Statement


The first SQL Server AND condition query involves a SELECT statement with 2 conditions.
For example:

SELECT *
FROM employees
WHERE last_name = 'Smith'
AND employee_id < 499;

This SQL Server AND example would return all employees who have a last_name of 'Smith' and have an employee_id less than
499. Because the * is used in the SELECT statement, all fields from the employees table would appear in the result set.

Example - JOINING Tables


Our next SQL Server AND example shows how the AND condition can be used to join multiple tables in a SELECT statement.
For example:

SELECT employees.employee_id, contacts.last_name


FROM employees, contacts
WHERE employees.employee_id = contacts.contact_id
AND employees.first_name = 'Sarah';

Though the above SQL works just fine, you would more traditionally write this SQL as follows using a proper INNER JOIN.
For example:

SELECT employees.employee_id, contacts.last_name


FROM employees
INNER JOIN contacts
ON employees.employee_id = contacts.contact_id
WHERE employees.first_name = 'Sarah';
Compiled By : Amit Srivastava
This SQL Server AND condition example would return all rows where the first_name in the employees table is 'Sarah'. And
the employees and contacts tables are joined on the employee_id from the employees table and the contact_id from
the contacts table. You will notice that all of the fields are prefixed with the table names (ie: contacts.last_name). This is required to
eliminate any ambiguity as to which field is being referenced; as the same field name can exist in both the employees and
the contacts tables.
In this case, the result set would only display the employee_id and last_name fields (as listed in the first part of the SELECT
statement.).

Example - With INSERT Statement


This next SQL Server AND example demonstrates how the AND condition can be used in the INSERT statement.
For example:

INSERT INTO contacts


(contact_id, last_name, first_name)
SELECT employee_id, last_name, first_name
FROM employees
WHERE first_name = 'Joanne'
AND employee_id >= 800;

This SQL Server AND condition example would insert into the contacts table, all employee_id, last_name, and first_name records
from the employees table where the first_name is 'Joanne' and the employee_id is greater than or equal to 800.

Example - With UPDATE Statement


This SQL Server AND condition example shows how the AND condition can be used in the UPDATE statement.
For example:

UPDATE employees
SET last_name = 'Johnson'
WHERE last_name = 'TBD'
AND employee_id < 300;

This SQL Server AND condition example would update all last_name values in the employees table to 'Johnson' where
the last_name is 'TBD' and the employee_id is less than 300.

Example - With DELETE Statement


Finally, this last SQL Server AND example demonstrates how the AND condition can be used in the DELETE statement.
For example:

DELETE FROM employees


WHERE first_name = 'Darlene'
AND last_name = 'Henderson';

This SQL Server AND condition example would delete all records from the employees table whose first_name is 'Darlene'
and last_name is 'Henderson'.

SQL Server: OR Condition


This SQL Server tutorial explains how to use the OR condition in SQL Server (Transact-SQL) with syntax and examples.

Description
Compiled By : Amit Srivastava
The SQL Server (Transact-SQL) OR condition is used to test multiple conditions where records are returned when any one of the
conditions are met. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Syntax
The syntax for the OR condition in SQL Server (Transact-SQL) is:

WHERE condition1
OR condition2
...
OR condition_n;

Parameters or Arguments
condition1, condition2, ... condition_n
Any of the conditions that must be met for the records to be selected.

Note

• The SQL Server OR condition allows you to test 2 or more conditions.


• The SQL Server OR condition requires that any of the conditions (ie: condition1, condition2, condition_n) must be met for
the record to be included in the result set.

Example - With SELECT Statement


The first SQL Server OR condition example that we'll take a look at involves a SELECT statement with 2 conditions.
For example:

SELECT *
FROM employees
WHERE first_name = 'Sarah'
OR last_name = 'Johnson';

This SQL Server OR example would return all employees whose first_name is 'Sarah' or last_name is 'Johnson'. Because the * is
used in the SELECT statement, all fields from the employees table would appear in the result set.

Example - With SELECT Statement (3 conditions)


The next SQL Server OR example looks at a SELECT statement with 3 conditions. If any of these conditions is met, the record will
be included in the result set.
For example:

SELECT last_name, first_name


FROM employees
WHERE last_name = 'Anderson'
OR state = 'California'
OR employee_id = 50;

This SQL Server OR condition example would return all last_name and first_name values from the employees table where
the last_name is 'Anderson' or the state is 'California' or the employee_id is equal to 50.

Example - With INSERT Statement


Compiled By : Amit Srivastava
The SQL Server OR condition can be used in the INSERT statement.
For example:

INSERT INTO contacts


(contact_id, last_name, first_name)
SELECT employee_id, last_name, first_name
FROM employees
WHERE last_name = 'Smith'
OR employee_id < 10;

This SQL Server OR example would insert into the contacts table, all employee_id, last_name, and first_name records from
the employees table where the last_name is 'Smith' or the employee_id is less than 10.

Example - With UPDATE Statement


The SQL Server OR condition can be used in the UPDATE statement.
For example:

UPDATE employees
SET state = 'Florida'
WHERE employee_id < 1000
OR city = 'Miami';

This SQL Server OR condition example would update all state values in the employees table to 'Florida' where the employee_id is
less than 1000 or the city is 'Miami'.

Example - With DELETE Statement


The SQL Server OR condition can be used in the DELETE statement.
For example:

DELETE FROM employees


WHERE first_name = 'Joanne'
OR first_name = 'Darlene';

This SQL Server OR condition example would delete all employees from the employees table whose first_name is either 'Joanne' or
'Darlene'.

SQL Server: Combining the AND and OR Conditions


This SQL Server tutorial explains how to use the AND condition and the OR condition together in a SQL Server (Transact-SQL)
query with syntax and examples.

Description
The SQL Server (Transact-SQL) AND condition and OR condition can be combined in a SELECT, INSERT, UPDATE, or DELETE
statement.
When combining these conditions, it is important to use parentheses so that the database knows what order to evaluate each
condition. (Just like when you were learning the order of operations in Math class!)

Syntax
The syntax for the AND condition and the OR condition together in SQL Server (Transact-SQL) is:
Compiled By : Amit Srivastava

WHERE condition1
AND condition2
...
OR condition_n;

Parameters or Arguments
condition1, condition2, ... condition_n
The conditions that are evaluated to determine if the records will be selected.

Note

• The SQL Server AND & OR conditions allow you to test multiple conditions.
• Don't forget the order of operation parentheses!

Example - With SELECT Statement


Let's look at an example that combines the AND and OR conditions in a SELECT statement.
For example:

SELECT *
FROM employees
WHERE (last_name = 'Anderson' AND first_name = 'Sarah')
OR (employee_id = 75);

This AND & OR example would return all employees whose last_name is 'Anderson' and first_name is 'Sarah, as well as all
employees whose employee_id is 75. The parentheses determine the order that the AND and OR conditions are evaluated. Just like
you learned in the order of operations in Math class!
The next example takes a look at a more complex statement.
For example:

SELECT employee_id, last_name, first_name


FROM employees
WHERE (last_name = 'Smith')
OR (last_name = 'Anderson AND first_name = 'Sarah')
OR (employee_id > 1000 and state = 'California');

This AND & OR example would return all employee_id, last_name, and first_name values where the last_name is 'Smith' OR
the last_name is 'Anderson' and the first_name is 'Sarah' OR the employee_id is greater than 1000 and the state is 'California'.

Example - With INSERT Statement


This next AND & OR example demonstrates how the AND condition and OR condition can be combined in the INSERT statement.
For example:

INSERT INTO contacts


(last_name, first_name)
SELECT last_name, first_name
FROM employees
WHERE (last_name = 'Johnson' OR 'last_name = 'Anderson')
Compiled By : Amit Srivastava
AND employee_id > 54;

This SQL Server AND and OR example would insert into the contacts table, all last_name and first_name values from
the employees table whose last_name is either 'Johnson' or 'Anderson' and where the employee_id is greater than 54.

Example - With UPDATE Statement


This AND & OR example shows how the AND and OR conditions can be used in the UPDATE statement.
For example:

UPDATE employees
SET last_name = 'TBD'
WHERE employee_id <= 2000
AND (state = 'California' OR state = 'Arizona');

This SQL Server AND & OR condition example would update all last_name values in the employees table to 'TBD' where
the employee_id is less than or equal to 2000 and resides in either the state of 'California' or 'Arizona'.

Example - With DELETE Statement


Finally, this last AND & OR example demonstrates how the AND and OR conditions can be used in the DELETE statement.
For example:

DELETE FROM employees


WHERE state = 'California'
AND (last_name = 'Johnson' OR first_name = 'Joe');

This SQL Server AND and OR condition example would delete all records from the employees table where the state is 'California'
and either the last_name is 'Johnson' or the first_name is 'Joe'.

SQL Server: DISTINCT Clause


This SQL Server tutorial explains how to use the DISTINCT clause in SQL Server (Transact-SQL) with syntax and examples.

Description
The SQL Server (Transact-SQL) DISTINCT clause is used to remove duplicates from the result set. The DISTINCT clause can only
be used with SELECT statements.

Syntax
The syntax for the DISTINCT clause in SQL Server (Transact-SQL) is:

SELECT DISTINCT expressions


FROM tables
[WHERE conditions];

Parameters or Arguments
expressions
The columns or calculations that you wish to retrieve.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Compiled By : Amit Srivastava
Optional. The conditions that must be met for the records to be selected.

Note

• When only one expression is provided in the DISTINCT clause, the query will return the unique values for that expression.
• When more than one expression is provided in the DISTINCT clause, the query will retrieve unique combinations for the
expressions listed.
• In SQL Server, the DISTINCT clause doesn't ignore NULL values. So when using the DISTINCT clause in your SQL
statement, your result set will include NULL as a distinct value.

Example - With Single Expression


Let's look at the simplest SQL Server DISTINCT clause example. We can use the SQL Server DISTINCT clause to return a single
field that removes the duplicates from the result set.
For example:

SELECT DISTINCT last_name


FROM employees
WHERE employee_id >= 50;

This SQL Server DISTINCT example would return all unique last_name values from the employees table where the employee_id is
greater than or equal to 50.

Example - With Multiple Expressions


Let's look at how you might use the SQL Server DISTINCT clause to remove duplicates from more than one field in your SELECT
statement.
For example:

SELECT DISTINCT first_name, last_name


FROM employees
WHERE employee_id >=50
ORDER BY last_name;

This SQL Server DISTINCT clause example would return each unique first_name and last_name combination from
the employees table where the employee_id is greater than or equal to 50. The results are sorted in ascending order by last_name.
In this case, the DISTINCT applies to each field listed after the DISTINCT keyword, and therefore returns distinct combinations.

You might also like