Posts tagged as:

Syntax

SQL Like Statement (or) Condition is basically used for checking if a particular charter string appears in a given string or not. We can use wildcard symbols in the where clause and also in the CASE Statements for pattern matching. Because of this, the SQL Like operator is more powerful than using the equal to (=) or not equal to (! =) symbols for pattern matching and more generically for string comparison. The basic point that we need to keep in mind while using the SQL Like operator is; the result set returned by it is a Boolean value, meaning a TRUE or FALSE.

SQL Like Syntax

The basic syntax for SQL Like is shown below.

match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]

SQL Like – Wildcards

The following are the wildcards that can be used with the SQL like condition – %( Percentage symbol), _ (Underscore), [] (Square Parenthesis), ^ (Caret symbol); will show each of them with examples…

Firstly, let us create a temporary table and insert some data into it and see how we can use the SQL Like operator.

CREATE TABLE #SQL_Like (NameID int, ContactName nvarchar(50))

 INSERT INTO #SQL_Like  Values (1,'Amy')
 INSERT INTO #SQL_Like  Values (2,'Anna')
 INSERT INTO #SQL_Like  Values (3,'Brenda')
 INSERT INTO #SQL_Like  Values (4,'Catherine')
 INSERT INTO #SQL_Like  Values (5,'Daniel')
 INSERT INTO #SQL_Like  Values (6,'Emilio')
 INSERT INTO #SQL_Like  Values (7,'Edna')
 INSERT INTO #SQL_Like  Values (8,'Frances')
 INSERT INTO #SQL_Like  Values (9,'Gustavo')
 INSERT INTO #SQL_Like  Values (10,'Hannah')
 INSERT INTO #SQL_Like  Values (11,'Ian')
 INSERT INTO #SQL_Like  Values (12,'John')

Examples for using SQL Like Condition

The most basic form to start with, suppose from the above table if we want to get all the names starting with “A” we can use the below query.

SELECT * FROM #SQL_Like  WHERE ContactName Like 'A%'

The “%” percentage wild card is used for doing a pattern match of any string of zero or more characters. And this is the result that we would get once we are done with executing the above line of T-SQL.

NameID ContactName

1          Amy

2          Anna

If we want to get a list of names that end with “A”, we can use the same wild card, but we will have to put it in the front and the letter that we want to search for at the end, shown like the below.

SELECT * FROM #SQL_Like  WHERE ContactName Like '%A'

And the result for the same would be

NameID ContactName

2          Anna

3          Brenda

7          Edna

Suppose, if there is a requirement where we know that we need to look into the names, in whose name the 2nd letter is “A”, then we have to write a query like the below, the “_” underscore wild card symbol denotes a single character.

SELECT * FROM #SQL_Like  WHERE ContactName Like '_A%'

And the result for the same would be

NameID ContactName

4          Catherine

5          Daniel

10         Hannah

11         Ian

Say, if we want to search for a name, which starts with “A” and in which the second alphabet is something between “A” and “M”, then our result has to be the first name that we had inserted, i.e “Amy”. For this we actually use the “[ ]” square brackets, they are used for searching any single character within the specified range ([a-g]) or set ([abcdefg]).

SELECT * FROM #SQL_Like  WHERE ContactName Like A[A-M]%'

Using SQL NOT Like

Till now we have seen how to directly use the “Like operator”. Now we shall take up an example where we will add “Not” in front of our “Like”. For this, the example that we can take is, say we need a list of all the name’s that do not have the alphabet “A” in them, then our query would resemble the below.

SELECT * FROM #SQL_Like  WHERE ContactName NOT Like '%A%'

Using SQL Like Escape Clause

Everything seems to be fine till now, so, let’s think like this, the wild card symbols are really cool, but what if I need to look into a string for those wild card character’s, puzzled!!!

For this we have these escape clause J. Check the syntax at the beginning of the article
In the below example, my escape character is “!”, so I am actually trying to search for John%, of course practically no names will exist in this way unless there is a type!!! This is just for the sake of taking an example and looking at on how to use it

SELECT * FROM #SQL_Like  WHERE ContactName LIKE '%John!%%' ESCAPE '!'

Let’s take one more example, here we want to look for the underscore symbol, and that’s a wildcard symbol, so decide to make use of the Escape clause over here as well.

SELECT * FROM #SQL_Like  WHERE ContactName LIKE '%John!_%' ESCAPE '!' 

The basic thing over here is that we need to look for a symbol that can be used in the escape clause, means something, that does not exist in our string.

Using SQL Like with Variables and Expressions
We can use the SQL LIKE operator with Variables and Expressions, they can combination of alphabets, alphabets and alpha-numeric, a query with scalar output, a varchar or nvarchar type local variable. But, remember one thing, at the end, everything would be looked at as a string(Not char) by the sql server.

The below is a self-explanatory code snippet. Firstly, we are declaring a variable, then we are setting it to a string “la” and then we are searching for it in the names. In the first, example we are trying to search for characters in the start of the name and in the second example we are trying to search for the characters in the end of the name

DECLARE @Name nvarchar(2)
 SET @Name ='Ia'
 SELECT * FROM #SQL_Like  WHERE ContactName Like @Name +'%'

DECLARE @Name nvarchar(2)
 SET @Name ='N'
 SELECT * FROM #SQL_Like  WHERE ContactName Like '%'+ @Name

Using SQL Like with Case Statement
As stated earlier, the sql like condition returns a true or false, so we can use this in multiple scenarios in conjunction with a CASE statement. Here in the below code snippet we are actually trying to find all the names that start with A, B. We can also construct similar thing where the condition can equal to 0.

SELECT * FROM #SQL_Like
 WHERE CASE
 WHEN ContactName LIKE 'A%' THEN 1
 WHEN ContactName LIKE 'B%' THEN 1
 END = 1

{ Comments on this entry are closed }

What is the difference between union and union all in sql server?

The UNION operator joins result sets from tow or more SELECT statements. The basic Syntax of using “UNION” operator is

SELECT Column List FROM Table1

UNION [ALL]

SELECT Column List FROM Table2 
  • ALL Clause in the query is optional

A couple of things that need to be kept in mind while using the “SQL UNION” operator are

  1. The tables should have same data types for the columns
  2. The Order in which we get the columns should be same
  3. If we want to enforce Sort order for the final result set, we should have a “Order By” Clause on the last “SQL SELECT Statement” that we are going to have in our query.

One main difference between using the “ UNION ALL” clause and not using it is, when we use the “UNION” without the “ALL” Clause we get distinct records in the overall result set, but when we use the “UNION ALL” we get the complete set of results with out the removal of any duplicates.

So, based on this we can say that, UNION for SQL Server is just concatenation whereas UNION ALL has one more operation of identifying and removing the duplicates.

Now, let’s take an example to see what is happening???

Let’s go ahead and create two tables for our learning purpose, Table1 with a single int column and also table2 with single int column and insert some records with duplicates in them

Table 1

CREATE TABLE Table1(Col1 int)

INSERT INTO Table1 Values (1)

INSERT INTO Table1 Values (1)

INSERT INTO Table1 Values (2)

INSERT INTO Table1 Values (3)

INSERT INTO Table1 Values (3)

INSERT INTO Table1 Values (4)

Table 2

CREATE TABLE Table2(Col1 int)

 INSERT INTO Table2 Values (4)

INSERT INTO Table2 Values (5)

INSERT INTO Table2 Values (5)

INSERT INTO Table2 Values (6)

INSERT INTO Table2 Values (7)

INSERT INTO Table2 Values (8)

So, now let’s go and write the UNION queries on these tables and see what the result set is and also what is the Execution Plan for these queries to get better understanding of these operators.

SELECT Col1 FROM Table1

UNION

SELECT Col1 FROM Table2

SQL UNION

SELECT Col1 FROM Table1

UNION ALL

SELECT Col1 FROM Table2

SQL UNION ALL

If you look at the operator that is used to unite the two sets for a UNION ALL, you’ll see it’s a Concatenation operator, combining two sets of data without any further thought of whether rows have previously been seen.

For a UNION, You can see a Distinct Sort as it makes sure it doesn’t return the same row twice.

So, now coming to the point on which one is better, from the above we can say that if duplicates are not an issue then definitely we should go for UNION ALL, but we need to really look at what our query needs to return and make sure users queries are answered correctly.

So, I think here I have pointed out nearly all the difference between union and union all in sql server.

If you have liked the article and want to get the articles (or) new posts at sql like, subscribe to articles through email by entering your email address in the top right and verifying the same. If you have any comments, then the below form is for you, go ahead!!!

{ Comments on this entry are closed }

SQL Select Statement

January 27, 2010

in SQL Basics

Out of all the statements in SQL (Structured Query Language), the Select statement is by far the most used once.

The select statement is used to retrieve data from tables/view/combination of tables and views in a database. The result thus generated using this statement is used for display to users through GUI, for reporting purpose, for processing the data and etc.

Such a result generated using a Select Statement is called a Result – Set.

The basic Syntax for a Select Statement is (One thing to be noted over he is SQL is not case sensitive)

SELECT Column_List FROM Table_Name

The <Table_Name> gets more prefixes depending on the Environment we have to select the data from, it can be also written as a three part identifies as [Database Name].[Schema Name].[Table Name]

Here is an example making use of the database AdventureWorks which is available from the site http://www.codeplex.com for download.

Use AdventureWorks
Go
SELECT EmployeeID,NationalIDNumber,Title,ManagerID FROM HumanResources.Employee

The above sql select statement selects four columns from the table Emplyee residing in the schema HumanResources.

EmployeeIDNationalIDNumberTitleManagerID
114417807Production Technician - WC6016
2253022876Marketing Assistant6
3509647174Engineering Manager12
4112457891Senior Tool Designer3
5480168528Tool Designer263

Now let us see one more basic example, say instead of a few columns we want to select all the columns in a table, for that we use the asterisk symbol “*”.
When we are going to write it, It’s going to take a form of the below

SELECT * FROM [Database Name].[Schema Name].[Table Name]

Here it is

Use AdventureWorks
Go
SELECT * FROM HumanResources.Employe

That’s it for not, will further write on these basics in the comin articles.
If you have like it and want to get the articles (or) new post at sql like, subscribe to articles through email by entering your email address in the top right and verifying the same.

 if you have any comments, then the below form is for you, go ahead!!!

{ Comments on this entry are closed }