Professional Documents
Culture Documents
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 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.
Why SQL?
● Allows users to define the data in database and manipulate that data.
● Allows to embed within other languages using SQL modules, libraries & pre-
compilers.
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.
● 1978 -- IBM worked to develop Codd's ideas and released a product named
System/R.
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:
Command Description
SELECT Retrieves certain records from one or more tables
INSERT Creates a record
UPDATE Modifies records
DELETE Deletes records
DATA:
● Basically data is a raw material when we process it,it will become useful
information.
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.
Data Integrity:
Data type:
The type of data entering into a column in a table is referred as data type.
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.
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:
CLASS:
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.
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.
Note! You can have many UNIQUE constraints per table, but only one PRIMARY
KEY constraint per table.
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:
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:
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 IN Clause:
9|Page
SQL ORDER BY Clause:
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
10 | P a g e
SQL DESC Statement :
DESC table_name;
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN [ WHERE
CONDITION ];
COMMIT;
11 | P a g e
5.SQL - OPERATORS
SQL Arithmetic Operators:
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 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:
Operator Description
The ALL operator is used to compare a value to all values in another value
ALL
set.
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 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.
IS NULL The NULL operator is used to compare a value with a NULL value.
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::
● Single-row function
● Multi-row function
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
• COUNT
• MIN,MAX
• 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 was added to SQL because the WHERE keyword could not be
used with aggregate functions.
Syntax:
User-defined Functions:
IN SQL, we may also create our own functions, so-called user-defined functions.
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 can use RETURN keyword but without any value being
passed[1].
• 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.
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
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;
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:
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.
19 | P a g e
7.JOINS
Different types of joins:
The INNER JOIN keyword selects records that have matching values in both tables.
20 | P a g e
Demo Database
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
21 | P a g e
8.Auto-increment field
Often this is the primary key field that we would like to be created automatically
every time a new record is inserted.
Age int,
);
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
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.
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:
Another view in the Northwind sample database selects every product in the "Products"
table with a unit price higher than the average unit price:
23 | P a g e
10.SQL Expressions
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:
There are different types of SQL expressions, which are mentioned below:
24 | P a g e
SELECT numerical_expression as OPERATION_NAME [FROM table_name WHERE
CONDITION] ;
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.
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:
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;
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.
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?
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.
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:
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
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
166020.aspx
w3shools.com - http://www.w3schools.com/sal
SQL server
29 | P a g e