Tag Archives: sql tutorials for beginners

SQL – UNIQUE Key

SQL UNIQUE Key Constraint :

1 . At The Time Of Table Creation :

UNIQUE Key Constraint is used to identify every record uniquely. Multiple Unique Key can be in a sigle table.

SQL – UNIQUE Key Constraint Syntax Example :

Example

CREATE TABLE UserProfile (
ID int(11) NOT NULL,
Name varchar(110) NOT NULL,
Email varchar(100) NOT NULL,
CONSTRAINT USER_EMAIL_UNIQUE_CONSTRAINT UNIQUE (Email)
) ;

Where USER_EMAIL is Constraint’s name you can choose constraint name as per you understanding.

2 .In Existing Table :

Example

ALTER TABLE UserProfile
ADD CONSTRAINT USER_EMAIL_UNIQUE_CONSTRAINT UNIQUE (Email);

Drop UNIQUE Key Constraint :

Example

ALTER TABLE UserProfile
DROP CONSTRAINT USER_EMAIL_UNIQUE_CONSTRAINT;

Note : In Mysql You have to Use Following Query to Drop the Constraint :

Example

ALTER TABLE UserProfile
DROP INDEX USER_EMAIL_UNIQUE_CONSTRAINT;

SQL Joins – INNER JOIN

SQL JOINS

SQL – Joins are used to fetch data collectivly from two or more than two tables. It Selects column values from the two tables & results it as combined data.

SQL Joins (INNER JOIN)

Sql INNER JOIN Selects the data from Both the tables only the matching records from both table.

Create An Order Table Which We will Use for joins.

Order Table Used for JOINS

CREATE TABLE IF NOT EXISTS `Orders` (
`OrderId` int(11) NOT NULL,
`UserId` int(11) NOT NULL,
`OrderItem` varchar(100) NOT NULL,
`Sysdate` datetime NOT NULL
) ;

ALTER TABLE `orders`
ADD PRIMARY KEY (`OrderId`);

INSERT INTO `customersdb`.`orders` (`orderId`, `userId`, `orderItem`, `Sysdate`) VALUES (‘1’, ‘2’, ‘Tees’, ‘2015-03-19 00:00:00’);
INSERT INTO `customersdb`.`orders` (`orderId`, `userId`, `orderItem`, `Sysdate`) VALUES ( ‘2’,’3′, ‘Shoes’, ‘2015-03-20 00:00:00’);
INSERT INTO `customersdb`.`orders` (`orderId`, `userId`, `orderItem`, `Sysdate`) VALUES (‘3′,’5’, ‘Shirt’, ‘2015-03-21 00:00:00’);
INSERT INTO `customersdb`.`orders` (`orderId`, `userId`, `orderItem`, `Sysdate`) VALUES (‘4’, ‘6’, ‘Watch’, ‘2015-03-21 00:00:00’);
INSERT INTO `customersdb`.`orders` (`orderId`, `userId`, `orderItem`, `Sysdate`) VALUES (‘5′,’8’, ‘Ipad’, ‘2015-03-22 00:00:00’);

Now We Have The Following Tables :

Orders Table :

OrderTable
Note : “UserId” In “Orders” Table is the id of the users which is assigned to users in “Users” Table in “ID” column. The Values stored in “UserId” Column are reffered from “Users” Table.

And

Users Table :

tableFull

Simple Join Example Can Be Explained Using The Above Two Tables :

Example

SELECT users.Name,Users.Email,Orders.OrderItem FROM Users JOIN Orders ON (Users.ID= Orders.UserId);

Note : Simple JOIN keyword also refers to the INNER JOIN.

ON – : Condition is key for the joining two tables which related the tables using common columns reffered from the tables..

After Running The Query the following Result will be produced :

SQL Joins results

SQL Between

SQL Between Clause

SQL – Between Clause is used to select the between the two specified range.

SQL Between Clause Syntax

SELECT ColumnName1,ColumnName2… FROM TableName WHERE columnName BETWEEN Range1 AND Range2 ;

Suppose We Have the following Table :

tableFull

Example

SELECT * FROM Users WHERE ID BETWEEN 5 AND 8 ;

Will Produce The Following Result :

Between_clause

SQL – NOT Between Clause Syntax-

NOT BETWEEN Clause selects only those records which does not come in the specified range.

SELECT ColumnName1,ColumnName2… FROM TableName WHERE columnName NOt BETWEEN Range1 AND Range2 ;

Example

SELECT * FROM Users WHERE ID NOT BETWEEN 5 AND 8 ;

Will Produce The Following Result :

SQL Between SQL_NOT_BETWEEN_CLAUSE

SQL In Operator

SQL – In Clause :

SQL In Clause is used to pass multiple values in WHERE condtion .

SQL In CLause Syntax :

SELECT ColumnName1, ColumnName2 FROM TableName WHERE ColumnName IN (value1,value2,value3,value4…valueN);

SQL NOT In CLause Syntax :
SQL NOT selectes the results excluding the spcified value .(values in NOT IN clause).

SELECT ColumnName1, ColumnName2 FROM TableName WHERE ColumnName NOT IN (value1,value2,value3,value4…valueN);


Example

Example

SELECT *FROM Users WHERE ID IN (1,5,7);

Will Produce The Follwoing Result.
SQL_IN_CLAUSE

SQL – Like

SQL Like Clause

Like operator is used to filter the results . Like operator compares the results using the wild cards.

There are two types of wildcards used for the filtering & matching the result.

1. % – (Percent Symbol).
2. _ – (Underscore Symbol).

SQL Like CLause Syntax (Wildcard %)

SELECT columnName1, ColumnName2.. FROM TableName WHERE ColumnName LIKE ‘%Pattern’;

Or

SELECT columnName1, ColumnName2.. FROM TableName WHERE ColumnName LIKE ‘Pattern%’;

or

SELECT columnName1, ColumnName2.. FROM TableName WHERE ColumnName LIKE ‘%Pattern%’;

Explanation :

‘Pattern%’ – : Mathes & finds the pattern where column value starts with the provided pattern (Ex . – ‘%John’ – Will find the records where Name(Column) starts with ‘John’).

‘%Pattern’ – : Mathes & finds the pattern where column value ends with the provided pattern (Ex . – ‘John%’ – Will find the records where Name(Column) ends with ‘John’ ).

‘%Pattern%’ – : Mathes & finds the pattern where pattern find at any place in column value (Ex . – ‘%John%’ – Will find the records where Name(Column) find at any where ).

SQL Like CLause Syntax (Wildcard _ ) –

SELECT columnName1, ColumnName2.. FROM TableName WHERE ColumnName LIKE ‘_Pattern’;

Or

SELECT columnName1, ColumnName2.. FROM TableName WHERE ColumnName LIKE ‘Pattern_’;

or

SELECT columnName1, ColumnName2.. FROM TableName WHERE ColumnName LIKE ‘_Pattern_’;

Explanation :

‘_Pattern’ – : Mathes & finds the pattern where column value has the pattern at second place (Ex . – ‘_J’ – Will match the column value where second value is ‘J’).

‘Pattern_’ – : Mathes & finds the pattern where column value start with the pattern (Ex . – ‘J%’ – Will match the column value where column value starts with ‘J’ ).

‘_Pattern_’ – : Mathes & finds the pattern where pattern where (Ex . – ‘_Jn_’ – Will find the records where 2nd value is ‘J’ and seond last value is ‘n’ ).

Example :

Example

SELECT *FROM Users WHERE Name LIKE ‘J%’;

Will Produce The Follwoing Result.

$like

Example :

Example

SELECT *FROM Users WHERE Name LIKE ‘%i’;

Will Produce The Follwoing Result.

SQL Like

SQL – DELETE

SQL DELETE Query

SQL – DELETE Query is used to delete records(rows) from table.

SQL DELETE Syntax :

DELETE FROM TableName WHERE columnName = someColumnValue;

Suppose We Have Following Data :

tableFull

Example : We want to delete row where id is ‘9’

Example

DELETE FROM Users WHERE ID = ‘9’;

This Will Delete the row where id is ‘9’ . The Table will look Now :

SQL Delete onrowDeleted

SQL – UPDATE

SQL Update Query

SQL – UPDATE Statement is used to update or change the records in table which are existing in the table.

SQL Update Query with Syntax

UPDATE TableName
SET columnName1 = newValue1,
SET columnName2 = newValue2,
SET columnName3 = newValue3
WHERE columnName = someColumnValue;

Suppose We have Following Data :

tableFull

Update Example :

Example

UPDATE USERS SET Name = ‘David Camron’ , City=”NEW LONDON” WHERE Email= ‘david@yahoo.com’;

The Above Query Will Update the row where email is ‘david@yahoo.com’ the update data will be as :

SQL UPDATE Query

SQL ORDER BY

SQL ORDER BY Clause

ORDER BY Clause is used to sort the data on the basis of columns in ascending or descing order.

SQL ORDER BY Syntax

:

SELECT columnName1, columnName2, columnName3
from TableName ORDER By columnName1 , columnName2 ASC | DESC

Note : If We do not use the ASC or DESC keyword the Default order ASC is considered.

Suppose We Have The Following Data :

tableFull

ORDER BY DESC Example :

Example

SELECT * FROM `Users` ORDER BY ID Desc;

The Above Query Will Sort the result in descening order by Id. The Query Produces the result as :
sortIdDec

ORDER BY ASC Example :

Example

SELECT * FROM `Users` ORDER BY ID ASC;

The Above Query Will Sort the result in ascending order by Id. The Query Produces the result as :

sql order by sortAscid

ORDER BY Multiple Columns Example :

Example

SELECT * FROM `Users` ORDER BY Name, Email ASC;

The Above Query Will Sort the result in ascending order by Name & Email. The Query Produces the result as :

sortByMultipleCOl

SQL – AND & OR

SQL – AND & OR Clauses

SQL – AND & OR Explained

AND Clause :

And Clause displays the results where both the conditions are fullfilled.

OR Clause :

OR Clause displays the results where atleast one conditions is fullfilled.

Suppose we have following data :

tableFull

AND Clause Example :

Example

SELECT * FROM Users WHERE (City=”DELHI” and Name=’Riya’);

Where [City=”DELHI” and Name=’Riya’] Both Conditions are satisfied.

This Will Produce The Result As :

SQL - AND & OR

OR Clause Example :

Example

SELECT * FROM Users WHERE (City=”DELHI” OR Name=’Riya’);

Where [City=”DELHI” OR Name=’Riya’] Either condition is satisfied.

This Will Produce The Result As :

SQL - AND & OR

AND & OR Clause Together Example :

This will select the result where city is (“delhi” or name is “riya” )[produces two rows]
with the condition followed by name “linga” [Selects one from the two rows where name is “linga”]

Example

SELECT * FROM Users WHERE (City=”DELHI” OR Name=’Riya’) AND Name=’linga’;

This Will Produce The Result As :

SQL - AND & OR