fal Nad
STRUCTURED
QUERY LANGUAGE
Structured Query Language (SQL) is the most popular query language used by Coo
major relational database management systems such as MySQL, ORACLE, S% CHAPTER CHECKLIST
SQL Server, etc. SQL is easy to learn as the statements comprise of descriptive
english words and are not case sensitive, 717
SQL provides statements for defining the structure of the data, manipulating
data in the database, declaring constraints and retrieving data from the database
in various ways, depending on your requirements. .
SQL provides variety of tasks such as
+ Querying data. °
+ Creating, replacing, altering and dropping tables. °
+ Inserting, updating and deleting rows in a table. ®
+ Controlling access to the database.” acl
+ Guaranteeing database consistency and integrity.
Advantages of SQL
+ SQL is portable It is not platform dependent, it can be used in all types of
devices; PCs, laptops and even mobile phones also, .
+ High speed SQL queries can be used to retrieve large amount of records from
a database quickly and efficiently,
+ Eagy to lea and understand SQL generally consists of english language
statements and ic is very easy to learn and understand,
+ SQLs used for relational database SQL is widely used for relational database,
SQL Statements
SQL Data Types
DDLStatements/Commands
DML Statements/Commands|
Working with Null Values
Aggregate Functions
Group By Statement
Having Clause
Joinqured Query Language
ge
ats as both programming language and interactive
seme SQL can do both the jobs of being a
ey seaming language as well asan interactive language
f
pitpesame CE, :
Seenserer language SQL. provides client-server
rretut. Ics used for linking front end computers
aback end databases.
pepo abet based programming With theemergence of
abject based programming, object storage capabilities are
ded to rational database
pisadvantages of SQL.
pificulty in interfacing. Interfacing a SQL database is
pie complex than adding a few lines of code.
| More features implemented in proprietary way Although
sQL databases confirm to ANSI and ISO standards,
some databases go for proprietary extensions to standard
SOL to ensure vendor lock-in,
sQL STATEMENTS
QL command or statement is a special kind of sentence
gutcontains clauses and all end with a semicolon() just as
sentence ends with a period.
‘There are four types of SQL statements
LDDL (Dats Definition Language)
Ic provides statements for creation and deletion of the
database tables, views, etc.
The DDL provides a sec of definitions to specify the storage
structure in a database system.
Some DDL statements are as follows
(i) CREATE used to create new table in the database.
(ii) DROP used to delete tables from the database,
(ii) ALTER used to change the structure of the database
table, This statement can add up additional column,
drop existing, and even change the dara type of
columns involved in a database table.
(iv) RENAME used to rename a table.
2. DML (Data Manipulation Language)
manipulating the database
the databases for information
Ik provides statements for
objects. Ie is used to query ¢
retrieval.
Some DML statements are as follows
(i) INSERT used to insert data into a table.
(ii) SELECT used to retieve daa from a database
199
(iii) UPDATE used to update existing dara within a rable.
(iv) DELETE used to delete all records from a table.
3. DCL (Data Control Language)
Itis used to assign security levels in database, which involves
multiple user setups. They are used to grant defined role
and access privileges to the users.
Some DCL statements are as follows
(i) GRANT used to give user's access privileges to
database.
(ii) REVOKE used to withdraw access privileges given
with grant command.
4. TCL (Transaction Control Language)
Ic is used for controlling the transactions in a database
system. These are also used to manage the changes made by
DML.
Some TCL statements ate as follows
() COMMIT used to save the work done.
(ii) SAVEPOINT used to identify a point in a
transaction to which you can later rollback.
(ii) ROLLBACK used to restore database to original
since the last COMMIT.
(iv) SET TRANSACTION establishes properties for the
current transactions.
In this chapter, we wi
statements.
Rules for SQL commands
Rules for SQL commands are given below
( SQL statements can be typed in lowercase or
uppercase letter. SQL statements are not case
iscuss only DDL and DML
sensitive,
(ii) The statements can be typed in single line or multiple
lines.
(iii) A semicolon ()) is used to terminate the SQL
statements
ww) eer be distributed across the line but
Ww) Acoma () is used co separate parameters without a
clause.
(ci) Characters and date constants of literals
enclosed in single quotes CA). THs Must be
(vil) A command can bi i
characters. ped cither full or First four
__ iva7
200
SQL DATA TYPES
Data types are declared to identify the type of data that will
be stored in a particular field or variable.
The following list of general SQL data types are given below
Data Type Syntax Explanation (f applicable
INTEGER INTEGER A32-bitsigned integer vae
or TNT andits range trom
2147483648 102147409647.
SMALUNT _ SMALLINT 16-bit signed integer valve
and its range trom 327680
ss sora eaeane
NUMERIC NUMERIC Where, pis a precision vale
(ps) and sis a scale valve. ¢9.
numeric (6.2) is a6 digit
number that has 4 dit before
the decimal and 2 digit ater the
decimal is
DECWAL DECIMAL Where, pisaprecisionvalueand
(3) sisascale value, (sameas
7 . NUMERIC)
REAL REAL Single-precision floating point
umber.
DOUBLE DOUBLE ___Doublesprecision floating point
PRECISION PRECISION number on
FLOAT FLOAT(p) Where, pis a precision vaue
CHARACTER CHAR(x) _Where,xistnenumber of
chatacters tobe stored. This
Gsiatype wlloccupy spacetor
NULLvalves. ean hold almost
__255 characters.
CHARACTER VARCHAR(x) Where, xis the number of
VARYING characters to be stored. It wil
‘occupy space for NULL values
TRean hol atmost 2000,
characters and used in ANSI
standard
CHARACTER VARCHAR? Where, xis the number of
VARYING) characters 1 be stored. can
hold 4000 byes of characters
and used only in Oracle.
Dare ATE ‘Stores year, month and day
values
Me TIE Stores hour, minute and
second values,
Check Point 01
4, Write 1wo advantages of SQL.
2, Write he short note on DDL.
3, Write use of semicolon (:) in SQL statements
4, Which language is used to query the database for
information retrieval?
5, Write two disadvantages of SOL.
| Alone | COMPUTER SCIENCE Chass yy,
SQL Command Basics
SQL database is a way of organizing a group of tables
Ske Ses the dae 1 he form of tow and cola M4
To create a bunch of different tables that share a coming,
theme, you would group them into one database to may”
the management process easier. So, for manipulating dar
we need to know about database commands, why a
described below
Creating and Using a Database
Create a database Creating database is an easier task, Yoy
need to just type the name of the database in a CREATE
DATABASE command.
Syntax
CREATE DATABASE CIF NOT
EXISTS];
CREATE DATABASE command will create an. emp
database with che specified name and would not contin
any table.
IF NOT EXISTS is an optional part of this seatement which
prevents you from an error if there exists a database with the
given name in the database catalog.
For example, nysq\>CREATE DATABASE BOOK:
Output Query OK, 1 row affected <0.01 sec
Select a Database
Creating database is not enough for use. Before working
with tables, first you have to select the database,
The only thing need to be considered before selecting 2
database is that it must already exist. To select a databise
‘USE command is used.
Syntax USE :;
For example, mysq)>USE ENGBOOK:
‘Where, USE command makes the specified database asa
current working database and EGNBOOK is the database
name.
Output Database changed
Show Databases
To check the names of the existing databases on the sever
you need to use the SHOW command. This will provide
you the information about databases and the contents
available in it.
Syntax
SHOW DATABASES;
For example,
mmysq]>SHOW DATABASES;yr
gostred Query Language
jxtput
Bo0K
ScHOOL j
copies}
stupent }
yopping a Database
prabase, can be removed or deleted using DROP
jonmand. But before deleting a database make sure that
x1 do not need the data stored in different tables of a
Yabase because when you delete a database, all its tables
sho gets removed along with it,
gyntax
OROP DATABASE ;
fir xample,
sysq12DROP DATABASE, SCHOOL:
Output
Query 0K, 1 row affected (0.04 sec)
‘+ Drop command permanently removes the
database.
+ MySQL is not case-sensitive,
'S0 you can write SOL commands either in
GIGO uppercase o: lowercase bul for UNIX MySQL is
case-sensitive,
DDL STATEMENTS/COMMANDS
Some DDL statements are as follows
CREATE Statement
The CREATE statement is used to create a table in a
database. In this command, we need to give information
about table like number of columns, rows and its types
and constraints.
Syntax
CREATE TABLE
q
mn_namel>(()]
uae Coonstraints).
rn_name2><éate_typert()1
ae Ceonstratnts),
e3>)]
anna
Displaying the Table Structure
DESCRIPTION or DESC. command is used 0
the structure of a table that you have created,
‘This command display the column names, available data
items with theie data types.
verify
Syntax
DESCRIBE :;
DESC
WHERE;
For example, query to display EMP_NAME and
EMP_SALARY for those employees whose salary is great
than or equal co 25000.
mysql> SELECT EMP_NAME,EMP_SALARY
FROM COMPANY
WHERE EMP_SALARY> = 25000;
+ =+
Rahul Sharma t
: 2600}
{Vikas Mittal! 26000 fy
{Uday Singh} 26000 |
3 rows in set (0,00 sec) Mar
‘When we use relational operators with character data {YP
< means earlier in the alphabet and > means later in the
alphabet ‘Bangalore ‘<’ ‘Brajl’ as ‘a’ comes before ‘f i®
alphabet.siructured Query Language
sogical Operators
icl operators compare two conditions at a time to
Deere toe be selected for the output,
aa operators are also called boolean operat
ors, because
see operators return a boolean datatype value as TRUE,
oc FALSE.
‘When retrieving data using a SELECT statement, you ean
we these operators in the WHERE clause,
which allows
you to combine more than one condition,
Sone ofthe BooleanlLogical operators wed in SQL are as
OPERATOR DESCRIPTION
NO Loti! AND compares two expressions ang
{etumn tue, when both expressions are roe
AR t29ical OR compares two expressions ang
‘elu tue, when atleast one ofthe,
expressions is rue
NoT NOT takes a single expression as an
‘tgument and changes its value tom false to
tue or rom tu
eto false. You can use an
exclamation poi
int () in place ofthis operator
‘Syntax
SELECT |* |
FROM