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

SQL Queries: 1.to Implement Various DDL, DML, DCL Commands in SQL

The document discusses SQL queries and constraints. It provides examples of using DDL commands like CREATE TABLE, ALTER TABLE, and DROP TABLE to define and modify table schemas. It also demonstrates DML commands like INSERT, SELECT, DELETE, and UPDATE to manipulate data. Constraints are defined that can be applied to table columns to ensure data integrity, such as primary keys, unique constraints, default values and nullability.

Uploaded by

wolkarix
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views

SQL Queries: 1.to Implement Various DDL, DML, DCL Commands in SQL

The document discusses SQL queries and constraints. It provides examples of using DDL commands like CREATE TABLE, ALTER TABLE, and DROP TABLE to define and modify table schemas. It also demonstrates DML commands like INSERT, SELECT, DELETE, and UPDATE to manipulate data. Constraints are defined that can be applied to table columns to ensure data integrity, such as primary keys, unique constraints, default values and nullability.

Uploaded by

wolkarix
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

SQL QUERIES

1.To implement various DDL, DML,DCL commands in SQL.

Data Definition Language Commands: A database scheme is specified by a set of definitions


which are expressed by a special language called a data definition language (DDL). The result of
compilation of DDL statements is a set of tables which are stored in a special file called data dictionary.

Various DDL commands are:

1.CREATE TABLE: Tables are defined with the CREATE TABLE command. When a table is created. Its
columns are named, data types and sizes are supplied for each column. Each table must at least have
one column. The syntax of CREATE TABLE command is:

CREATE TABLE <table-name>

(<column-name> <data type> [(<size)],

<column-name> <data type> [(<size>)…]);

To create an employee table whose scheme is as follows:

Employee (ecode, ename, sex, grade, gross)

SQL command:

CREATE TABLE emp

( ecode integer,

ename char(20),

sex char(1),

grade char(2),

gross decimal);

Output:

emp

ecode ename sex grade Gross


2. ALTER TABLE: It is used to change the definition of existing tables. Usually it can add columns to a
table. Sometimes it can delete columns or change their sizes.

Syntax:

ALTER TABLE <table-name> ADD <column-name> <data type> <size>;

The new column will be added with NULL values for all rows currently in the table.

For instance, to add a new column tel_no of type integer in table emp

ALTER TABLE emp

ADD (tel_no integer);

OUTPUT:

emp

ecode ename sex grade gross tel_no

To modify existing columns, ALTER TABLE command can be used as;

ALTER TABLE <table-name>

MODIFY (columnname newdatatype (newsize));

For instance to modify column ename to be 30 characters wide,

ALTER TABLE emp

MODIFY (ename (30));

3. DROP TABLE: This command lets us drop a table from the database. The SQL requires us to empty
a table before we eliminate from the database. To remove all the rows from the table, we use DELETE
command.

If we want to delete emp table, we first remove all the rows.

DELETE FROM emp;

Then we can drop the empty table emp as follows:

DROP TABLE emp;


Once this command is given, the table name is no longer recognized and no more commands can be
given on that object.

4. CREATE VIEW: A view is a virtual table with no data, but can be operated like any other table.
CREATE VIEW taxpayee AS

SELECT*

FROM emp

WHERE gross>8000;

This query creates a view which contains only those rows of table emp where value of gross is greater
than 8000.

ecode Ename sex grade gross


1001 Priya F A1 8670

5. DROP VIEW: To delete a view from the database the DROP VIEW command is used.
DROP VIEW taxpayee

Drops the view taxpayee from the database. When a view is dropped , it does not cause any change in
its base table.

DATA MANIPULATION LANGUAGE: After the database scheme has been specified and the database
has been created, the data can be manipulated using a set of procedures which are expressed by data
manipulation language (DML). Manipulation means retrieval, insertion, deletion, modification of
information.

The Insert command: The rows (tuples) are added to relations using INSERT command.

SYNTAX:

INSERT INTO emp

VALUES (1001, ‘Priya’,’F’,’A1’, 8670.00);

INSERT INTO emp

VALUES (1002,’Prateek’,’M’,’A2’, 7560.00);


VALUES (1003,’Hardik’,’M’,’B1’, 6325.00);

INSERT INTO emp

VALUES (1004, ‘Sakshi’,’F’,’B2’5120.00);

INSERT INTO emp

VALUES (1005,’Eti’,’F’,’C1’, 4450.00);

INSERT INTO emp

VALUES (1006,’Priya’,’F’,’B2’, 5000.00);

Output:

emp

Ecode Ename sex Grade gross


1001 Priya F A1 8670
1002 Prateek M A2 7560
1003 Hardik M B1 6325
1004 Sakshi F B2 5120
1005 Eti F C1 4450
1006 Priya F B2 5000

INSERT command can also be used to take values from one table and place them in another using it with
a query.

INSERT INTO emp1

SELECT* FROM emp

WHERE gross> 7000.00;

OUTPUT:

emp1

Ecode Ename sex grade gross


1001 Priya F A1 8670
1002 Prateek M A2 7560

2. The SELECT command: It lets us make queries on the database. A query is a command that is given
to produce certain specified information from the database.
SYNTAX:

SELECT <coloumn-name> [,<column-name>,….]

FROM <table-name>;

QUERY:

SELECT ecode, ename

FROM emp;

OUTPUT:

Ecode Ename
1001 Priya
1002 Prateek
1003 Hardik
1004 Sakshi
1005 Eti
1006 Priya

While giving a query, the result can be obtained in any order.

SELECT ename, ecode, sex, grade, gross

FROM emp;

OUTPUT:

Ename ecode sex grade gross


Priya 1001 F A1 8670
Prateek 1002 M A2 7560
Hardik 1003 M B1 6325
Sakshi 1004 F B2 5120
Eti 1005 F C1 4450
Priya 1006 F B2 5000

Eliminating Redundant data:

By default, data is selected from all the rows of the table, even if the data appearing in the result is
duplicated. The DISTINCT keyword eliminates duplicate rows from the result of a select statement.
SELECT DISTINCT ename

FROM emp;

Ename
Priya
Prateek
Hardik
Sakshi
Eti

Whenever distinct is used, only one NULL value is returned in the results, no matter how many NULL
values are encountered.

3. The DELETE command: It removes the rows from a table. It removes the entire rows, not the
individual field values, so no field argument is needed or accepted.

SYNTAX:

DELETE FROM <table-name>

[WHERE<predicate>];

To remove rows from emp where gross>6000.00

DELETE FROM emp

WHERE gross>6000.00;

Ecode Ename sex grade gross


1001 Priya F A1 8670
1002 Prateek M A2 7560
1003 Hardik M B1 6325

4.The UPDATE command: It is used to change some or all of the values in a existing row. It specifies the
row to be changed using WHERE clause, and the new data using the SET keyword. The new data can be
specified as a constant, an expression or data from other tables.

UPDATE emp

SET grade=B2

WHERE gross=4450;
OUTPUT: emp

Ecode Ename sex grade gross


1001 Priya F A1 8670
1002 Prateek M A2 7560
1003 Hardik M B1 6325
1004 Sakshi F B2 5120
1005 Eti F B2 4450
1006 Priya F B2 5000
2.To implement all the constraints on the table emp.
A constraint is a condition or check applicable on a field or set of fields.

When we create a table, we can place constraints on the values that can be entered into its fields. If this
is specified, SQL will reject any values that violate the criteria we define.

The two basis types of constraints are column constraints and table constraints. The difference between
the two is that former applies to individual columns and the latter to groups of one or more columns.

SYNTAX:

CREATE TABLE <table-name>

(<column-name> <data type> [<size>]<column constraint>,

<column-name> ,data type> [<size>]<column constraint>….

<table constraint> (<column-name>) [,<column-name>…])..);

Different constraints:

These constraints ensure database integrity, thus are sometimes called database integrity constraints.

1.Unique constraint. It ensures that no two rows have the same value in the specified column(s).

2.Primary Key Constraint: It declares the column as primary key of the table. This is similar to unique
constraint except that only one column(or one group of column) can be applied in this constraint.

3.Default constraint: A default value can be specified for a column using the default clause. When user
does not specify a value for the column(having default value, the defined value is inserted in the field.

4.NOT NULL constraint: When we want a field to be not null, we specify the constraint NOT NULL
against the field. In that case, an attempt to enter a null value raises an error.

5.CHECK constraint: This constraint limits values that can be inserted into a column of a table
Now we redefine the schema of table emp by applying various constraints on its attributes.

CREATE TABLE employee

( ecode integer PRIMARY KEY,

ename char(20),

sex char(1),

grade char(2) DEFAULT=’E1’;

gross decimal CHECK(gross>2000);

NOT NULL(ename, sex)); ------- the table constraint

The above definition of table employee specifies that ecode is the PRIMARY KEY of the table, ename and
sex fields cannot be left unspecified, if no value is specified for a grade,’E1’ wll serve as a default value
and finally gross value should be greater than 2000.

INSERT INTO emp

VALUES(1001, ‘Priya’,’F’,’A1’,8670.00);

INSERT INTO emp

VALUES(1002,’Prateek’,’M’,’A2’,7560.00);

INSERT INTO emp

VALUES(1003,’Hardik’,’M’,6325.00);

INSERT INTO emp

VALUES(1004, ‘Sakshi’,’F’,5120.00);

INSERT INTO emp

VALUES(1005,’Eti’,’F’,4450.00);

INSERT INTO emp

VALUES(1006,’Priya’,’F’,’B2’,5000.00);
employee

Ecode Ename sex grade gross


1001 Priya F A1 8670
1002 Prateek M A2 7560
1003 Hardik M E1 6325
1004 Sakshi F E1 5120
1005 Eti F E1 4450
1006 Priya F B2 5000

Since all the constraints are satisfied, no error is raised and default value is inserted where not specified.

To explore SELECT clause using WHERE, ORDER BY, GROUP BY, HAVING clauses and using BETWEEN and
LIKE operators.

The WHERE clause in SELECT statement specifies the criteria for selection of rows to be returned.

SYNTAX:

SELECT <column-name>…..

FROM <table-name>

WHERE <condition>;

To display the ename and ecode for the employees whose gross is greater than 4000.

SELECT ecode, ename

FROM emp

WHERE gross>5000;

1001 Priya
1002 Prateek
1003 Hardik
1004 Sakshi

Condition based on a range:

The BETWEEN operator defines a range of values that the column values must fall in to make the
condition true.
To display the ename, ecode and grade of all employee whose gross is in between 5000 to 7000(both
inclusive).

SELECT ecode, ename, gross

FROM emp

WHERE gross BETWEEN 5000 AND 7000;

Ecode Ename gross


1003 Hardik 6325
1004 Sakshi 5120
1006 Priya 5000

Condition based on pattern matches:

SQL includes a string matching operator, LIKE, for comparisons on character strings using patterns.
Patterns are described using two special wildcard characters:

 Percent(%),. The % character matches any substring.


 Underscore(_). The _character matches any character.
 LIKE ”wx\%yz%” ESCAPE “\” matches all strings beginning with “wx%yz”
 LIKE ”wx\\yz%” ESCAPE “\” matches all strings beginning with “wx\yz”

To display ename and grade of those employees where ename starts with Har or contains the string
aksh or is 3 letters long.

SELECT ename, grade

FROM emp

WHERE ename LIKE “Har%” or ename LIKE ”%aksh% or ename like”___”;

Ename Grade
Hardik B1
Sakshi B2
Eti C1
Order By Clause: Whenever a SELECT query is executed, the resulting rows emerge in a predefined
order. We can sort the results of a query in a specific order using ORDER BY clause. The ORDER BY clause
allows sorting of query results by one or more columns. The sorting can be done either in ascending
order or descending order, the default order is ascending. The data in the table is not sorted ; only the
results that appear on the screen are sorted.

SYNTAX:

SELECT <column-name>…

FROM<table-name>

[WHERE<predicate>]

[ORDER BY <column-name>];

To display the grades of all the employees in descending order. If more than one employee has same
grade,display them in ascending order.

SELECT *

FROM emp

ORDER BY grade DESC, ename ASC;

ecode ename sex grade gross


1001 Priya F A1 8670
1002 Prateek M A2 7560
1003 Hardik M B1 6325
1004 Priya F B2 5120
1005 Sakshi F B2 5000
1006 Eti F C1 4450

GROUP BY CLAUSE: It is used in SELECT statements to divide the table into groups. Grouping can be
done by a column name , or with aggregate functions an which case the aggregate produces a value for
each group.

To calculate the no. of employees in each grade and average gross for each grade of employees.

SELECT grade, count(*),sum(gross)

FROM emp

GROUP BY grade;
grade Count(*) Sum(gross)
A1 1 8670
A2 1 7560
B1 1 6325
B2 2 10120
C1 1 4450

Placing conditions on groups- HAVING clause: It places conditions on groups in contrast to WHERE
clause that places conditions on individual rows. While where conditions cannot include aggregate
functions, HAVING conditions can do so.

To calculate the average gross and total gross for employees belonging to ‘B2’ grade.

SELECT avg(gross), sum(gross)

FROM emp

GROUP BY grade

HAVING grade=’B2’;

Avg(gross) Sum(gross)
560 10120
3.To implement different inbuilt functions on table emp
i) Aggregate Functions: The summary values are calculated from data in a particular column using
aggregate functions. The result of aggregate functions is a single value.

avg- to compute average value stddev-to find the standard deviation

min-to find minimum value count- to count non null values in a column

max- to find maximum value count(*)-to count total no of roes in a table

sum- to find total value variance-to compute the variance of values in a coloumn

To calculate maximum gross of employees.

SELECT max (gross)

FROM emp;

max (gross)
8670

To count the no. of rows in emp table.

SELECT count(*)

FROM emp;

count(*)
6

ii). Case Manipulation Functions:

1. lower ( column/expression)- converts alpha character values to lower case.

2. upper (column/expression)- converts alpha character values to upper case.

3.INITCAP(col/exp)- converts alpha character values to upper case for first letter of each word.
iii).Character Manipulation Function:

1.CONCAT(col1/exp1, col2/exp2)- Concatenates the first character value to the second character value.

2. SUBSTR(col/exp, m,[n])- returns specified character value starting at character position m, n


characters long.( if m is –ve, then count starts from the end of the character value). If n is omitted, all
characters to the end of the string are returned.

3.LENGTH(col/exp)- Returns the no. of characters in the expression.

4. INSTR(col/exp, ‘string’,[m],[n])- returns the numeric position of a named string (optionally we can
provide a position m to start searching an occurrence n of the string). By default m and n are equal to 1.

5.LPAD(col/exp, n, ‘character’)- pads the character value right justified to a total of n character postion.

6.RPAD(col/exp,n,’character’)- pads the character value left justified to a total of n character position.

7. TRM( heading/trailing/both, trim char from trim source)- enables us to heading or trailing or both
from a character string (if trim char and trim source is a characterthen we must enclose it in single
quotes).This is a feature available from oracle 8i and its successors.

8.Replace(text, searchstring, replacementstring)-It searches a text expression for a character string and
if found replaces it with a specified replacement string.

iv). Numeric value functions:

1.ROUND(col/exp,n)- rounds off the numeric expression on least significant n positions.

ex. ROUND(193.329)=193.33

2.TRUNC(col/exp,n)-truncates the numerical expression by n least significant digits.

ex-TRUNC(193.329,1)=193.32

3.MOD(m,n)-finds the modulus of m and n.

ex. MOD(400,70)=50
v) Date conversion functions:

1. months_between(‘date1’, ‘date2’)- here date1 is greater than date2. it return the no. of months
between these two dates.

2.Add_months(date, n)- adds n months to the no of month specified in date and returns the modified
date.

3.Next_day(date, ‘day’)- returns the next date on which specified day comes i.e. if day is specified as
Monday then it would return the date of next Monday from the specified date.

4. Last_day(date)

5.Round(date, int)

6.TRUNC( date, int)

7. date-number: subtracts the number from no of days in the date.

8.date+number: adds the number to no of days in date.

9.date+date: adds the no of days of second date to no of days of first date.

Now consider the following table “emprecord” for the queries to implement all the above inbuilt
functions.

emprecord

fname lname DOH salary


priya kapoor 02-Sep-08 45000
prateek saxena 16-Jan-08 50000
sakshi malhotra 03-Dec-08 47000
hardik dsouza 18-Sep-08 43000

1.Create a query to display first name of all employee with first letter as capital, last name with all the
letters capital and concatenate first name and lastname as ename, length of first name as len. format
the salary to be10 characters long left padded with dollar sign.

SELECT CONCAT(INITCAP(fname),’ ‘,upper(lname)) as ename, LENGTH(ename)as len, LPAD(sal,10,$)

FROM emprecord;
ename len salary
Priya KAPOOR 11 $$$$$45000
Prateek SAXENA 13 $$$$$50000
Sakshi MALHOTRA 14 $$$$$47000
Hardik DSOUZA 12 $$$$$43000

2. For each employee display the employees’ last name and calculate the no of months between
today(15-Sep-09) and the date on which emp was hired. Order your result by no. of months and round
the no. of months upto the closest whole no.

SELECT lname, ROUND(Months_Between(’15-sep-09’,DOH)) as emonths

FROM emprecord

ORDER BY emonths;

lname emonths
malhotra 9
dsouza 12
kapoor 12
saxena 20

3. Display each employees’ first name, hire date and salary review date( which is the first MONDAY
after six months of service). label the column as review.

SELECT fname, DOH,Next_day((Add_months(DOH,6), ‘MONDAY’) as review

FROM emprecord;

fname DOH review


priya 02-Sep-08 02-Mar-09
prateek 16-Jan-08 21-Jul-08
sakshi 03-Dec-08 08-Jun-09
hardik 18-Sep-08 23-Mar-09
4.To implement Nested Subqueries.
SQL provides a mechanism for nesting subqueries. A subquery is a select-from-where expression that is
nested within another query.

consider following relations:

account

account_no branch_name balance


A-101 downtown 500
A-102 perryridge 400
A-201 brighton 900
A-215 mianus 700
A-217 brighton 750
A-222 redwood 700
A-305 round hill 350

branch

branch_name branch_city assets


brighton Brooklyn 7100000
downtown Brooklyn 9000000
mianus horseneck 400000
north town rye 3700000
perryridge horseneck 1700000
pownal bennington 300000
redwood palo alto 2100000
round hill horse neck 8000000

customer

customer_name customer_stree customer_city


t
adams spring Pittsfield
brooks senator Brooklyn
curry north rye
glenn sand hill woodside
green walnut Stamford
hayes main Harrison
Johnson alma palo alto
jones main harrison
Lindsay park pittsfield
smith north rye
turner Putnam stamford
Williams Nassau princeton

depositor

customer_name account_no
hayes A-102
Johnson A-101
Johnson A-201
jones A-217
Lindsay A-222
smith A215
turner A-305

loan

loan_no branch_name amount


L-11 round hill 900
L-14 downtown 1500
L-15 perryridge 1500
L-16 perryridge 1300
L-17 downtown 1000
L-23 redwood 2000
L-93 mianus 500

borrower

customer_name loan_no
adams L-16
curry L-93
hayes L-15
Jackson L-14
jones L-17
smith L-11
smith L-23
Williams L-17
Test for set membership:

The in connective tests for set membership, where the set is a collection of values produced by select
clause. The not in connective tests for the absence of set membership.

Find all the customers who have both a loan and an account at the bank.

select distinct customer_name

from borrower

where customer_name in (select customer_name

from depositor)

customer name
hayes
jones
smith

find all the customers who have both an account and a loan at the perryridge branch.

select distinct customer_name

from borrower, loan

where borrower.loan_no=loan.loan_no and

branch_name=”perryridge” and

(branch_name, customer_name) in

(select branch_name, customer_name

from depositor, account

where depositor.account_no=account.account_no)

customer name
hayes
find all the customers who do have a loan at the bank, but do not have an account at the bank.

select distinct customer_name

from borrower

where customer_name not in (select customer_name

from depositor)

customer name
adams
curry
Jackson
Williams

2. Set comparisons

find the names of all the branches that have assets greater than those of at least one branch located
in Brooklyn.

select distinct branch_name

from branch

where assets > some (select assets

from branch

where branch_city=”brooklyn”);

branch_name
mianus
north town
perryridge
pownal
redwood
roundhill
find the names of all the branches that have an asset value greater than that of each branch in
brooklyn.

select branch_name

from branch

where assets> all(select assets

from branch

where branch_city=”brooklyn”);

branch_name
roundhill
5.To implement various Join operations.
SQL provides not only the basic cartesian-product mechanism for joining tuples of relations, but also
provides various other mechanisms for joining relations including condition joins and natural joins, as
well as various forms of outer joins. These additional operations are typically used as subquery
expressions in the FROM clause.

consider the following relations

loan

loan_no branch_name amount


L-170 downtown 3000
L-230 redwood 4000
L-260 perryridge 1700

borrower

customer_name loan_no
jones L-170
smith L-230
hayes L-155

1.Inner join: The inner join is a binary operation that allows us to combine certain sections
and a Cartesian_product into one operation. It retains duplicate attributes.

SELECT* FROM loan inner join borrower on loan.loan_no=borrower.loan_no

loan_no branch_name amount customer_names loan_no


L-170 downtown 3000 jones L-170
L-230 redwood 4000 smith L-230

SELECT* FROM loan natural inner join borrower

loan_no branch_name amount customer_names


L-170 downtown 3000 jones
L-230 redwood 4000 smith
natural join removes duplicate attributes.
2.Outer Join: This operation is an extension of the inner join operation to deal with missing
information.There are actually three forms of outer join. They are:

i) left outer join: it takes all the tuples in the left relation that did not match with any tuple in the
right relation, pads the tuples with null values for all other attributes from right relation, and adds them
to the result of the inner join.

SELECT* FROM loan left outer join borrower on loan.loan-no=borrower.loan_no

loan_no branch_name amount customer_name loan_no


L-170 downtown 3000 jones L-170
L-230 redwood 4000 smith L-230
L-260 perryridge 1700 null null

ii) Right outer join: it is symmetric with outer join: It pads tuples from the right relation that did not
match any from the left relation with nulls and adds them to the result of the inner join.

SELECT * FROM loan natural right outer join borrower

loan_no branch_name amount customer_name


L-170 downtown 3000 jones
L-230 redwood 4000 smith
L-155 null null hayes

iii) Full outer join: It does both those operation, padding tuples with null from the left relation that did
not match any from the right relation, as well as tuples from the right relation that did not match any
from the left relation, and adding them to the result of inner join.

SELECT * FROM loan full outer join borrower using (loan_no)

loan_no branch_name amount customer_name


L-170 downtown 3000 jones
L-230 redwood 4000 smith
L-260 perryridge 1700 null
L-155 null null hayes

You might also like