0% found this document useful (0 votes)
19 views

DataBase SQL

Study database SQL cmmands
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

DataBase SQL

Study database SQL cmmands
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Quick Lab Reference GUIDE for Database & SQL / By ENDELLY tatsopt@gmail.

com

Table of Contents
SQL Overview................................................................................................................................................................................................................... 3
What is SQL? .................................................................................................................................................................................................................... 3
Why SQL? ......................................................................................................................................................................................................................... 3
SQL Process: ..................................................................................................................................................................................................................... 3
SQL Commands: .............................................................................................................................................................................................................. 3
DDL - Data Definition Language: .................................................................................................................................................................................... 4
DML - Data Manipulation Language: ............................................................................................................................................................................. 4
DCL - Data Control Language: ....................................................................................................................................................................................... 4
DQL - Data Query Language: ......................................................................................................................................................................................... 4
SQL RDBMS Concepts .................................................................................................................................................................................................... 4
What is NULL value? ....................................................................................................................................................................................................... 5
SQL Constraints: .............................................................................................................................................................................................................. 5
Data Integrity: .................................................................................................................................................................................................................. 5
Integrity Constraints: ....................................................................................................................................................................................................... 5
NOT NULL (Presence Check) Constraint: ..................................................................................................................................................................... 5
DEFAULT Constraint:..................................................................................................................................................................................................... 6
Drop Default Constraint: ................................................................................................................................................................................................. 6
UNIQUE Constraint: ........................................................................................................................................................................................................ 7
DROP a UNIQUE Constraint: ......................................................................................................................................................................................... 7
PRIMARY Key:................................................................................................................................................................................................................ 7
Create Primary Key: ........................................................................................................................................................................................................ 8
Delete Primary Key: ......................................................................................................................................................................................................... 8
FOREIGN Key: ................................................................................................................................................................................................................ 8
DROP a FOREIGN KEY Constraint: ............................................................................................................................................................................. 9
CHECK Constraint: ......................................................................................................................................................................................................... 9
DROP a CHECK Constraint: ........................................................................................................................................................................................ 10
INDEX:............................................................................................................................................................................................................................ 10
DROP an INDEX Constraint:........................................................................................................................................................................................ 11
Database Normalization ................................................................................................................................................................................................. 11
First Normal Form ......................................................................................................................................................................................................... 11
Second Normal Form ..................................................................................................................................................................................................... 13
Third Normal Form ........................................................................................................................................................................................................ 14
SQL Syntax ..................................................................................................................................................................................................................... 15
SQL Data Types .............................................................................................................................................................................................................. 19
Exact Numeric Data Types: ........................................................................................................................................................................................... 19
Approximate Numeric Data Types: ............................................................................................................................................................................... 19
Date and Time Data Types:............................................................................................................................................................................................ 19
Character Strings Data Types: ...................................................................................................................................................................................... 19
Unicode Character Strings Data Types: ........................................................................................................................................................................ 20
Binary Data Types: ......................................................................................................................................................................................................... 20
SQL Operators................................................................................................................................................................................................................ 20
SQL Comparison Operators: ......................................................................................................................................................................................... 22
SQL Logical Operators: ................................................................................................................................................................................................. 24
SQL NULL Values.......................................................................................................................................................................................................... 27
SQL CREATE Database ................................................................................................................................................................................................ 28
DROP or DELETE Database ......................................................................................................................................................................................... 28
SQL SELECT Database ................................................................................................................................................................................................. 28
SQL CREATE Table ...................................................................................................................................................................................................... 29
SQL DROP or DELETE Table ...................................................................................................................................................................................... 31

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 1


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL INSERT Query....................................................................................................................................................................................................... 31


SQL SELECT Query ...................................................................................................................................................................................................... 32
SQL WHERE Clause ..................................................................................................................................................................................................... 33
SQL UPDATE Query ..................................................................................................................................................................................................... 36
SQL DELETE Query ..................................................................................................................................................................................................... 37
SQL LIKE Clause and Wildcard Operators ................................................................................................................................................................. 38
SQL ORDER BY Clause ................................................................................................................................................................................................ 40
SQL Group By ................................................................................................................................................................................................................ 41
SQL Distinct Keyword ................................................................................................................................................................................................... 43
SQL SORTING Results .................................................................................................................................................................................................. 44
SQL Joins ........................................................................................................................................................................................................................ 46
SQL Join Types: ............................................................................................................................................................................................................. 46
INNER JOIN................................................................................................................................................................................................................... 47
LEFT JOIN ..................................................................................................................................................................................................................... 48
RIGHT JOIN .................................................................................................................................................................................................................. 49
FULL JOIN ..................................................................................................................................................................................................................... 50
SELF JOIN ..................................................................................................................................................................................................................... 51
CARTESIAN JOIN ........................................................................................................................................................................................................ 52
SQL Unions Clause ......................................................................................................................................................................................................... 53
The UNION ALL Clause: .............................................................................................................................................................................................. 54
SQL Alias Syntax ............................................................................................................................................................................................................ 55
SQL ALTER TABLE Command................................................................................................................................................................................... 57
SQL TRUNCATE TABLE ............................................................................................................................................................................................. 58
SQL HAVING CLAUSE ................................................................................................................................................................................................ 59
SQL Sub Queries ............................................................................................................................................................................................................ 60
Subqueries with the SELECT Statement: ..................................................................................................................................................................... 60
Subqueries with the INSERT Statement: ...................................................................................................................................................................... 61
Subqueries with the DELETE Statement: .................................................................................................................................................................... 62
SQL – Using Sequences .................................................................................................................................................................................................. 63
Using AUTO_INCREMENT column: ........................................................................................................................................................................... 63
Renumbering an Existing Sequence: ............................................................................................................................................................................. 63
SQL Useful Functions ..................................................................................................................................................................................................... 64
SQL COUNT Function ................................................................................................................................................................................................... 64
SQL MAX Function ....................................................................................................................................................................................................... 65
SQL AVG Function ........................................................................................................................................................................................................ 67
SQL SUM Function ........................................................................................................................................................................................................ 68
SQL SQRT Function ...................................................................................................................................................................................................... 69
SQL RAND Function ..................................................................................................................................................................................................... 70
SQL CONCAT Function ................................................................................................................................................................................................ 71
SQL - Using Views .......................................................................................................................................................................................................... 72
Creating Views: .............................................................................................................................................................................................................. 72
The WITH CHECK OPTION: ...................................................................................................................................................................................... 73
Updating a View: ............................................................................................................................................................................................................ 74
Inserting Rows into a View: ........................................................................................................................................................................................... 74
Dropping Views: ............................................................................................................................................................................................................. 75
SQL Transactions ........................................................................................................................................................................................................... 75

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 2


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL Overview
What is SQL?
SQL is Structured Query Language, which is a computer language for Relation Database System for
storing, manipulating and retrieving data stored in relational database. A query is a way of searching
and extracting data from a database to find the answer to a question. The query/search checks each
record and produces a list of data that satisfies the query criteria.
All relational database management systems (DBMS) 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
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 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:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 3


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

DDL - Data Definition Language:

DML - Data Manipulation Language:

DCL - Data Control Language:

DQL - Data Query Language:

SQL RDBMS Concepts


When data is organised into files, and each file is organised into a number of rows and columns this is
referred to as a table or ‘flat file’. A table is two-dimensional hence the description ‘flat file’. The table
below can be referred to as a ‘customer’ table or relation.

A file or table such as the one above consists of a number of records. A record is represented as a row
in a table. A record consists of data items related to an object or person. A field is part of a record that
stores a single data item. In a table, each field is represented by a column and is referenced by its field

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 4


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

name (the column title). The key field (or primary key) is the field used to uniquely identify one
record. In the table above the key field is CustomerID; each customer has a unique ID.

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.

What is NULL value?


A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL
value is a field with no value.
It is very important to understand that a NULL value is different than a zero value or a field that contains
spaces. A field with a NULL value is one that has been left blank during record creation.

SQL Constraints:
Constraints are the rules enforced on data columns on table that to limits 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, whereas 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.

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.
Integrity Constraints:
Integrity constraints are used to ensure accuracy and consistency of data in a relational database. Data
integrity is handled in a relational database through the concept of referential integrity. There are
many types of integrity constraints that play a role in referential integrity (RI). These constraints include
Primary Key, Foreign Key, Unique Constraints and other constraints mentioned above.

NOT NULL (Presence Check) Constraint:


By default, a column can hold NULL values. If you do not want a column to have a NULL value, then
you need to define such constraint on this column specifying that NULL is now not allowed for that
column. Example: For example, the following SQL creates a new table called CUSTOMERS and adds
five columns, three of which, ID and NAME and AGE, specify not to accept NULLs:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 5


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Here, NOT NULL signifies that column should always accept an explicit value of the given data type.
If CUSTOMERS table has already been created, then to add a NOT NULL constraint to SALARY
column in Oracle and MySQL, you would write a statement similar to the following:

DEFAULT Constraint:
The DEFAULT constraint provides a default value to a column when the INSERT INTO statement
does not provide a specific value.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here,
SALARY column is set to 5000.00 by default, so in case INSERT INTO statement does not provide a
value for this column. Then by default this column would be set to 5000.00.

If CUSTOMERS table has already been created without Default constraint, then to add it to SALARY
column, you would write a statement similar to the following:

Drop Default Constraint:


To drop a DEFAULT constraint, use the following SQL:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 6


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

UNIQUE Constraint:
The UNIQUE Constraint prevents two records from having identical values in a particular column. In
the CUSTOMERS table, for example, you might want to prevent two or more people from having
identical age.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here,
AGE column is set to UNIQUE, so that you cannot have two records with same age:

If CUSTOMERS table has already been created without UNIQUE constraint, then to add it to AGE
column, you would write a statement similar to the following:

You can also use following syntax, which supports naming the constraint in multiple columns as well:

DROP a UNIQUE Constraint:


To drop a UNIQUE constraint, use the following SQL:

If you are using MySQL, then you can use the following syntax:

PRIMARY Key:
A primary key is a field in a table which uniquely identifies each row/record in a database table.
Primary keys must contain unique values. A primary key column cannot have NULL values.
A table can have only one primary key, which may consist of single or multiple fields. When multiple
fields are used as a primary key, they are called a composite key.
If a table has a primary key defined on any field(s), then you cannot have two records having the same
value of that field(s).
Note: You would use these concepts while creating database tables.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 7


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Create Primary Key:


Here is the syntax to define ID attribute as a primary key in a CUSTOMERS table.

To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table already exists
without it, use the following SQL syntax:

NOTE: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must
already have been declared to not contain NULL values (when the table was first created).
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:

To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when CUSTOMERS table
already exists without it, use the following SQL syntax:

Delete Primary Key:


You can clear the primary key constraints from the table, Use Syntax:

FOREIGN Key:
A foreign key is a key used to link two tables together. This is sometimes called a referencing key.
Foreign Key is a column or a combination of columns whose values match a Primary Key in a different
table.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 8


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

The relationship between 2 tables matches the Primary Key in one of the tables with a Foreign Key in
the second table.
If a table has a primary key defined on any field(s), then you cannot have two records having the same
value of that field(s). Example:
Consider the structure of the two tables as follows:
CUSTOMERS table:

ORDERS table:

If ORDERS table has already been created, and the foreign key has not yet been set, use the syntax for
specifying a foreign key by altering a table

DROP a FOREIGN KEY Constraint:


To drop a FOREIGN KEY constraint, use the following SQL

CHECK Constraint:
The CHECK Constraint enables a condition to check the value being entered into a record. If the
condition evaluates to false, the record violates the constraint and isn’t entered into the table.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns. Here,
we add a CHECK with AGE column, so that you cannot have any CUSTOMER below 18 years:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 9


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

If CUSTOMERS table has already been created without a CHECK constraint, then to add it to AGE
column, you would write a statement similar to the following

You can also use following syntax, which supports naming the constraint in multiple columns as well:

DROP a CHECK Constraint:


To drop a CHECK constraint, use the following SQL. This syntax does not work with MySQL:

INDEX:
The INDEX is used to create and retrieve data from the database very quickly. Index can be created by
using single or group of columns in a table. When index is created, it is assigned a ROWID for each
row before it sorts out the data. Proper indexes are good for performance in large databases, but
you need to be careful while creating index. Selection of fields depends on what you are using in your
SQL queries. Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 10


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Now, you can create index on single or multiple columns using the following syntax

To create an INDEX on AGE column, to optimize the search on customers for a particular age,
following is the SQL syntax

DROP an INDEX Constraint:


To drop an INDEX constraint, use the following SQL:

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 table.
 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.
The Normal Forms are:
 First Normal Form (1NF)
 Second Normal Form (2NF)
 Third Normal Form (3NF)
First Normal Form
First normal form (1NF) sets the very basic rules for an organized database:
 Define the data items required, because they become the columns in a table. Place related data
items in a table.
 Ensure that there are no repeating groups of data.
 Ensure that there is a primary key.
Consider we have the following table:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 11


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

So if we populate this table for a single customer having multiple orders, then it would be something as
follows

But as per 1NF, we need to ensure that there are no repeating groups of data. So let us break above table
into two parts and join them using a key as follows:
CUSTOMERS table:

This table would have the following record:

ORDERS table:

This table would have the following records:

The final rule of the first normal form, create a primary key for each table which we have already
created.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 12


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Second Normal Form


Second normal form states that it should meet all the rules for 1NF and there must be no partial
dependences of any of the columns on the primary key:
Consider a customer-order relation and you want to store customer ID, customer name, order ID and
order detail, and date of purchase:

This table is in first normal form, in that it obeys all the rules of first normal form. In this table, the
primary key consists of CUST_ID and ORDER_ID. Combined, they are unique assuming same
customer would hardly order same thing.
However, the table is not in second normal form because there are partial dependencies of primary
keys and columns. CUST_NAME is dependent on CUST_ID, and there's no real link between a
customer's name and what he purchased. Order detail and purchase date are also dependent on
ORDER_ID, but they are not dependent on CUST_ID, because there's no link between a CUST_ID and
an ORDER_DETAIL or their SALE_DATE.
To make this table comply with second normal form, you need to separate the columns into three
tables. First, create a table to store the customer details as follows:

Next, create a table to store details of each order:

Finally, create a third table storing just CUST_ID and ORDER_ID to keep track of all the orders for a
customer:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 13


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Third Normal Form


A table is in third normal form when the following conditions are met:
 It is in second normal form.
 All non-primary fields are dependent on the primary key (No Transitive Dependency).
The dependency of non-primary fields is between the data. For example, in the below table, street name,
city, and state are unbreakably bound to the zip code.

The dependency between zip code and address is called a transitive dependency. To comply with
third normal form, all you need to do is move the Street, City, and State fields into their own table,
which you can call the Zip. Code table:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 14


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Next, alter the CUSTOMERS table as follows:

The advantages of removing transitive dependencies are mainly twofold. First, the amount of data
duplication is reduced and therefore your database becomes smaller.
The second advantage is data integrity. When duplicated data changes, there's a big risk of updating
only some of the data (Data Inconsistency), especially if it's spread out in a number of different places
in the database. For example, if address and zip code data were stored in three or four different tables,
then any changes in zip codes would need to ripple out to every record in those three or four tables

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.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 15


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 16


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 17


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 18


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

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:

Approximate Numeric Data Types:

Date and Time Data Types:

Note: Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy.
Character Strings Data Types:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 19


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Unicode Character Strings Data Types:

Binary Data Types:

Misc Data Types:

SQL Operators
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:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 20


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Here are simple examples showing usage of SQL Arithmetic Operators:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 21


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL Comparison Operators:


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

Consider the CUSTOMERS table having the following records

Here are simple examples showing usage of SQL Comparison Operators:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 22


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 23


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL Logical Operators:


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

Consider the CUSTOMERS table having the following records:

Here are simple examples showing usage of SQL Comparison Operators

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 24


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 25


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 26


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL NULL Values


The SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a
field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that a NULL
value is different than a zero value or a field that contains spaces.
Example:
The NULL value can cause problems when selecting data, however, because when comparing an
unknown value to any other value, the result is always unknown and not included in the final results.
You must use the IS NULL or IS NOT NULL operators in order to check for a NULL value.
Consider the following table, CUSTOMERS having the following records:

Now, following is the usage of IS NOT NULL operator:

This would produce the following result:

Now, following is the usage of IS NULL operator:

This would produce the following result:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 27


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL CREATE Database


The SQL CREATE DATABASE statement is used to create new SQL database.
Syntax:
Basic syntax of CREATE DATABASE statement is as follows:

Always database name should be unique within the RDBMS.


Example:
If you want to create new database <testDB>, then CREATE DATABASE statement would be as
follows

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

DROP or DELETE Database


The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.
Syntax:
Basic syntax of DROP DATABASE statement is as follows:

Always database name should be unique within the RDBMS.


Example:
If you want to delete an existing database <testDB>, then DROP DATABASE statement would be as
follows:

NOTE: Be careful before using this operation because by deleting an existing database would result in
loss of complete information stored in the database.
Make sure you have admin privilege before dropping any database. Once a database is dropped, you
can check it.

SQL SELECT Database


When you have multiple databases in your SQL Schema, then before starting your operation, you would
need to select a database where all the operations would be performed.
The SQL USE statement is used to select any existing database in SQL schema.
Syntax:
Basic syntax of USE statement is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 28


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Always database name should be unique within the RDBMS.


Example:
You can check available databases as follows:

Now, if you want to work with AMROOD database, then you can execute the following SQL command
and start working with AMROOD database:

SQL CREATE Table


Creating a basic table involves naming the table and defining its columns and each column's data type.
The SQL CREATE TABLE statement is used to create a new table.
Syntax:
Basic syntax of CREATE TABLE statement is as follows:

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.
Create Table Using another Table
A copy of an existing table can be created using a combination of the CREATE TABLE statement and
the SELECT statement.
The new table has the same column definitions. All columns or specific columns can be selected.
When you create a new table using existing table, new table would be populated using existing values
in the old table.
Syntax:
The basic syntax for creating a table from another table is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 29


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Here, column1, column2...are the fields of existing table and same would be used to create fields of
new table.
Example:
Following is an example, which would create a table SALARY using CUSTOMERS table and having
fields customer ID and customer SALARY:

This would create new table SALARY, which would have the following records:

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 cannot be NULL while creating records in this table:

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:

Now, you have CUSTOMERS table available in your database which you can use to store required
information related to customers.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 30


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL DROP or DELETE Table


The SQL DROP TABLE statement is used to remove a table definition and all data, indexes, triggers,
constraints, and permission specifications for that table.
NOTE: You have to be careful while using this command because once a table is deleted then all the
information available in the table would also be lost forever.
Syntax:
Basic syntax of DROP TABLE statement is as follows:

Example:
Let us first verify CUSTOMERS table and then we would delete it from the database:

This means CUSTOMERS table is available in the database, so let us drop it as follows:

Now, if you would try DESC command, then you would get error as follows

SQL INSERT Query


The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:

Here, column1, column2,...columnN are the names of the columns in the table into which you want to
insert data.
You may not need to specify the column(s) name in the SQL query if you are adding values for all the
columns of the table. But make sure the order of the values is in the same order as the columns in the
table. The SQL INSERT
INTO syntax would be as follows:

Example:
Following statements would create six records in CUSTOMERS table:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 31


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

You can create a record in CUSTOMERS table using second syntax as follows:

All the above statements would produce the following records in CUSTOMERS table:

Populate one table using another table:


You can populate data into a table through select statement over another table provided another table
has a set of fields, which are required to populate first table. Here is the syntax:

SQL SELECT Query


SQL SELECT Statement is used to fetch the data from a database table which returns data in the form
of result table. These result tables are called result-sets.
Syntax:
The basic syntax of SELECT statement is as follows:

Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch
all the fields available in the field, then you can use the following syntax:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 32


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Example:
Consider the CUSTOMERS table having the following records:

Following is an example, which would fetch ID, Name and Salary fields of the customers available in
CUSTOMERS table:

This would produce the following result:

If you want to fetch all the fields of CUSTOMERS table, then use the following query:

This would produce the following result:

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.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 33


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

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:

This would produce the following result:

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 ('') whereas numeric values should be given without any quote as in above example:

This would produce the following result

SQL AND and OR Operators

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 34


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

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.
The AND Operator:
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
Syntax:
The basic syntax of AND operator with WHERE clause is as follows:

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:

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 than 25 years:

This would produce the following result:

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

You can combine N number of conditions using OR operator. For an action to be taken by the SQL
statement, whether it be a transaction or query, only any ONE of the conditions separated by the OR
must be TRUE.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 35


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

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 OR age is less than 25 years:

This would produce the following result:

SQL UPDATE Query


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:

You can combine N number of conditions using AND or OR operators.


Example:
Consider the CUSTOMERS table having the following records:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 36


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Following is an example, which would update ADDRESS for a customer whose ID is 6:

Now, CUSTOMERS table would have the following records

If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not
need to use WHERE clause and UPDATE query would be as follows:

Now, CUSTOMERS table would have the following records:

SQL DELETE Query


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.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 37


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:

You can combine N number of conditions using AND or OR operators.


Example:
Consider the CUSTOMERS table having the following records:

Following is an example, which would DELETE a customer, whose ID is 6:

Now, CUSTOMERS table would have the following records:

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

Now, CUSTOMERS table would not have any record.

SQL LIKE Clause and Wildcard Operators


The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are
two wildcards used in conjunction with the LIKE operator:
 The percent sign (%)
 The underscore (_)
The percent sign represents zero, one, or multiple characters. The underscore represents a single number
or character. The symbols can be used in combinations.
Syntax:
The basic syntax of % and _ is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 38


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

You can combine N number of conditions using AND or OR operators. Here, XXXX could be any
numeric or string value
Example:
Here are number of examples showing WHERE part having different LIKE clause with '%' and '_'
operators:

Let us take a real example, consider the CUSTOMERS table having the following records:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 39


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Following is an example, which would display all the records from CUSTOMERS table where
SALARY starts with 200:

This would produce the following result:

SQL ORDER BY Clause


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one
or more columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause is as follows:

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:

Following is an example, which would sort the result in ascending order by NAME and SALARY:

This would produce the following result:


Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 40
Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Following is an example, which would sort the result in descending order by NAME:

This would produce the following result

SQL Group By
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical
data into groups. The GROUP BY clause follows the WHERE clause in a SELECT statement and
precedes the ORDER BY clause.
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.

Example:
Consider the CUSTOMERS table having the following records:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 41


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

If you want to know the total amount of salary on each customer, then GROUP BY query would be as
follows:

This would produce the following result:

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:

This would produce the following result:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 42


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL Distinct Keyword


The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the
duplicate records and fetching only unique records.
There may be a situation when you have multiple duplicate records in a table. While fetching such
records, it makes more sense to fetch only unique records instead of fetching duplicate records.
Syntax:
The basic syntax of DISTINCT keyword to eliminate duplicate records is as follows:

Example:
Consider the CUSTOMERS table having the following records:

First, let us see how the following SELECT query returns duplicate salary records:

This would produce the following result where salary 2000 is coming twice which is a duplicate record
from the original table.

Now, let us use DISTINCT keyword with the above SELECT query and see the result:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 43


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

This would produce the following result where we do not have any duplicate entry

SQL SORTING Results


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one
or more columns. Some databases sort query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause which would be used to sort result in ascending or descending
order is as follows:

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:

Following is an example, which would sort the result in ascending order by NAME and SALARY:

This would produce the following result:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 44


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Following is an example, which would sort the result in descending order by NAME:

This would produce the following result:

To fetch the rows with own preferred order, the SELECT query would be as follows:

This would produce the following result:

This will sort customers by ADDRESS in your own Order of preference first and in a natural order for
the remaining addresses. Also remaining Addresses will be sorted in the reverse alpha order.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 45


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL Joins
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a
means for combining fields from two tables by using values common to each.
Consider the following two tables, (a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables in our SELECT statement as follows:

This would produce the following result

Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be used to
join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join
tables. However, the most common operator is the equal symbol.

SQL Join Types:


There are different types of joins available in SQL:
 INNER JOIN: returns rows when there is a match in both tables.
 LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
 RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
 FULL JOIN: returns rows when there is a match in one of the tables.
 SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming
at least one table in the SQL statement.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 46


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

 CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more
joined tables.
INNER JOIN
The most frequently used and important of the joins is the INNER JOIN. They are also referred to as
an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables (table1 and
table2) based upon the join-predicate. The query compares each row of table1 with each row of table2
to find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied, column
values for each matched pair of rows of A and B are combined into a result row.
Syntax:
The basic syntax of INNER JOIN is as follows:

Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using INNER JOIN as follows

This would produce the following result:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 47


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table.
This means that if the ON clause matches 0 (zero) records in right table, the join will still return a row
in the result, but with NULL in each column from right table.
This means that a left join returns all the values from the left table, plus matched values from the right
table or NULL in case of no matching join predicate.
Syntax:
The basic syntax of LEFT JOIN is as follows:

Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using LEFT JOIN as follows:

This would produce the following result:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 48


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in the left
table. This means that if the ON clause matches 0 (zero) records in left table, the join will still return a
row in the result, but with NULL in each column from left table.
This means that a right join returns all the values from the right table, plus matched values from the left
table or NULL in case of no matching join predicate.
Syntax:
The basic syntax of RIGHT JOIN is as follows:

Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using RIGHT JOIN as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 49


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

This would produce the following result:

FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both tables, and fill in NULLs for missing matches on
either side.
Syntax:
The basic syntax of FULL JOIN is as follows:

Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:

(b) Another table is ORDERS as follows:

Now, let us join these two tables using FULL JOIN as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 50


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

This would produce the following result

If your Database does not support FULL JOIN like MySQL does not support FULL JOIN, then you
can use UNION ALL clause to combine two JOINS as follows:

SELF JOIN
The SQL SELF JOIN is used to join a table to itself as if the table were two tables, temporarily renaming
at least one table in the SQL statement.
Syntax:
The basic syntax of SELF JOIN is as follows:

Here, WHERE clause could be any given expression based on your requirement
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 51


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Now, let us join this table using SELF JOIN as follows:

This would produce the following result:

CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the cartesian product of the sets of records from the
two or more joined tables. Thus, it equates to an inner join where the join-condition always evaluates
to True or where the join-condition is absent from the statement.
Syntax:
The basic syntax of INNER JOIN is as follows:

Example:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 52


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Consider the following two tables, (a) CUSTOMERS table is as follows:


(b) Another table is ORDERS as follows:
Now, let us join these two tables using INNER JOIN as follows:

This would produce the following result:

SQL Unions Clause


The SQL UNION clause/operator is used to combine the results of two or more SELECT statements
without returning any duplicate rows.
To use UNION, each SELECT must have the same number of columns selected, the same number of
column expressions, the same data type, and have them in the same order, but they do not have to be
the same length.
Syntax:
The basic syntax of UNION is as follows:

Here given condition could be any given expression based on your requirement.
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 53


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

(b) Another table is ORDERS as follows:

Now, let us join these two tables in our SELECT statement as follows:

This would produce the following result:

The UNION ALL Clause:


The UNION ALL operator is used to combine the results of two SELECT statements including
duplicate rows. The same rules that apply to UNION apply to the UNION ALL operator.
Syntax:
The basic syntax of UNION ALL is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 54


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Here given condition could be any given expression based on your requirement.
Now, let us join these two tables in our SELECT statement as follows:

This would produce the following result:

SQL Alias Syntax


You can rename a table or a column temporarily by giving another name known as alias.
The use of table aliases means to rename a table in a particular SQL statement. The renaming is a
temporary change and the actual table name does not change in the database.
The column aliases are used to rename a table's columns for the purpose of a particular SQL query.
Syntax:
The basic syntax of table alias is as follows:

The basic syntax of column alias is as follows:

Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 55


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

(b) Another table is ORDERS as follows:

Now, following is the usage of table alias:

This would produce the following result:

Following is the usage of column alias:

This would produce the following result:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 56


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL ALTER TABLE Command


The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table.
You would also use ALTER TABLE command to add and drop various constraints on an existing table.
Syntax:
The basic syntax of ALTER TABLE to add a new column in an existing table is as follows:

Example:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 57


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Consider the CUSTOMERS table having the following records:

Following is the example to ADD a new column in an existing table:

Now, CUSTOMERS table is changed and following would be output from SELECT statement:

Following is the example to DROP sex column from existing table:

Now, CUSTOMERS table is changed and following would be output from SELECT statement:

SQL TRUNCATE TABLE


The SQL TRUNCATE TABLE command is used to delete complete data from an existing table.
You can also use DROP TABLE command to delete complete table but it would remove complete table
structure form the database and you would need to re-create this table once again if you wish you store
some data.
Syntax:
The basic syntax of TRUNCATE TABLE is as follows:

Example:
Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 58
Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Consider the CUSTOMERS table having the following records:

Following is the example to truncate:

Now, CUSTOMERS table is truncated and following would be the output from SELECT statement:

SQL HAVING CLAUSE


The HAVING clause enables you to specify conditions that filter which group results appear in the final
results. The WHERE clause places conditions on the selected columns, whereas the HAVING clause
places conditions on groups created by the GROUP BY clause.
Syntax:
The following is the position of the HAVING clause in a query:

The HAVING clause must follow the GROUP BY clause in a query and must also precede the ORDER
BY clause if used. The following is the syntax of the SELECT statement, including the HAVING
clause:

Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 59


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Following is the example, which would display record for which similar age count would be more than
or equal to 2:

This would produce the following result:

SQL Sub Queries


A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN etc.
There are a few rules that subqueries must follow:
 Subqueries must be enclosed within parentheses.
 A subquery can have only one column in the SELECT clause, unless multiple columns are in
the main query for the subquery to compare its selected columns.
 An ORDER BY cannot be used in a subquery, although the main query can use an ORDER
BY. The GROUP BY can be used to perform the same function as the ORDER BY in a
subquery.
 Subqueries that return more than one row can only be used with multiple value operators, such
as the IN operator.
 The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY,
CLOB, or NCLOB.
 A subquery cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a subquery; however, the BETWEEN operator
can be used within the subquery.
Subqueries with the SELECT Statement:
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 60


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Example:
Consider the CUSTOMERS table having the following records:

Now, let us check the following subquery with SELECT statement:

This would produce the following result:

Subqueries with the INSERT Statement:


Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned
from the subquery to insert into another table. The selected data in the subquery can be modified with
any of the character, date or number functions.
The basic syntax is as follows:

Example:
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy
complete
CUSTOMERS table into CUSTOMERS_BKP, following is the syntax:

Subqueries with the UPDATE Statement:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 61


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows:

Example:
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
Following example updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose
AGE is greater than or equal to 27:

This would impact two rows and finally CUSTOMERS table would have the following records:

Subqueries with the DELETE Statement:


The subquery can be used in conjunction with the DELETE statement like with any other statements
mentioned above.
The basic syntax is as follows:

Example:
Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.
Following example deletes records from CUSTOMERS table for all the customers whose AGE is
greater than or equal to 27:

This would impact two rows and finally CUSTOMERS table would have the following records:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 62


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL – Using Sequences


A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are frequently
used in databases because many applications require each row in a table to contain a unique value, and
sequences provide an easy way to generate them.
This chapter describes how to use sequences in MySQL.
Using AUTO_INCREMENT column:
The simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and leave
rest of the things to MySQL to take care.
Example:
Try out the following example. This will create table and after that it will insert few rows in this table
where it is not required to give record ID because its auto-incremented by MySQL.

Renumbering an Existing Sequence:


There may be a case when you have deleted many records from a table and you want to re-sequence all
the records. This can be done by using a simple trick but you should be very careful to do so if your
table is having joins with other table.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 63


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it


is to drop the column from the table, then add it again. The following example shows how to renumber
the id values in the insect table using this technique:

Starting a Sequence at a Particular Value:


By default, MySQL will start sequence from 1 but you can specify any other number as well at the time
of table creation. Following is the example where MySQL will start sequence from 100

Alternatively, you can create the table and then set the initial sequence value with ALTER TABLE

SQL Useful Functions


SQL has many built-in functions for performing processing on string or numeric data. Following is the
list of all useful SQL built-in functions:
 SQL COUNT Function - The SQL COUNT aggregate function is used to count the number of
rows in a database table.
 SQL MAX Function - The SQL MAX aggregate function allows us to select the highest
(maximum) value for a certain column.
 SQL MIN Function - The SQL MIN aggregate function allows us to select the lowest
(minimum) value for a certain column.
 SQL AVG Function - The SQL AVG aggregate function selects the average value for certain
table column.
 SQL SUM Function - The SQL SUM aggregate function allows selecting the total for a numeric
column.
 SQL SQRT Functions - This is used to generate a square root of a given number.
 SQL RAND Function - This is used to generate a random number using SQL command.
 SQL CONCAT Function - This is used to concatenate any string inside any SQL command.
 SQL Numeric Functions - Complete list of SQL functions required to manipulate numbers in
SQL.
 SQL String Functions - Complete list of SQL functions required to manipulate strings in SQL.

SQL COUNT Function


SQL COUNT function is the simplest function and very useful in counting the number of records, which
are expected to be returned by a SELECT statement.
To understand COUNT function, consider an employee_tbl table, which is having the following
records:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 64


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Now suppose based on the above table you want to count total number of rows in this table, then you
can do it as follows:

Similarly, if you want to count the number of records for Zara, then it can be done as follows:

NOTE: All the SQL queries are case insensitive, so it does not make any difference if you give ZARA
or Zara in WHERE CONDITION.

SQL MAX Function


SQL MAX function is used to find out the record with maximum value among a record set.
To understand MAX function, consider an employee_tbl table, which is having the following records:

Now suppose based on the above table you want to fetch maximum value of daily_typing_pages, then
you can do so simply using the following command:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 65


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

You can find all the records with maximum value for each name using GROUP BY clause as follows:

You can use MIN Function along with MAX function to find out minimum value as well. Try out the
following example:

SQL MIN Function


SQL MIN function is used to find out the record with minimum value among a record set.
To understand MIN function, consider an employee_tbl table, which is having the following records:

Now suppose based on the above table you want to fetch minimum value of daily_typing_pages, then
you can do so simply using the following command:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 66


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

You can find all the records with minimum value for each name using GROUP BY clause as follows:

You can use MIN Function along with MAX function to find out minimum value as well. Try out the
following example:

SQL AVG Function


SQL AVG function is used to find out the average of a field in various records.
To understand AVG function, consider an employee_tbl table, which is having the following records:

Now suppose based on the above table you want to calculate average of all the dialy_typing_pages,
then you can do so by using the following command:
Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 67
Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

You can take average of various records set using GROUP BY clause. Following example will take
average all the records related to a single person and you will have average typed pages by every person.

SQL SUM Function


SQL SUM function is used to find out the sum of a field in various records.
To understand SUM function, consider an employee_tbl table, which is having the following records:

Now suppose based on the above table you want to calculate total of all the dialy_typing_pages, then
you can do so by using the following command:

You can take sum of various records set using GROUP BY clause. Following example will sum up all
the records related to a single person and you will have total typed pages by every person

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 68


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL SQRT Function


SQL SQRT function is used to find out the square root of any number. You can Use SELECT statement
to find out sqrt root of any number as follows:

You are seeing float value here because internally SQL will manipulate square root in float data type.
You can use SQRT function to find out square root of various records as well. To understand SQRT
function in more detail, consider an employee_tbl table, which is having the following records:

Now suppose based on the above table you want to calculate square root of all the dialy_typing_pages,
then you can do so by using the following command:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 69


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL RAND Function


SQL has a RAND function that can be invoked to produce random numbers between 0 and 1

When invoked with an integer argument, RAND( ) uses that value to seed the random number generator.
Each time you seed the generator with a given value, RAND( ) will produce a repeatable series of
numbers:

You can use ORDER BY RAND() to randomize a set of rows or values as follows:
To understand ORDER BY RAND() function, consider an employee_tbl table, which is having the
following records:

Now, use the following commands:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 70


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

SQL CONCAT Function


SQL CONCAT function is used to concatenate two strings to form a single string. Try out the following
example:

To understand CONCAT function in more detail, consider an employee_tbl table, which is having the
following records

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 71


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Now suppose based on the above table you want to concatenate all the names employee ID and
work_date, then you can do it using the following command:

SQL - Using Views


A view is nothing more than a SQL statement that is stored in the database with an associated name. A
view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one or
many tables which depends on the written SQL query to create a view.
Views, which are kind of virtual tables, allow users to do the following:
 Structure data in a way that users or classes of users find natural or intuitive.
 Restrict access to the data such that a user can see and (sometimes) modify exactly what they
need and no more.
 Summarize data from various tables which can be used to generate reports.
Creating Views:
Database views are created using the CREATE VIEW statement. Views can be created from a single
table, multiple tables, or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
The basic CREATE VIEW syntax is as follows:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 72


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

You can include multiple tables in your SELECT statement in very similar way as you use them in
normal SQL SELECT query.
Example:
Consider the CUSTOMERS table having the following records:

Now, following is the example to create a view from CUSTOMERS table. This view would be used to
have customer name and age from CUSTOMERS table:

Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table. Following is
the example:

This would produce the following result:

The WITH CHECK OPTION:


The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH
CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view
definition.
If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.
The following is an example of creating same view CUSTOMERS_VIEW with the WITH CHECK
OPTION:

The WITH CHECK OPTION in this case should deny the entry of any NULL values in the view's AGE
column, because the view is defined by data that does not have a NULL value in the AGE column.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 73


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Updating a View:
A view can be updated under certain conditions:
 The SELECT clause may not contain the keyword DISTINCT.
 The SELECT clause may not contain summary functions.
 The SELECT clause may not contain set functions.
 The SELECT clause may not contain set operators.
 The SELECT clause may not contain an ORDER BY clause.
 The FROM clause may not contain multiple tables.
 The WHERE clause may not contain subqueries.
 The query may not contain GROUP BY or HAVING.
 Calculated columns may not be updated.
 All NOT NULL columns from the base table must be included in the view in order for the
INSERT query to function.
So if a view satisfies all the above mentioned rules then you can update a view. Following is an example
to update the age of Ramesh:

This would ultimately update the base table CUSTOMERS and same would reflect in the view itself.
Now, try to query base table, and SELECT statement would produce the following result:

Inserting Rows into a View:


Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also
apply to the INSERT command.
Here, we cannot insert rows in CUSTOMERS_VIEW because we have not included all the NOT NULL
columns in this view, otherwise you can insert rows in a view in similar way as you insert them in a
table.
Deleting Rows into a View:
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT
commands apply to the DELETE command.
Following is an example to delete a record having AGE= 22.

This would ultimately delete a row from the base table CUSTOMERS and same would reflect in the
view itself. Now, try to query base table, and SELECT statement would produce the following result:

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 74


Quick Lab Reference GUIDE for Database & SQL / By ENDELLY [email protected]

Dropping Views:
Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The
syntax is very simple as given below:

Following is an example to drop CUSTOMERS_VIEW from CUSTOMERS table:

SQL Transactions
A transaction is a unit of work that is performed against a database. Transactions are units or sequences
of work accomplished in a logical order, whether in a manual fashion by a user or automatically by
some sort of a database program.
A transaction is the propagation of one or more changes to the database. For example, if you are creating
a record or updating a record or deleting a record from the table, then you are performing transaction
on the table. It is important to control transactions to ensure data integrity and to handle database errors.
Practically, you will club many SQL queries into a group and you will execute all of them together as
a part of a transaction.
Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the acronym ACID:
 Atomicity: ensures that all operations within the work unit are completed successfully;
otherwise, the transaction is aborted at the point of failure, and previous operations are rolled
back to their former state.
 Consistency: ensures that the database properly changes states upon a successfully committed
transaction.
 Isolation: enables transactions to operate independently of and transparent to each other.
 Durability: ensures that the result or effect of a committed transaction persists in case of a
system failure.
Transaction Control:
There are following commands used to control transactions:
 COMMIT: to save the changes.
 ROLLBACK: to rollback the changes.
 SAVEPOINT: creates points within groups of transactions in which to ROLLBACK
 SET TRANSACTION: Places a name on a transaction.
Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE only.
They cannot be used while creating tables or dropping them because these operations are automatically
committed in the database.
The COMMIT Command:
The COMMIT command is the transactional command used to save changes invoked by a transaction
to the database.

Reference: SQL TUTORIAL / Simply Easy Learning by www.tutorialspoint.com 75

You might also like