You are on page 1of 29

1.

INTRODUCTION
SQL tutorial gives unique learning on Structured Query Language and it helps to
make practice on SQL commands which provides immediate results. SQL is a language
of database, it includes database creation, deletion, fetching rows and modifying rows
etc.
SQL is an ANSI (American National Standards Institute) standard but there are many
different versions of the SQL language.

What is SQL?

SQL is Structured Query Language, which is a computer language for storing,


manipulating and retrieving data stored in relational database.

SQL is the standard language for Relation Database System. All relational database
management systems like MySQL, MS Access, Oracle, Sybase, Informix, postgres and
SQL Server use SQL as standard database language.

Also, they are using different dialects, such as:

● MS SQL Server using T-SQL,

● Oracle using PL/SQL,

● MS Access version of SQL is called JET SQL (native format) etc.

Why SQL?

● Allows users to access data in relational database management systems.

● Allows users to describe the data.

● Allows users to define the data in database and manipulate that data.

● Allows to embed within other languages using SQL modules, libraries & pre-
compilers.

● Allows users to create and drop databases and tables.

● Allows users to create view, stored procedure, functions in a database.

● Allows users to set permissions on tables, procedures, and views

1|Page
History:

● 1970 -- Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational
databases. He described a relational model for database.

● 1974 -- Structured Query Language appeared.

● 1978 -- IBM worked to develop Codd's ideas and released a product named
System/R.

● 1986 -- IBM developed the first prototype of relational database and


standardized by ANSI. The first relational database was released by Relational
Software and its later becoming Oracle.

SQL Process:
When you are executing an SQL command for any RDBMS, the system determines
the best way to carry out your request and SQL engine figures out how to interpret the
task.
There are various components included in the process. These components are Query
Dispatcher, Optimization Engines, Classic Query Engine and SQL Query Engine, etc.
Classic query engine handles all non-SQL queries but SQL query engine won't handle
logical files.
Following is a simple diagram showing SQL Architecture:

2|Page
2.SQL COMMANDS
The standard SQL commands to interact with relational databases are CREATE,
SELECT, INSERT, UPDATE, DELETE and DROP. These commands can be
classified into groups based on their nature:

DDL - Data Definition Language:


Command Description
CREATE Creates a new table, a view of a table, or other object in database
ALTER Modifies an existing database object, such as a table.
DROP Deletes an entire table, a view of a table or other object in the database.

DML - Data Manipulation Language:

Command Description
SELECT Retrieves certain records from one or more tables
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records

DCL - Data Control Language:


Command Description
GRANT Gives a privilege to user
REVOKE Takes back privileges granted from user

DATA:
● Basically data is a raw material when we process it,it will become useful
information.

● Data is a set of collection of useful information.

● Data is a fact which is realated to an entity as an object.


DATABASE:
● Database is a systematic collection of data where we manage the data.

3|Page
3.TYPES OF DATABASES
RDBMS:

RDBMS stands for Relational Database Management System. RDBMS is the basis
for SQL and for all modern database systems like MS SQL Server, IBM DB2, Oracle,
MySQL, and Microsoft Access.
A Relational database management system (RDBMS) is a database management
system (DBMS) that is based on the relational model as introduced by E. F. Codd.

● RDBMS defines relationship in the form of table.

● Table consists of rows and columns.

● Rows are also called as records or tuple.

● Columns are also called as attributes or fields.

● The intersection of rows and columns is called as cell.

● Table is also called as entity, relation or object.


DBMS:
DBMS stands for Database Management System.Database is the systematic collection
of data where we can store and retrieve the data.

Data Integrity:

● Data integrity is used to restrict the invalid data into a table.

● Data integrity can be achieved by providing data type and constraints.

Data type:

The type of data entering into a column in a table is referred as data type.

Types of data types:

1. Number
2. Char/Var Char
3. Date

1. Number:
Number data type is used to enter the numeric value or the numeric data into
column in a table.

4|Page
2. Char/Var char:
In CHAR if we vary the size of character, the space won’t vary.

3. Date:
Date data type is used to enter a valid date into a column in a table

Constrains:
Constrains are conditions which are provided through a column in a table to restrict
invalid data.

Types of constrains:

1. Not null
2. Unique
3. Primary key
4. Foreign key
5. Check

PRIMARY KEY:
The PRIMARY KEY constraint uniquely identifies each record in a database table.

Primary keys must contain unique values. It is normal to just use running numbers, like
1, 2, 3, 4, 5, … as values in Primary Key column. It is a good idea to let the system
handle this for you by specifying that the Primary Key should be set to identity(1,1).
IDENTITY(1,1) means the first value will be 1 and then it will increment by 1.

Each table should have a primary key, and each table can have only ONE primary key.

If we take a closer look at the CUSTOMER table created earlier:

CREATE TABLE [CUSTOMER] (


CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE,
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
AreaCode int NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL,
)

As you see we use the “Primary Key” keyword to specify that a column should be the
Primary Key.

5|Page
FOREIGN KEY:
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.

Example:

SCHOOL:

CREATE TABLE SCHOOL


(
SchoolId int IDENTITY(1,1) PRIMARY KEY,
SchoolName varchar(50) NOT NULL UNIQUE,
Description varchar(1000) NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL, PostCode varchar(50) NULL,
PostAddress varchar(50) NULL,
)

CLASS:

CREATE TABLE CLASS


(
ClassId int IDENTITY(1,1) PRIMARY KEY,
SchoolId int NOT NULL FOREIGN KEY REFERENCES
SCHOOL (SchoolId),
ClassName varchar(50) NOT NULL UNIQUE,
Description varchar(1000) NULL,
)

NOT NULL:
The NOT NULL constraint enforces a column to NOT accept NULL values.

The NOT NULL constraint enforces a field to always contain a value. This means that
you cannot insert a new record, or update a record without adding a value to this field.

If we take a closer look at the CUSTOMER table created earlier:

CREATE TABLE [CUSTOMER]


(
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE,
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
AreaCode int NULL, Address varchar(50) NULL,
Phone varchar(50) NULL,
)

6|Page
UNIQUE:
The UNIQUE constraint uniquely identifies each record in a database table. The
UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for
a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.

Note! You can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.

If we take a closer look at the CUSTOMER table created earlier:

CREATE TABLE [CUSTOMER]


(
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE,
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
AreaCode int NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL,
)

CHECK:
The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a single column it allows only certain values for
this column.

If you define a CHECK constraint on a table it can limit the values in certain columns
based on values in other columns in the row.

Example:

CREATE TABLE [CUSTOMER](


CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE
CHECK(CustomerNumber>0),
FirstName varchar(50) NOT NULL,
AreaCode int NULL, Address varchar(50) NULL,
Phone varchar(50) NULL,
)

7|Page
DEFAULT:
The DEFAULT constraint is used to insert a default value into a column.

The default value will be added to all new records, if no other value is specified.

Example:

CREATE TABLE [CUSTOMER]


(
CustomerId int IDENTITY(1,1) PRIMARY KEY,
CustomerNumber int NOT NULL UNIQUE,
LastName varchar(50) NOT NULL,
FirstName varchar(50) NOT NULL,
Country varchar(20) DEFAULT 'Norway', AreaCode int NULL,
Address varchar(50) NULL,
Phone varchar(50) NULL,
)

8|Page
4.SQL SYNTAX

SQL is followed by unique set of rules and guidelines called Syntax. This tutorial gives
you a quick start with SQL by listing all the basic SQL Syntax:

All the SQL statements start with any of the keywords like SELECT, INSERT,
UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements
end with a semicolon (;).

SQL SELECT Statement:

SELECT column1, column2....columnN FROM table_name;

SQL DISTINCT Clause:

SELECT DISTINCTcolumn1,column2....columnN FROM table_name;

SQL WHERE Clause:

SELECT column1, column2....columnN FROM table_name WHERE


CONDITION;

SQL AND/OR Clause:

SELECT column1, column2....columnN FROM table_name


WHERE CONDITION-1 {AND|OR} CONDITION-2;

SQL IN Clause:

SELECT column1, column2....columnN FROM table_name


WHERE column_name IN (val-1, val-2,...val-N);

SQL BETWEEN Clause:

SELECT column1, column2....columnN


FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;

SQL Like Clause:

SELECT column1, column2....columnN


FROM table_name
WHERE column_name LIKE { PATTERN };

9|Page
SQL ORDER BY Clause:

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};

SQL GROUP BY Clause:

SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;

SQL COUNT Clause:

SELECT COUNT(column_name) FROM table_name WHERE CONDITION;

SQL HAVING Clause:

SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);

SQL CREATE TABLE Statement:

CREATE TABLE table_name( column1 datatype, column2 datatype, column3


datatype,
..... columnN datatype,
PRIMARY KEY( one or more columns ) );

SQL DROP TABLE Statement:

DROP TABLE table_name;

SQL CREATE INDEX Statement :

CREATE UNIQUE INDEX index_name


ON table_name ( column1, column2,...columnN);

SQL DROP INDEX Statement :

ALTER TABLE table_name


DROP INDEX index_name;

10 | P a g e
SQL DESC Statement :

DESC table_name;

SQL TRUNCATE TABLE Statement:

TRUNCATE TABLE table_name;

SQL ALTER TABLE Statement:

ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};

SQL ALTER TABLE Statement (Rename) :

ALTER TABLE table_name RENAME TO new_table_name;

SQL INSERT INTO Statement:

INSERT INTO table_name( column1, column2....columnN) VALUES ( value1,


value2....valueN);

SQL UPDATE Statement:

UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN [ WHERE
CONDITION ];

SQL DELETE Statement:

DELETE FROM table_name WHERE {CONDITION};

SQL CREATE DATABASE Statement:

CREATE DATABASE database_name;

SQL DROP DATABASE Statement:

DROP DATABASE database_name;

SQL USE Statement:

USE DATABASE database_name;

SQL COMMIT Statement:

COMMIT;

11 | P a g e
5.SQL - OPERATORS
SQL Arithmetic Operators:

Assume variable a holds 10 and variable b holds 20, then:

SQL Comparison Operators:

Assume variable a holds 10 and variable b holds 20, then:

Operator Description Example

Checks if the values of two operands are equal or not, if yes (a = b) is


=
then condition becomes true. not true.

Checks if the values of two operands are equal or not, if values (a != b) is


!=
are not equal then condition becomes true. true.

Checks if the values of two operands are equal or not, if values (a <> b) is
<>
are not equal then condition becomes true. true.

Checks if the value of left operand is greater than the value of (a > b) is
>
right operand, if yes then condition becomes true. not true.

Checks if the value of left operand is less than the value of right (a < b) is
<
operand, if yes then condition becomes true. true.

Checks if the value of left operand is greater than or equal to (a >= b) is


>=
the value of right operand, if yes then condition becomes true. not true.

Checks if the value of left operand is less than or equal to the (a <= b) is
<=
value of right operand, if yes then condition becomes true. true.

Checks if the value of left operand is not less than the value of (a !< b) is
!<
right operand, if yes then condition becomes true. false.

12 | P a g e
SQL Logical Operators:

Here is a list of all the logical operators available in SQL.

Operator Description

The ALL operator is used to compare a value to all values in another value
ALL
set.

The AND operator allows the existence of multiple conditions in an SQL


AND
statement's WHERE clause.

The ANY operator is used to compare a value to any applicable value in


ANY
the list according to the condition.

The BETWEEN operator is used to search for values that are within a set
BETWEEN
of values, given the minimum value and the maximum value.

The EXISTS operator is used to search for the presence of a row in a


EXISTS
specified table that meets certain criteria.

The IN operator is used to compare a value to a list of literal values that


IN
have been specified.

The LIKE operator is used to compare a value to similar values using


LIKE
wildcard operators.

The NOT operator reverses the meaning of the logical operator with
NOT which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This
is a negate operator.

The OR operator is used to combine multiple conditions in an SQL


OR
statement's WHERE clause.

IS NULL The NULL operator is used to compare a value with a NULL value.

The UNIQUE operator searches every row of a specified table for


UNIQUE
uniqueness (no duplicates).

13 | P a g e
6.FUNCTIONS
With SQL and SQL Server you can use lots of built-in functions or you may create your
own functions. Here we will learn to use some of the most used built-in functions and
in addition we will create our own function.
Types of function:

● Built- in function

● User-defined function

Built-in Functions::

SQL has many built-in functions for performing calculations on data.

We have 2 categories of functions, namely aggregate functions and scalar functions.


Aggregate functions return a single value, calculated from values in a column, while
scalar functions return a single value, based on the input value.

Types of built-in function:

● Single-row function
● Multi-row function

Aggregate functions - examples:

• AVG() - Returns the average value


• STDEV() - Returns the standard deviation value
• COUNT() - Returns the number of rows
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
Scalar functions - examples:

• UPPER() - Converts a field to upper case


• LOWER() - Converts a field to lower case
• LEN() - Returns the length of a text field

14 | P a g e
• ROUND() - Rounds a numeric field to the number of decimals specified
• GETDATE() - Returns the current system date and time
• etc.
String Functions:
Here are some useful functions used to manipulate with strings in SQL Server.

• CHAR
• CHARINDEX
• REPLACE
• SUBSTRING
• LEN
• REVERSE
• LEFT
• RIGHT
• LOWER
• UPPER
• LTRIM
• RTRIM
Date and Time Functions:

Here are some useful Date and Time functions in SQL Server.

• DATEPART

• GETDATE

• DATEADD

• DATEDIFF

15 | P a g e
• DAY

• MONTH

• YEAR

• ISDATE

Mathematics and Statistics Functions:


Here are some useful functions for mathematics and statistics in SQL Server:

• COUNT

• MIN,MAX

• COS, SIN, TAN

• SQRT

• STDEV

• MEAN

• AVG

AVG():

The AVG() function returns the average value of a numeric column. Syntax: SELECT
AVG(column_name) FROM table_name.

The HAVING Clause:

The HAVING clause was added to SQL because the WHERE keyword could not be
used with aggregate functions.

Syntax:

SELECT column_name, aggregate_function(column_name) FROM table_name


WHERE column_name operator value GROUP BY column_name HAVING
aggregate_function(column_name) operator value

User-defined Functions:

IN SQL, we may also create our own functions, so-called user-defined functions.

A user-defined function is a routine that accepts parameters, performs an action, such


as a complex calculation, and returns the result of that action as a value. The return
value can either be a scalar (single) value or a table. Use this statement to create a
reusable routine that can be used in other queries.

16 | P a g e
In SQL databases, a user-defined function provides a mechanism for extending the
functionality of the database server by adding a function that can be evaluated in SQL
statements. The SQL standard distinguishes between scalar and table functions. A
scalar function returns only a single value (or NULL), whereas a table function returns
a (relational) table comprising zero or more rows, each row with one or more columns.

Stored Procedures vs. Functions:


•Only functions can return a value (using the RETURN keyword).

• Stored procedures can use RETURN keyword but without any value being
passed[1].

• Functions could be used in SELECT statements, provided they don’t do any


data manipulation and also should not have any OUT or IN OUT parameters.

• Functions must return a value, but for stored procedures this is not
compulsory. • A function can have only IN parameters, while stored procedures
may have OUT or IN OUT parameters.

• A function is a subprogram written to perform certain computations and return


a single value.

• A stored procedure is a subprogram written to perform a set of actions, and


can return multiple values using the OUT parameter or return no value at all.
User-defined functions in SQL are declared using the CREATE FUNCTION
statement. When we have created the function, we can use the function the
same way we use built-in functions.

SQL FORMAT FUNCTION( ):


The FORMAT() function is used to format how a field is to be displayed.

SQL FORMAT() Syntax:


SELECT FORMAT(column_name,format) FROM table_name;
Parameter Description

column_name Required. The field to be formatted.

format Required. Specifies the format.

Example With Demo Database :


In this tutorial we will use the well-known Northwind sample database. Below is a
selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes x 20 18
bags

17 | P a g e
2 Chang 1 1 24 - 12 oz 19
bottles
3 Aniseed Syrup 1 2 12 - 550 ml 10
bottles
4 Chef Anton's Cajun 2 2 48 - 6 oz jars 21.35
Seasoning
5 Chef Anton's Gumbo 2 2 36
Mix

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName Country


1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y Ana Trujillo Mexico


helados
3 Antonio Moreno Taquería Antonio Moreno Mexico

Notice that the "CustomerID" column in the "Orders" table refers to the
"CustomerID" in the "Customers" table. The relationship between the two tables
above is the "CustomerID" column.

Then, we can create the following SQL statement (that contains an INNER JOIN),
that selects records that have matching values in both tables:

Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN
Customers ON Orders.CustomerID=Customers.Customer;

and it will produce something like this:

OrderID CustomerName OrderDate

10308 Ana Trujillo Emparedados y helados 9/18/1996

10365 Antonio Moreno Taquería 11/27/1996

10383 Around the Horn 12/16/1996

10355 Around the Horn 11/15/1996


NOW FUNCTION( ):
Look at the following "Products" table:

18 | P a g e
P_Id ProductName UnitPrice UnitsInStock UnitsOnOrder

1 Jarlsberg 10.45 16 15

2 Mascarpone 32.56 23

3 Gorgonzola 15.67 9 20

Suppose that the "UnitsOnOrder" column is optional, and may contain NULL
values. We have the following SELECT statement:

SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder) FROM Products

In the example above, if any of the "UnitsOnOrder" values are NULL, the result is
NULL. Microsoft's ISNULL() function is used to specify how we want to treat NULL
values.

The NVL(), IFNULL(), and COALESCE() functions can also be used to achieve the
same result.

In this case we want NULL values to be zero.

Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because


ISNULL() returns a zero if the value is NULL:

19 | P a g e
7.JOINS
Different types of joins:

Here are the different types of the JOINs in SQL:


● (INNER) JOIN: Returns records that have matching values in both tables
● LEFT (OUTER) JOIN: Return all records from the left table, and the matched
records from the right table.
● RIGHT (OUTER) JOIN: Return all records from the right table, and the matched
records from the left table
● FULL (OUTER) JOIN: Return all records when there is a match in either left or
right table

Inner join keyword:

The INNER JOIN keyword selects records that have matching values in both tables.

20 | P a g e
Demo Database

In this tutorial we will use the well-known Northwind sample database.


Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

And a selection from the "Customers" table:

Customer CustomerNa ContactNa Address City PostalCo Count


ID me me de ry
1 Alfreds Maria Obere Str. Berlin 12209 Germa
Futterkiste Anders 57 ny

2 Ana Ana Trujillo Avda. de Méxi 05021 Mexico


Trujillo la co
Empareda Constituc D.F.
dos y ión 2222
helados
3 Antonio Anto Matade Méxi 05023 Mexico
Moreno nio ros co
Taquería Mor 2312 D.F.
eno

21 | P a g e
8.Auto-increment field

Auto-increment allows a unique number to be generated automatically when a new


record is inserted into a table.

Often this is the primary key field that we would like to be created automatically
every time a new record is inserted.

The following SQL statement defines the "ID" column to be an auto-increment


primary key field in the "Persons" table:

CREATE TABLE Persons (

ID int NOT NULL AUTO_INCREMENT,

LastName varchar(255) NOT


NULL, FirstName
varchar(255),

Age int,

PRIMARY KEY (ID)

);

MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment


feature.

By default, the starting value for AUTO_INCREMENT is 1, and it will increment


by 1 for each new record.

To let the AUTO_INCREMENT sequence start with another value, use the
following SQL statemen To insert a new record into the "Persons" table, we will
NOT have to specify a value for the "ID" column (a unique value will be added
automatically):

The SQL statement above would insert a new record into the "Persons" table. The
"ID" column would be assigned a unique value. The "FirstName" column would be
set to "Lars" and the "LastName" column would be set to "Monsen".

22 | P a g e
9.SQL VIEW

SQL CREATE VIEW:


In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present
the data as if the data were coming from one single table.

CREATE VIEW Syntax:


CREATE VIEW view_name AS SELECT column1, column2, ... FROM table_name
WHERE condition;

SQL CREATE VIEW Examples:


If you have the Northwind database you can see that it has several views installed by
default.

The view "Current Product List" lists all active products (products that are not
discontinued) from the "Products" table. The view is created with the following
SQL:

CREATE VIEW [Current Product List] AS SELECT ProductID, ProductName


FROM Products WHERE Discontinued = No;

Then, we can query the view as follows:

SELECT * FROM [Current Product List];

Another view in the Northwind sample database selects every product in the "Products"
table with a unit price higher than the average unit price:

CREATE VIEW [Products Above Average Price] AS SELECT ProductName,


UnitPrice FROM Products WHERE UnitPrice > (SELECT AVG(UnitPrice)
FROM Products);

We can query the view above as follows:

SELECT * FROM [Products Above Average Price];

23 | P a g e
10.SQL Expressions

An expression is a combination of one or more values, operators, and SQL functions


that evaluate to a value.

SQL EXPRESSIONs are like formulas and they are written in query language. You
can also use them to query the database for specific set of data.

Syntax:
Consider the basic syntax of the SELECT statement as follows:

SELECT column1, column2, columnN FROM table_name WHERE


[CONDITION|EXPRESSION];

There are different types of SQL expressions, which are mentioned below:

SQL - Boolean Expressions:


SQL Boolean Expressions fetch the data on the basis of matching single value.
Following is the syntax:

SELECT column1, column2, columnN FROM table_name WHERE SINGLE


VALUE MATCHTING EXPRESSION;

Consider the CUSTOMERS table having the following records:

Here is simple example showing usage of SQL Boolean Expressions:

SQL - Numeric Expression:


This expression is used to perform any mathematical operation in any query.Following
is the syntax:

24 | P a g e
SELECT numerical_expression as OPERATION_NAME [FROM table_name WHERE
CONDITION] ;

Here numerical_expression is used for mathematical expression or any formula.


Following is a simple examples showing usage of SQL Numeric Expressions:

There are several built-in functions like avg(), sum(), count(), etc., to perform what is
known as aggregate data calculations against a table or a specific table column.

SQL - Date Expressions:


Date Expressions return current system date and time values:

25 | P a g e
11.SQL WHERE Clause
The SQL WHERE clause is used to specify a condition while fetching the data from
single table or joining with multiple tables.

If the given condition is satisfied, then only it returns specific value from the table.
You would use WHERE clause to filter the records and fetching only necessary
records.

The WHERE clause is not only used in SELECT statement, but it is also used in
UPDATE, DELETE statement, etc., which we would examine in subsequent chapters.

Syntax:
The basic syntax of SELECT statement with WHERE clause is as follows:

SELECT column1, column2, columnN FROM table_name WHERE [condition]

You can specify a condition using comparison or logical operators like >, <, =, LIKE,
NOT etc. Below examples would make this concept clear.

Example:
Consider the CUSTOMERS table having the following records:

Following is an example, which would fetch ID, Name and Salary fields from the
CUSTOMERS table where salary is greater than 2000:

SELECT ID, NAME, SALARY FROM CUSTOMERS WHERE SALARY > 2000;

This would produce the following result

26 | P a g e
12.SQL INJECTION
SQL injection is a technique where malicious users can inject SQL commands into
an SQL statement, via web page input.

Injected SQL commands can alter SQL statement and compromise the security of a
web application.

SQL Injection Based on 1=1 is Always True


Look at the example above, one more time.

Let's say that the original purpose of the code was to create an SQL statement to
select a user with a given user id.

If there is nothing to prevent a user from entering "wrong" input, the user can enter
some "smart" input like this:

105 or 1=1

UserId:
SELECT * FROM Users WHERE UserId = 105 or 1=1;

The SQL above is valid. It will return all rows from the table Users, since WHERE
1=1

is always true.

Does the example above seem dangerous? What if the Users table contains names and
passwords?

The SQL statement above is much the same as this:

SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;

A smart hacker might get access to all the user names and passwords in a database by
simply inserting 105 or 1=1 into the input box.

SQL Injection Based on “”=”” is Always True

Here is a common construction, used to verify user login to a web


site:

27 | P a g e
Server Code
uName = getRequestString("UserName"); uPass = getRequestString("UserPass");

sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' +
uPass + '"'

Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"

A smart hacker might get access to user names and passwords in a database by simply
inserting " or ""=" into the user name or password text box:

User Name: “or””=”

Password: “or””=”

The code at the server will create a valid SQL statement like this:

Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""

The result SQL is valid. It will return all rows from the table Users, since WHERE
""=""

is always true.

SQL HOSTING:
If you want your web site to be able to store and retrieve data from a database, your
web server should have access to a database-system that uses the SQL language.

If your web server is hosted by an Internet Service Provider (ISP), you will have to
look for SQL hosting plans.

The most common SQL hosting databases are MS SQL Server, Oracle, MySQL, and
MS Access.

MY SQL Server

Microsoft's SQL Server is a popular database software for database-driven web


sites with high traffic.

SQL Server is a very powerful, robust and full featured SQL database system.

Oracle
Oracle is also a popular database software for database-driven web sites with high
traffic.

28 | P a g e
13.References
My Blog: https://www.halvorsen.blog

Microsoft official SQL Server Website - http://www.microsoft.com/sqlserver

SQL Server Books Online - http://msdn.microsoft.com/en-us/library/ms

166020.aspx

SQL Server Help

w3shools.com - http://www.w3schools.com/sal

Wikipedia - Microsoft SQL Server - http://en.wikipedia.org/wiki/Microsoft

SQL server

Wikipedia - SQL- http://en.wikipedia.org/wiki/SQL

Wikipedia - Transact SQL - http://en.wikipedia.org/wiki/T-SQL

29 | P a g e

You might also like