Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

SQL (Structured Query Language)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16
At a glance
Powered by AI
SQL is a language used to operate relational databases. It allows users to define, manipulate, and retrieve data stored in tables. Some key uses of SQL include accessing and modifying data, as well as managing the structure of databases and tables.

SQL is used to access, manipulate, and retrieve data stored in relational database management systems. It allows users to define, manage, and query data within these systems.

The main SQL commands are DDL, DML, DCL, TCL, and DQL. DDL is used to define database schemas and tables. DML manipulates data within tables. DCL manages user permissions and access. TCL manages transactions. And DQL retrieves and views data.

4.

SQL (Structured Query Language)


SQL is a language to operate databases; it includes database creation,
deletion, fetching rows, modifying rows, etc. SQL is an ANSI (American
National Standards Institute) standard language, but there are many
different versions of the SQL language.

What is SQL?
SQL is Structured Query Language, which is a computer language for storing,
manipulating and retrieving data stored in a relational database.

SQL is the standard language for Relational Database System. All the
Relational Database Management Systems (RDMS) like MySQL, MS Access,
Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard
database language.

Also, they are using different dialects, such as −

 MS SQL Server using T-SQL,


 Oracle using PL/SQL,

Why SQL?
SQL is widely popular because it offers the following advantages −

 Allows users to access data in the relational database management


systems.

 Allows users to describe the data.

 Allows users to define the data in a 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.


A Brief History of SQL
 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of
relational databases. He described a relational model for databases.

 1974 − Structured Query Language appeared.

 1978 − IBM worked to develop Codd's ideas and released a product


named System/R.

 1986 − IBM developed the first prototype of relational database and


standardized by ANSI. The first relational database was released by
Relational Software which later came to be known as Oracle.

Basic Structure
A relational database is a collection of tables. Each table has its own unique
name.

The basic structure of an SQL expression consists of three clauses:


 The select clause which corresponds to the projection operation. It is the
list of attributes that will appear in the resulting table.
 The from clause which corresponds to the Cartesian-product operation.
It is the list of tables that will be joined in the resulting table.
 The where clause which corresponds to the selection operation. It is the
expression that controls the which rows appear in the resulting table.

A typical SQL query has the form of:


select A1, A2, ..., An
from r1, r2, ..., rn,
where P
SQL Command

There are five types of SQL commands: DDL, DML, DCL, TCL, and
DQL.
1. Data Definition Language (DDL)

This includes changes to the structure of the table like creation of table, altering
table, deleting a table etc.

All DDL commands are auto-committed. That means it saves all the changes
permanently in the database.

Command Description
create to create new table or database
alter for alteration
truncate delete data from table
drop to drop a table
rename to rename a table

CREATE TABLE
The SQL CREATE TABLE statement is used to create a new table.
Syntax

The basic syntax of the CREATE TABLE statement is as follows −


CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
Example

The following code block is an example, which creates a CUSTOMERS table


with an ID as a primary key and NOT NULL are the constraints showing that
these fields cannot be NULL while creating records in this table −
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

ALTER TABLE
The SQL ALTER TABLE command is used to add, delete or modify columns
in an existing table. You should also use the ALTER TABLE command to add
and drop various constraints on an existing table.

Syntax

The basic syntax of an ALTER TABLE command to add a New Column in an


existing table is as follows.
ALTER TABLE table_name ADD column_name datatype;

The basic syntax of an ALTER TABLE command to DROP COLUMN in an


existing table is as follows.
ALTER TABLE table_name DROP COLUMN column_name;

The basic syntax of an ALTER TABLE command to change the DATA TYPE
of a column in a table is as follows.
ALTER TABLE table_name MODIFY COLUMN column_name datatype;

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 a TRUNCATE TABLE command is as follows.


TRUNCATE TABLE table_name;
Eg. TRUNCATE TABLE CUSTOMERS;

DROP or DELETE Table


The SQL DROP TABLE statement is used to remove a table definition and all
the data, indexes, triggers, constraints and permission specifications for that
table.

NOTE − You should be very careful while using this command because once a
table is deleted then all the information available in that table will also be lost
forever.

Syntax

The basic syntax of this DROP TABLE statement is as follows −


DROP TABLE table_name;
Eg. DROP TABLE CUSTOMERS;

Data Manipulation Language(DML) Commands

DML commands are used for manipulating the data stored in the table and not
the table itself.

DML commands are not auto-committed. It means changes are not permanent
to database, they can be rolled back.
Command Description
insert to insert a new row
update to update existing row
delete to delete a row
merge merging two rows or two tables

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 the INSERT INTO statement which are shown
below.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
OR
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

OR

You can create a record in the CUSTOMERS table by using the second syntax
as shown below.
INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

UPDATE Query
The SQL UPDATE Query is used to modify the existing records in a table. You
can use the WHERE clause with the UPDATE query to update the selected
rows, otherwise all the rows would be affected.

Syntax

The basic syntax of the UPDATE query with a WHERE clause is as follows −
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

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

The following query will update the ADDRESS for a customer whose ID
number is 6 in the table.
SQL> UPDATE CUSTOMERS SET ADDRESS = 'Pune' WHERE ID = 6;

UPDATE CUSTOMERS SET ADDRESS = 'Pune', SALARY = 1000.00;

DELETE Query
The SQL DELETE Query is used to delete the existing records from a table.

You can use the WHERE clause with a DELETE query to delete the selected
rows, otherwise all the records would be deleted.

Syntax

The basic syntax of the DELETE query with the WHERE clause is as follows −
DELETE FROM table_name WHERE [condition];
Example:
DELETE FROM CUSTOMERS WHERE ID = 6;

If you want to DELETE all the records from the CUSTOMERS table, you do
not need to use the WHERE clause and the DELETE query would be as follows

SQL> DELETE FROM CUSTOMERS;
DQL: Data Query Language
Data query language is used to fetch data from tables based on conditions that
we can easily apply.

Command Description
select retrieve records from one or more table

SELECT Query
The SQL SELECT statement is used to fetch the data from a database table
which returns this data in the form of a result table. These result tables are
called result-sets.

Syntax

The basic syntax of the SELECT statement is as follows −


SELECT column1, column2, columnN FROM table_name;

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.
SELECT * FROM table_name;

Example:

SELECT ID, NAME, SALARY FROM CUSTOMERS;

SELECT * FROM CUSTOMERS;

Other Clauses with select:

1.where clause:
The WHERE clause specifies criteria that restrict the contents of the results table. You can
test for simple relationships or, using subselects, for relationships between a column and a set
of columns.
Using a simple WHERE clause, the contents of the results table can be restricted.
SELECT expressions FROM TABLES WHERE conditions;

Example:

SELECT FirstName FROM Student WHERE RollNo > 15;

The following are the various SQL clauses:

2. GROUP BY

 SQL GROUP BY statement is used to arrange identical data into groups. The GROUP BY
statement is used with the SQL SELECT statement.
 The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause.
 The GROUP BY statement is used with aggregation function.

Syntax

SELECT column  FROM table_name  WHERE conditions  GROUP BY column  ORDER BY column ;

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST


Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120

Example:

SELECT COMPANY, COUNT(*)  FROM PRODUCT_MAST   GROUP BY COMPANY;  

Output:

Com1 5
Com2 3
Com3 2

3. HAVING

 HAVING clause is used to specify a search condition for a group or an aggregate.


 Having is used in a GROUP BY clause. If you are not using GROUP BY clause then
you can use HAVING function like a WHERE clause.

Syntax:

SELECT column1, column2  FROM table_name  WHERE conditions GROUP BY column1, 
column2  HAVING conditions ORDER BY column1, column2;  

Example:

SELECT COMPANY, COUNT(*)  FROM PRODUCT_MAST   GROUP BY COMP
ANY  HAVING COUNT(*)>2;  

Output:

Com1 5
Com2 3

4. ORDER BY

 The ORDER BY clause sorts the result-set in ascending or descending order.


 It sorts the records in ascending order by default. DESC keyword is used to sort the records
in descending order.

Syntax:

SELECT column1, column2  FROM table_name  WHERE condition  ORDER BY column1, column2... AS
C|DESC;  
Where

ASC: It is used to sort the result set in ascending order by expression.

DESC: It sorts the result set in descending order by expression.

Example: Sorting Results in Ascending Order

Table:

CUSTOMER

CUSTOMER_ID NAME ADDRESS

12 Kathrin US

23 David Bangkok

34 Alina Dubai

45 John UK

56 Harry US

Enter the following SQL statement:

SELECT *  FROM CUSTOMER  ORDER BY NAME;  

Output:

CUSTOMER_ID NAME ADDRESS

34 Alina Dubai

23 David Bangkok

56 Harry US

45 John UK

12 Kathrin US

Example: Sorting Results in Descending Order

Using the above CUSTOMER table

SELECT *  FROM CUSTOMER  ORDER BY NAME DESC;  

Output:

CUSTOMER_ID NAME ADDRESS

12 Kathrin US
45 John UK

56 Harry US

23 David Bangkok

34 Alina Dubai

SQL Aggregate Functions


 SQL aggregation function is used to perform the calculations on multiple rows of a
single column of a table. It returns a single value.
 It is also used to summarize the data.

aggregate Functions are all about

 Performing calculations on multiple rows


 Of a single column of a table
 And returning a single value.

Types of SQL Aggregation Function

1. COUNT FUNCTION

 COUNT function is used to Count the number of rows in a database table. It can work on
both numeric and non-numeric data types.
 COUNT function uses the COUNT(*) that returns the count of all the rows in a specified
table. COUNT(*) considers duplicate and Null.
Syntax

COUNT(*)  

or  

COUNT( [ALL|DISTINCT] expression )  

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST


Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item7 Com1 5 30 150
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Item10 Com3 4 30 120

Example: COUNT()

SELECT COUNT(*)  FROM PRODUCT_MAST;  

Output:

10

Example: COUNT with WHERE

SELECT COUNT(*)  FROM PRODUCT_MAST WHERE RATE>=20;  

Output:

Example: COUNT() with DISTINCT

SELECT COUNT(DISTINCT COMPANY)  FROM PRODUCT_MAST;    

Output:

Example: COUNT() with GROUP BY


SELECT COMPANY, COUNT(*)  FROM PRODUCT_MAST  GROUP BY COMP
ANY;  

Output:

Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

SELECT COMPANY, COUNT(*)  FROM PRODUCT_MAST  GROUP BY COMPAY  
HAVING COUNT(*)>2;  

Output:

Com1 5
Com2 3

2. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.

Syntax

SUM()  

or  

SUM( [ALL|DISTINCT] expression )  

Example: SUM()

SELECT SUM(COST)  FROM PRODUCT_MAST;  

Output:

670

Example: SUM() with WHERE

SELECT SUM(COST)  FROM PRODUCT_MAST  WHERE QTY>3;  

Output:

320
Example: SUM() with GROUP BY

SELECT SUM(COST)  FROM PRODUCT_MAST  WHERE QTY>3  GROUP BY COMPANY;  

Output:

Com1 150
Com2 170

Example: SUM() with HAVING

SELECT COMPANY, SUM(COST)  FROM PRODUCT_MAST  GROUP BY COMPANY  HAVING SUM(CO
ST)>=170;  

Output:

Com1 335
Com3 170

3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.

Syntax

AVG()  

or  

AVG( [ALL|DISTINCT] expression )  

Example:

SELECT AVG(COST)  FROM PRODUCT_MAST;  

Output:

67.00

4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.

Syntax

MAX()  or  
MAX( [ALL|DISTINCT] expression )  

Example:

SELECT MAX(RATE)  FROM PRODUCT_MAST;  

Output: 30

5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.

Syntax

MIN()  

or  

MIN( [ALL|DISTINCT] expression )  

Example:

SELECT MIN(RATE)  FROM PRODUCT_MAST;  

Output:

10

You might also like