Thursday, August 20, 2015

SQL - Overview

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

HISTORY:

  • 1970 -- Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational databases. He described a relational model for databases.
  • 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:
SQL Architecture

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:

CommandDescription
CREATECreates a new table, a view of a table, or other object in database
ALTERModifies an existing database object, such as a table.
DROPDeletes an entire table, a view of a table or other object in the database.

DML - DATA MANIPULATION LANGUAGE:

CommandDescription
SELECTRetrieves certain records from one or more tables
INSERTCreates a record
UPDATEModifies records
DELETEDeletes records

DCL - DATA CONTROL LANGUAGE:

CommandDescription
GRANTGives a privilege to user
REVOKETakes back privileges granted from user

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 (;).
Important point to be noted is that SQL is case insensitive, which means SELECT and select have same meaning in SQL statements, but MySQL makes difference in table names. So if you are working with MySQL, then you need to give table names as they exist in the database.
All the examples given in this tutorial have been tested with MySQL server.

SQL SELECT STATEMENT:

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

SQL DISTINCT CLAUSE:

SELECT DISTINCT column1, 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 };

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;

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_name;

SQL COMMIT STATEMENT:

COMMIT;

SQL ROLLBACK STATEMENT:

ROLLBACK;

SQL - Data Types

SQL data type is an attribute that specifies type of data of any object. Each column, variable and expression has related data type in SQL.
You would use these data types while creating your tables. You would choose a particular data type for a table column based on your requirement.
SQL Server offers six categories of data types for your use:

EXACT NUMERIC DATA TYPES:

DATA TYPEFROMTO
bigint-9,223,372,036,854,775,8089,223,372,036,854,775,807
int-2,147,483,6482,147,483,647
smallint-32,76832,767
tinyint0255
bit01
decimal-10^38 +110^38 -1
numeric-10^38 +110^38 -1
money-922,337,203,685,477.5808+922,337,203,685,477.5807
smallmoney-214,748.3648+214,748.3647

APPROXIMATE NUMERIC DATA TYPES:

DATA TYPEFROMTO
float-1.79E + 3081.79E + 308
real-3.40E + 383.40E + 38

DATE AND TIME DATA TYPES:

DATA TYPEFROMTO
datetimeJan 1, 1753Dec 31, 9999
smalldatetimeJan 1, 1900Jun 6, 2079
dateStores a date like June 30, 1991
timeStores a time of day like 12:30 P.M.
Note: Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy.

CHARACTER STRINGS DATA TYPES:

DATA TYPEFROMTO
charcharMaximum length of 8,000 characters.( Fixed length non-Unicode characters)
varcharvarcharMaximum of 8,000 characters.(Variable-length non-Unicode data).
varchar(max)varchar(max)Maximum length of 231characters, Variable-length non-Unicode data (SQL Server 2005 only).
texttextVariable-length non-Unicode data with a maximum length of 2,147,483,647 characters.

UNICODE CHARACTER STRINGS DATA TYPES:

DATA TYPEDescription
ncharMaximum length of 4,000 characters.( Fixed length Unicode)
nvarcharMaximum length of 4,000 characters.(Variable length Unicode)
nvarchar(max)Maximum length of 231characters (SQL Server 2005 only).( Variable length Unicode)
ntextMaximum length of 1,073,741,823 characters. ( Variable length Unicode )

BINARY DATA TYPES:

DATA TYPEDescription
binaryMaximum length of 8,000 bytes(Fixed-length binary data )
varbinaryMaximum length of 8,000 bytes.(Variable length binary data)
varbinary(max)Maximum length of 231 bytes (SQL Server 2005 only). ( Variable length Binary data)
imageMaximum length of 2,147,483,647 bytes. ( Variable length Binary Data)

MISC DATA TYPES:

DATA TYPEDescription
sql_variantStores values of various SQL Server-supported data types, except text, ntext, and timestamp.
timestampStores a database-wide unique number that gets updated every time a row gets updated
uniqueidentifierStores a globally unique identifier (GUID)
xmlStores XML data. You can store xml instances in a column or a variable (SQL Server 2005 only).
cursorReference to a cursor object
tableStores a result set for later processing

SQL - Operators

WHAT IS AN OPERATOR IN SQL?

An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations.
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement.
  • Arithmetic operators
  • Comparison operators
  • Logical operators
  • Operators used to negate conditions

SQL ARITHMETIC OPERATORS:

Assume variable a holds 10 and variable b holds 20, then:
OperatorDescriptionExample
+Addition - Adds values on either side of the operatora + b will give 30
-Subtraction - Subtracts right hand operand from left hand operanda - b will give -10
*Multiplication - Multiplies values on either side of the operatora * b will give 200
/Division - Divides left hand operand by right hand operandb / a will give 2
%Modulus - Divides left hand operand by right hand operand and returns remainderb % a will give 0

SQL COMPARISON OPERATORS:

Assume variable a holds 10 and variable b holds 20, then:
OperatorDescriptionExample
=Checks if the values of two operands are equal or not, if yes then condition becomes true.(a = b) is not true.
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(a != b) is true.
<>Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(a <> b) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(a > b) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(a < b) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(a >= b) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(a <= b) is true.
!<Checks if the value of left operand is not less than the value of right operand, if yes then condition becomes true.(a !< b) is false.
!>Checks if the value of left operand is not greater than the value of right operand, if yes then condition becomes true.(a !> b) is true.

SQL LOGICAL OPERATORS:

Here is a list of all the logical operators available in SQL.
OperatorDescription
ALLThe ALL operator is used to compare a value to all values in another value set.
ANDThe AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
ANYThe ANY operator is used to compare a value to any applicable value in the list according to the condition.
BETWEENThe BETWEEN operator is used to search for values that are within a set of values, given the minimum value and the maximum value.
EXISTSThe EXISTS operator is used to search for the presence of a row in a specified table that meets certain criteria.
INThe IN operator is used to compare a value to a list of literal values that have been specified.
LIKEThe LIKE operator is used to compare a value to similar values using wildcard operators.
NOTThe NOT operator reverses the meaning of the logical operator with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
ORThe OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
IS NULLThe NULL operator is used to compare a value with a NULL value.
UNIQUEThe UNIQUE operator searches every row of a specified table for uniqueness (no duplicates).