SQL tut
SQL tut
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 embedding 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
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:
DROP Deletes an entire table, a view of a table or other object in the database.
What is field?
Every table is broken up into smaller entities called fields. The fields in the
CUSTOMERS table consist of ID, NAME, AGE, ADDRESS and SALARY.
Syntax:
Basic syntax of CREATE DATABASE statement is as follows:
CREATE DATABASE DatabaseName;
Make sure you have admin privilege before creating any database. Once a
database is created, you can check it in the list of databases as follows:
SQL> SHOW DATABASES;
+--------------------+
|Database|
+--------------------+
|information_schema|
| AMROOD |
| TUTORIALSPOINT |
|mysql|
|orig|
|test|
|testDB|
+--------------------+
7 rows inset(0.00 sec)
Syntax:
Basic syntax of DROP DATABASE statement is as follows:
DROP DATABASE DatabaseName;
Example:
If you want to delete an existing database <testDB>, then DROP DATABASE
statement would be as follows:
SQL> DROP DATABASE testDB;
SQL Constraints:
Constraints are the rules enforced on data columns on table. These are used
to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the database.
Constraints could be column level or table level. Column level constraints
are applied only to one column where as table level constraints are applied
to the whole table.
Following are commonly used constraints available in SQL:
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is
specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column
satisfy certain conditions.
INDEX: Use to create and retrieve data from the database very quickly.
Syntax:
Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE table_name(
column1datatype,
column2datatype,
column3datatype,
.....
columnNdatatype,
PRIMARY KEY( one or more columns )
CREATE TABLE is the keyword telling the database system what you want to
do. In this case, you want to create a new table. The unique name or
identifier for the table follows the CREATE TABLE statement.
Then in brackets comes the list defining each column in the table and what
sort of data type it is. The syntax becomes clearer with an example below.
A copy of an existing table can be created using a combination of the
CREATE TABLE statement and the SELECT statement. You can check
complete details at Create Table Using another Table.
Example:
Following is an example, which creates a CUSTOMERS table with ID as
primary key and NOT NULL are the constraints showing that these fields can
not be NULL while creating records in this table:
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(25),
SALARY DECIMAL (18,2),
PRIMARY KEY (ID)
);
You can verify if your table has been created successfully by looking at the
message displayed by the SQL server, otherwise you can
use DESC command as follows:
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
|Field|Type|Null|Key|Default|Extra|
+---------+---------------+------+-----+---------+-------+
| ID |int(11)| NO | PRI |||
| NAME |varchar(20)| NO ||||
| AGE |int(11)| NO ||||
| ADDRESS |char(25)| YES || NULL ||
|SALARY |decimal(18,2)| YES || NULL ||
+---------+---------------+------+-----+---------+-------+
5 rows inset(0.00 sec)
Now, you have CUSTOMERS table available in your database which you can
use to store required information related to customers.
Syntax:
Basic syntax of DROP TABLE statement is as follows:
DROP TABLE table_name;
Example:
Let us first verify CUSTOMERS table and then we would delete it from the
database:
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
|Field|Type|Null|Key|Default|Extra|
+---------+---------------+------+-----+---------+-------+
| ID |int(11)| NO | PRI |||
| NAME |varchar(20)| NO ||||
| AGE |int(11)| NO ||||
| ADDRESS |char(25)| YES || NULL ||
|SALARY |decimal(18,2)| YES || NULL ||
+---------+---------------+------+-----+---------+-------+
5 rows inset(0.00 sec)
Now, if you would try DESC command, then you would get error as follows:
SQL> DESC CUSTOMERS;
ERROR 1146(42S02):Table'TEST.CUSTOMERS' doesn't exist
Here, TEST is database name which we are using for our examples.
Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);
Example:
Following statements would create six records in CUSTOMERS table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,'Ramesh',32,'Ahmedabad',2000.00);
Syntax:
Basic syntax of USE statement is as follows:
USE DatabaseName;
Example:
You can check available databases as follows:
SQL> SHOW DATABASES;
+--------------------+
|Database|
+--------------------+
|information_schema|
| AMROOD |
| TUTORIALSPOINT |
|mysql|
|orig|
|test|
+--------------------+
6 rows inset(0.00 sec)
Now, if you want to work with AMROOD database, then you can execute the
following SQL command and start working with AMROOD database:
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:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
|7|Muffy|24|Indore|10000.00|
+----+----------+-----+-----------+----------+
Following is an example which would fetch ID, Name and Salary fields from
the CUSTOMERS table where salary is greater than 2000:
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY >2000;
Following is an example, which would fetch ID, Name and Salary fields from
the CUSTOMERS table for a customer with name Hardik. Here, it is
important to note that all the strings should be given inside single quotes ('')
Data Integrity:
The following categories of the data integrity exist with each RDBMS:
Entity Integrity: There are no duplicate rows in a table.
Domain Integrity: Enforces valid entries for a given column by restricting the
type, the format, or the range of values.
Referential integrity: Rows cannot be deleted, which are used by other
records.
User-Defined Integrity: Enforces some specific business rules that do not fall
into entity, domain or referential integrity.
Database Normalization
Database normalization is the process of efficiently organizing data in a
database. There are two reasons of the normalization process:
Eliminating redundant data, for example, storing the same data in more than
one tables.
Ensuring data dependencies make sense.
Both of these are worthy goals as they reduce the amount of space a
database consumes and ensure that data is logically stored. Normalization
consists of a series of guidelines that help guide you in creating a good
database structure.
Normalization guidelines are divided into normal forms; think of form as the
format or the way a database structure is laid out. The aim of normal forms
is to organize the database structure so that it complies with the rules of
first normal form, then second normal form, and finally third normal form.
It's your choice to take it further and go to fourth normal form, fifth normal
form, and so on, but generally speaking, third normal form is enough.
First Normal Form (1NF)
Second Normal Form (2NF)
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
- Subtraction - Subtracts right hand operand from left hand operand a - b will
give -10
% Modulus - Divides left hand operand by right hand operand and b%a
returns remainder will give
0
= Checks if the values of two operands are equal or not, if yes then (a = b) is
condition becomes true. not true.
!= Checks if the values of two operands are equal or not, if values are not (a != b)
equal then condition becomes true. is true.
<> Checks if the values of two operands are equal or not, if values are not (a <> b)
equal then condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right (a > b) is
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 the value (a >= b)
of right operand, if yes then condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value of (a <= b)
right operand, if yes then condition becomes true. is true.
!< Checks if the value of left operand is not less than the value of right (a !< b)
operand, if yes then condition becomes true. is false.
!> Checks if the value of left operand is not greater than the value of right (a !> b)
operand, if yes then condition becomes true. is true.
Show Examples
ALL The ALL operator is used to compare a value to all values in another value set.
AND The AND operator allows the existence of multiple conditions in an SQL statement's
WHERE clause.
ANY The ANY operator is used to compare a value to any applicable value in the list
according to the condition.
BETWEEN The BETWEEN operator is used to search for values that are within a set of values,
given the minimum value and the maximum value.
EXISTS The EXISTS operator is used to search for the presence of a row in a specified table
that meets certain criteria.
LIKE The LIKE operator is used to compare a value to similar values using wildcard
operators.
NOT The 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.
IS NULL The NULL operator is used to compare a value with a NULL value.
UNIQUE The UNIQUE operator searches every row of a specified table for uniqueness (no
duplicates).
The SQL AND and OR operators are used to combine multiple conditions to
narrow data in an SQL statement. These two operators are called
conjunctive operators.
These operators provide a means to make multiple comparisons with
different operators in the same SQL statement.
Syntax:
The basic syntax of AND operator with WHERE clause is as follows:
SELECT column1, column2,columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
You can combine N number of conditions using AND operator. For an action
to be taken by the SQL statement, whether it be a transaction or query, all
conditions separated by the AND must be TRUE.
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
Following is an example, which would fetch ID, Name and Salary fields from
the CUSTOMERS table where salary is greater than 2000 AND age is less tan
25 years:
SQL> SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY >2000 AND age <25;
The OR Operator:
The OR operator is used to combine multiple conditions in an SQL
statement's WHERE clause.
Syntax:
The basic syntax of OR operator with WHERE clause is as follows:
SELECT column1, column2,columnN
FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
|7|Muffy|24|Indore|10000.00|
+----+----------+-----+-----------+----------+
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:
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> SELECT COUNT(*) AS "RECORDS" FROM CUSTOMERS;
+---------+
| RECORDS |
+---------+
|7|
+---------+
1 row inset(0.00 sec)
The SQL UPDATE Query is used to modify the existing records in a table.
You can use WHERE clause with UPDATE query to update selected rows
otherwise all the rows would be affected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name
SET column1 = value1, column2 = value2....,columnN=valueN
WHERE [condition];
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
|7|Muffy|24|Indore|10000.00|
+----+----------+-----+-----------+----------+
The SQL DELETE Query is used to delete the existing records from a table.
You can use WHERE clause with DELETE query to delete selected rows,
otherwise all the records would be deleted.
Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:
DELETE FROM table_name
WHERE [condition];
Example:
If you want to DELETE all the records from CUSTOMERS table, you do not
need to use WHERE clause and DELETE query would be as follows:
SQL> DELETE FROM CUSTOMERS;
Syntax:
The basic syntax of % and _ is as follows:
SELECT FROM table_name
or
or
or
or
Example:
Here are number of examples showing WHERE part having different LIKE
clause with '%' and '_' operators:
Statement Description
WHERE SALARY LIKE '200%' Finds any values that start with 200
WHERE SALARY LIKE Finds any values that have 200 in any position
'%200%'
WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions
WHERE SALARY LIKE '2_%_ Finds any values that start with 2 and are at least 3 characters in
%' length
WHERE SALARY LIKE '%2' Finds any values that end with 2
WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end with
a3
WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2 and end
with 3
Let us take a real example, consider the CUSTOMERS table having the
following records:
+----+----------+-----+-----------+----------+
Syntax:
The basic syntax of TOP clause with SELECT statement would be as follows:
SELECT TOP number|percentcolumn_name(s)
FROM table_name
WHERE [condition]
Example:
Consider the CUSTOMERS table having the following records:
Syntax:
The basic syntax of ORDER BY clause is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
You can use more than one column in the ORDER BY clause. Make sure
whatever column you are using to sort, that column should be in column-
list.
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
|7|Muffy|24|Indore|10000.00|
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|3|kaushik|23|Kota|2000.00|
|2|Khilan|25|Delhi|1500.00|
|6|Komal|22| MP |4500.00|
|7|Muffy|24|Indore|10000.00|
|1|Ramesh|32|Ahmedabad|2000.00|
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|7|Muffy|24|Indore|10000.00|
|6|Komal|22| MP |4500.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
|5|Hardik|27|Bhopal|8500.00|
|4|Chaitali|25|Mumbai|6500.00|
+----+----------+-----+-----------+----------+
SQL - Group By
Syntax:
The basic syntax of GROUP BY clause is given below. The GROUP BY clause
must follow the conditions in the WHERE clause and must precede the
ORDER BY clause if one is used.
SELECT column1, column2
FROM table_name
WHERE [ conditions]
GROUP BY column1, column2
ORDER BY column1, column2
Example:
Consider the CUSTOMERS table is having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
|7|Muffy|24|Indore|10000.00|
+----+----------+-----+-----------+----------+
If you want to know the total amount of salary on each customer, then
GROUP BY query would be as follows:
SQL> SELECT NAME,SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
Now, let us have following table where CUSTOMERS table has the following
records with duplicate names:
Now again, if you want to know the total amount of salary on each
customer, then GROUP BY query would be as follows:
SQL> SELECT NAME,SUM(SALARY) FROM CUSTOMERS
GROUP BY NAME;
Syntax:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as
follows:
SELECT DISTINCT column1,column2,.....columnN
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
|7|Muffy|24|Indore|10000.00|
+----+----------+-----+-----------+----------+
First, let us see how the following SELECT query returns duplicate salary
records:
SQL> SELECT SALARY FROM CUSTOMERS
ORDER BY SALARY;
This would produce the following result where salary 2000 is coming twice
which is a duplicate record from the original table.
+----------+
| SALARY |
+----------+
|1500.00|
|2000.00|
|2000.00|
|4500.00|
|6500.00|
|8500.00|
|10000.00|
+----------+
Now, let us use DISTINCT keyword with the above SELECT query and see the
result:
SQL> SELECT DISTINCT SALARY FROM CUSTOMERS
ORDER BY SALARY;
This would produce the following result where we do not have any duplicate
entry:
+----------+
| SALARY |
+----------+
|1500.00|
|2000.00|
|4500.00|
|6500.00|
|8500.00|
SQL Syntax
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