SQL Commands: SR - No. Command & Description
SQL Commands: SR - No. Command & Description
1 CREATE
Creates a new table, a view of a table, or other object in the database.
2 ALTER
Modifies an existing database object, such as a table.
3 DROP
Deletes an entire table, a view of a table or other objects in the database.
4. RENAME
1 INSERT
Creates a record.
2 UPDATE
Modifies records.
3 DELETE
7
Deletes records.
DQL-Data Query Language
4 SELECT
Retrieves certain records from one or more tables.
Creating a basic table involves naming the table and defining its columns and each
column's data type.
Data types:
Varchar(size)-Variable length string(can be store letter,number ,special
characters)
Int-integer
Float(size,d):Floating point Number,(where size represents digit, d –number
after decimal)
Double(size,d)-Floating point number(large numbers)
Boolean-True (result will be non zero)or false(result will be zero)
Date-Date(YYYY-MM-DD)
.....
columnN datatype,
Example:
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL, AGE INT NOT NULL,ADDRESS CHAR (25), SALARY DOUBLE(18, 2),
7
PRIMARY KEY (ID));
or
CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255),Age int,CONSTRAINT PK_Person PRIMARY
KEY (ID,LastName));
or
CREATE TABLE Persons ( ID int NOT NULL PRIMARY KEY, LastName varchar(255)
NOT NULL, FirstName varchar(255), Age int);
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.
The basic syntax of ALTER TABLE to add a new column in an existing table is as
follows:
ALTER TABLE table_name ADD column_name datatype;
Eg: ALTER TABLE CUSTOMERS ADD CITY CHAR(20);
The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a
table is as follows:
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a
table is as follows:
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is
as follows:
ALTER TABLE TableName ADD PRIMARY KEY (ColumnName);
or
ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY (ID);
The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a
table is as follows:
7
SQL - DROP Table
The SQL DROP TABLE statement is used to remove a table definition and all data,
constraints, and permission specifications for that table.
Basic syntax of DROP TABLE statement is as follows:
DML
The SQL INSERT INTO Statement is used to add new rows of data to a table in the
database.
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:
The SQL UPDATE Query is used to modify the existing records in a table.
7
You can use WHERE clause with UPDATE query to update selected rows otherwise
all the rows would be affected.
Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:
UPDATE table_name SET column1 = value1, column2 = value2...., columnN =
valueN WHERE [condition];
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.
The basic syntax of DELETE query with WHERE clause is as follows:
DELETE FROM table_name WHERE [condition];
Now, CUSTOMERS table would not have any record If you want to DELETE all the
records from CUSTOMERS table, you do not need to use WHERE clause and
DELETE query would be as follows:
SQL> DELETE FROM CUSTOMERS;
Drop statement is used to delete the entire table structure. Delete is used just to delete
the data. Table structure will be unaffected.
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:
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;
SQL - LIKE Clause
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.
Syntax
The basic syntax of % and _ is as follows −
or
or
or
or
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 the query results in an ascending order by default.
Syntax
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
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 the column-list.
Example
Consider the CUSTOMERS table having the following records −
7
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
The following code block has an example, which would sort the result in an ascending order
by the NAME and the SALARY −
7
Module-3 DBMS
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ +- GROUP
SQL + BY+Clause + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 GROUP
The SQL | Indore BY| 10000.00
clause is| used in collaboration with the SELECT statement to
| 6 | Komal | 22 | MP | 4500.00 |
arrange identical data into groups. This GROUP BY clause follows the WHERE
| 2 | Khilan | 25 | Delhi | 1500.00 |
clause| in
| 3 | kaushik 23a| SELECT
Kota | statement
2000.00 |and precedes the ORDER BY clause.
| 5 | Hardik | 27 | Bhopal | 8500.00 |
Syntax
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+ + The basic + syntax
+ of a GROUP
+ BY
+ clause is shown in the following code block. The
GROUP BY clause must follow the conditions in the WHERE clause and must
precede the ORDER BY clause if one is used.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
If you want to know the total amount of the salary on each customer, then the GROUP BY
query would be as follows.
+Now, let +us look at a+table where the CUSTOMERS table has the following records with
| NAME | SUM(SALARY) |
duplicate names −
+ + +
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
19 | 2000.00 |
| kaushik
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
Module-3 DBMS
+ + + + + +
| 6 | Komal | 22 | MP | 4500.00 |
+ + + + + +
Now again, if you want to know the total amount of salary on each customer, then the
GROUP BY query would be as follows −
+ + +
| NAME | SUM(SALARY) |
+ + +
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+ + +
Syntax
The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows −
+ + + + + + First,
| ID | NAME | AGE | ADDRESS | SALARY | let us
+ + + + + + see
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | how
| 2 | Khilan | 25 | Delhi | 1500.00 | the
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
following SELECT query returns the duplicate salary records.
ORDER BY SALARY;
This would produce the following result, where the salary (2000) is coming twice which is a
duplicate record from the original table.
+ +
| SALARY |
+ +
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+ +
Now, let us use the DISTINCT keyword with the above SELECT query and then see the
result.
+ +
| SALARY |
+ + Set
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+ 19 +
Module-3 DBMS
Operations in SQL
SQL supports few Set operations to be performed on table data. These are used to get
meaningful results from data, under different special conditions.
Set operators are used to join the results of two (or more) SELECT statements. The
SET operators available in sql are UNION, UNION ALL, INTERSECT, EXCEPT
(MINUS).
UNION
UNION is used to combine the results of two or more Select statements. However it
will eliminate duplicate rows from its result set.
In case of union, number of columns and datatype must be same in both the tables.
Example of UNION
The First table,
ID Name
1 Abhi
2 Adam
ID Name
2 Adam
3 Chester
ID NAME
1 Abhi
2 Adam
3 Chester
UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
ID NAME
1 Abhi
2 Adam
ID NAME
2 Adam
3 Chester
ID NAME
1 Abhi
2 Adam
2 Adam
3 Chester
INTERSECT
Intersect operation is used to combine two SELECT statements, but it only returns the
records which are common from both SELECT statements.
In case of Intersect the number of columns and datatype must be same.
Example of Intersect
The First table,
ID NAME
1 Abhi
2 Adam
ID NAME
19
Module-3 DBMS
2 Adam
3 Chester
ID NAME
2 Adam
EXCEPT (MINUS)
Minus operation combines result of two Select statements and return only those result
which belongs to first set of result.
Example of Minus
The First table,
ID NAME
1 Abhi
2 Adam
ID NAME
19
Module-3 DBMS
2 Adam
3 Chester
ID NAME
1 Abhi
COUNT( )
The COUNT() function returns the number of rows that matches a specified criteria.
Syntax is
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
SUM ( )
To calculate the sum of units in stock by product category, you use the SUM function
as follows:
AVG ( )
SELECT AVG(column_name)
FROM table_name
WHERE condition;
To calculate the average units in stock of the products, you use the AVG function as
follows:
SELECT AVG(unitsinstock) FROM products;
19
Module-3 DBMS
MIN ( )
The MIN( ) function returns the smallest value of the selected column.MIN( ) Syntax is
SELECT MIN(column_name)
FROM table_name
WHERE condition;
To get the minimum units in stock of products in the products table, you use the
MIN function as follows:
MAX ( )
The MAX() function returns the largest value of the selected column.
MAX() Syntax is
SELECT MAX(column_name)
FROM table_name
WHERE condition;
MAX function example
To get the maximum units in stock of products in the products table, you use
the MAX function as shown in the following query:
+ + + + + +
+ + + + + +
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
19
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS This
would
WHERE ID IN (SELECT ID
FROM CUSTOMERS
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY | Sub
+ + + + + + queries
| 4 | Chaitali | 25 | Mumbai | 6500.00 | with the
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
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.
22
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have CUSTOMERS_BKP table available which is backup of
CUSTOMERS table. The following example updates SALARY by 0.25 times in the
CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
22
[ WHERE) condition];
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table. The following example deletes the records from the
CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
Views
A View is a single table that is derived from other tables.
These other tables can be base tables or previously defined views.
A View does not necessarily exist in physical form; It is considered to be a virtual
table
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:
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, you can query CUSTOMERS_VIEW in similar way as you query an actual
table.
Following is the example:
SELECT * FROM CUSTOMERS_VIEW;
| name | age |
+ + +
| Ramesh | 32 |
22
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
+ + +
Updating Views:
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:
DROP VIEW view_name;
22
Inline View
It is possible to define a view table in the FROM clause of an SQL query. This is known as
in-line view. In this case, the view is defined within the query itself.
Advantages of Views
Restrict Data Access and/or Simplify Data Access
Simplify Data Manipulation
Import and Export Data
Merge Data
Triggers
Triggers are stored programs, which are automatically executed or fired when some
events occur.
Triggers are, in fact, written to be executed in response to any of the following
events –
1. A database manipulation (DML) statement (DELETE, INSERT,
or UPDATE)
2. A database definition (DDL) statement (CREATE, ALTER, or
DROP).
3. A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event
is associated.
Benefits of Triggers
Triggers can be written for the following purposes −
22
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF column_name]
ON table_name
WHEN (condition)
BEGIN
……………
END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing
trigger with the trigger_name.
{BEFORE | AFTER } − This specifies when the trigger will be executed.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF column_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.
Example
To start with, we will be using the CUSTOMERS table.
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+ + + + + +
22
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
DECLARE
sal_diff number;
BEGIN
END;
/
executed at the SQL prompt, it produces the following result −
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −
22
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null.
Let us now perform one more DML operation on the CUSTOMERS table. The UPDATE
statement will update an existing record in the table −
UPDATE customers
22