You are on page 1of 41

Using TOP and PERCENT

The TOP option is used for limiting the output of a query result set. TOP can
either specify the number of rows to return, or the percentage of rows to return.
The ORDER BY clause can be used successfully with the TOP option.

SELECT TOP 10 *
FROM employees

SELECT TOP 20 PERCENT *


FROM employees

SELECT TOP 10 *
FROM employees
ORDER BY Salary DESC

SELECT TOP 1 WITH TIES * FROM EMP


ORDER BY SAL
1
INTO CLAUSE

INTO clause creates a new table and inserts rows and columns listed in the
SELECT statement into it. INTO clause also inserts existing rows into a new
table.

SELECT EMPNO,ENAME,JOB INTO


EMP20 FROM EMP
WHERE DEPTNO =10;

2
[ ] (Wildcard - Character(s) to Match)

Matches any single character within the specified range or set


that is specified between the brackets.

SELECT * FROM EMP


WHERE SAL LIKE '[0-9][0-9][0-9]'

3
[^] (Wildcard - Character(s) Not to Match)

Matches any single character that is not within the range or set
specified between the square brackets.

SELECT * FROM EMP


WHERE ENAME LIKE 'A[^L]%'

4
GROUP BY ALL

If you use ALL, the query results include all groups produced by the
GROUP BY clause, even if some of the groups have no rows that meet
the search conditions. Without ALL, a SELECT statement that includes
GROUP BY does not show groups for which no rows qualify.

SELECT AVG(SAL),DEPTNO
FROM EMP
WHERE DEPTNO IN(10,20)
GROUP BY ALL DEPTNO

5
GROUP BY CUBE

CUBE is an aggregate operator that produces a super aggregate row.


In addition to the usual rows provided by the GROUP BY, it also
provides the summary of the rows that the GROUP BY clause
generates.

The Summary row is displayed for every possible combination of


groups in the result set.

The Summary row displays NULL in the result set

SELECT AVG(SAL),DEPTNO,JOB
FROM EMP
GROUP BY DEPTNO ,JOB WITH CUBE

6
GROUP BY ROLLUP

ROLLUP:- In addition to the rows generated by the group by clause , it


also introduces summary rows into the result set.

It arranges the groups from the lowest to the highest.

SELECT AVG(SAL),DEPTNO,JOB
FROM EMP
GROUP BY DEPTNO,JOB WITH ROLLUP

7
SQL Insert

The SQL INSERT command allows you to insert a


record into a table in your database.

INSERT INTO Student (Rollno, name, age)


VALUES ( 1, 'Benny', 12)

8
SQL Update

The SQL UPDATE statement allows you to update an existing


record in the database.

The UPDATE command uses a WHERE clause. If you don't use a


WHERE clause, all rows will be updated.

UPDATE student
SET age = 12
WHERE rollno = 1

9
SQL Delete
The SQL DELETE statement allows you to delete a record from the database.

The DELETE command uses a WHERE clause. If you don't use a WHERE
clause, all rows in the table will be deleted.

DELETE FROM Individual


WHERE Rollno = 1

10
Data type Range Storage

-2^63 (-9,223,372,036,854,775,808) to
bigint 8 Bytes
2^63-1 (9,223,372,036,854,775,807)

int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes

smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes

tinyint 0 to 255 1 Byte

11
Fixed-precision and scale-numeric data from –10^38+1 through 10^38–1.
numeric (p, s)
Storage size is 19 bytes.

Monetary data values from (–2^63/10000) (–922,337,203,685,477.5808)


money through 2^63–1 (922,337,203,685,477.5807)

Storage size is 8 bytes.

12
datetime Date and time data from January 1, 1753, to December 31, 9999,

smalldatetime January 1, 1900, through June 6, 2079

13
Fixed-length, non-Unicode character data with a length of n bytes. n
char [ ( n ) ]
must be a value from 1 through 8,000.

Variable-length, non-Unicode character data. n can be a value from 1


varchar [ ( n | max ) ]
through 8,000.

Variable-length with a maximum length of 2^31-1 (2,147,483,647)


text
characters.

14
national character(n)
Fixed-length Unicode data with a maximum length of 4000 characters.
Synonym: nchar(n)

national character
varying(n) Variable-length Unicode data with a length of 1 to 4000 characters.
Synonym: nvarchar(n)

15
Variable-length Unicode data with a maximum length of (2^30–2)/2
ntext
(536,870,911) characters.

binary(n) Fixed-length binary data with a maximum length of 8000 bytes.

varbinary(n) Variable-length binary data with a maximum length of 8000 bytes.

Variable-length binary data with a maximum length of 2^30–1


image (1,073,741,823) bytes.

Storage is the length of the value in bytes.

uniqueidentifier A globally unique identifier (GUID). Storage size is 16 bytes.

16
Only data columns of the integer data types can be used for identity columns. A table can
have only one identity column. A seed and increment can be specified and the column
IDENTITY [(s, i)] cannot be updated.
s (seed) = starting value
i (increment) = increment value

This is a property of a data column, not a distinct data type. It is a column in a table that is
ROWGUIDCOL defined by using the uniqueidentifier data type. A table can have only one ROWGUIDCOL
column.

17
Using the IDENTITY property with CREATE TABLE

IDENTITY property for an automatically incrementing identification number.

CREATE TABLE employees ( id_num int IDENTITY(1,1),


fname varchar (20), lname varchar(30) )

INSERT employees (fname, lname) VALUES ('Karin„, 'Josephs')

18
Naming Conventions

– Must begin with a letter


– Can be 1–30 characters long
– Must contain only A–Z, a–z, 0–9 , _
– Must not duplicate the name of another
object owned by the same user
– Must not be an reserved word
The CREATE TABLE Statement
– You specify:
• Table name
• Column name, column datatype, and column
size
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr];
The DEFAULT Option
– Specify a default value for a column during
an insert.
… job varchar(15) DEFAULT ‘clerk’, …
Creating Tables
– Create the table.
SQL> CREATE TABLE dept
2 (deptno NUMBER(2),
3 dname VARCHAR(14),
4 loc VARCHAR(13));
Table created.
The ALTER TABLE Statement

Use the ALTER TABLE statement to:


– Add a new column
– Modify an existing column
– Define a default value for the new column
ALTER TABLE table
ADD (column datatype [DEFAULT expr];

ALTER TABLE table


ALTER COLUMN(column_name datatype [DEFAULT expr]);
Adding a Column
“…add a
DEPT30 New column
new
EMPNO ENAME ANNSAL HIREDATE JOB
------ ---------- --------
column
7698 BLAKE 34200 01-MAY-81 into
7654 MARTIN 15000 28-SEP-81 DEPT30
7499 ALLEN 19200 20-FEB-81 table…”
7844 TURNER 18000 08-SEP-81
...

DEPT30
EMPNO ENAME ANNSAL HIREDATE JOB
------ ---------- --------
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
Adding a Column

– You use the ADD clause to add columns.


SQL> ALTER TABLE dept30
2 ADD (job VARCHAR(9));
Table altered.

• The new column becomes the last column.

EMPNO ENAME ANNSAL HIREDATE JOB


--------- ---------- --------- --------- ----
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
6 rows selected.
Modifying a Column

– You can change a column's datatype,


size, and default value.
ALTER TABLE dept30
ALTER COLUMN (ename VARCHAR(15));
Table altered.

– A change to the default value affects


only subsequent insertions to the table.
Dropping a Table

– All data and structure in the table is


deleted.
– Any pending transactions are committed.
– All indexes are dropped.
– You cannot roll back this statement.

SQL> DROP TABLE dept30;


Table dropped.
Truncating a Table
– The TRUNCATE TABLE statement:
• Removes all rows from a table
• Releases the storage space used by that
table

SQL> TRUNCATE TABLE department;


Table truncated.

– Cannot roll back row removal when


using TRUNCATE
– Alternatively, remove rows by using the
DELETE statement
What Are Constraints?
– Constraints enforce rules at the table level.
– Constraints prevent the deletion of a table if
there are dependencies.
– The following constraint types are :-
• NOT NULL
• UNIQUE Key
• PRIMARY KEY
• FOREIGN KEY
• CHECK
Constraint Guidelines
– Create a constraint:
• At the same time as the table is created
• After the table has been created
– Define a constraint at the column or table
level.
Defining Constraints
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],

[table_constraint]);

CREATE TABLE emp(


empno NUMBER(4),
ename VARCHAR(10),

deptno NUMBER(7,2) NOT NULL,
CONSTRAINT emp_empno_pk
PRIMARY KEY (EMPNO));
The NOT NULL Constraint
Ensures that null values are not
permitted for the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO

7839 KING PRESIDENT 10


7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...

NOT NULL constraint Absence of NOT NULL NOT NULL constraint


(no row may contain constraint
a null value for (any row can contain
this column) null for this column)
The NOT NULL Constraint

Defined at the column level


SQL> CREATE TABLE emp(
2 empno NUMBER(4),
3 ename VARCHAR(10) NOT NULL,
4 job VARCHAR(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL);
The UNIQUE Key Constraint
UNIQUE key constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into Not allowed


50 SALES DETROIT (DNAME SALES
already exists)
60 BOSTON Allowed
The UNIQUE Key Constraint

Defined at either the table level or the


column level

SQL> CREATE TABLE dept(


2 deptno NUMBER(2),
3 dname VARCHAR(14),
4 loc VARCHAR(13),
5 CONSTRAINT dept_dname_uk UNIQUE(dname));
The PRIMARY KEY Constraint

PRIMARY KEY
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into Not allowed


20 MARKETING DALLAS (DEPTNO 20 already
exists)
FINANCE NEW YORK Not allowed
(DEPTNO is null)
The PRIMARY KEY Constraint

Defined at either the table level or the


column level
SQL> CREATE TABLE dept(
2 deptno NUMBER(2),
3 dname VARCHAR(14),
4 loc VARCHAR(13),
5 CONSTRAINT dept_dname_uk UNIQUE (dname),
6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));
The FOREIGN KEY Constraint

DEPT
PRIMARY DEPTNO DNAME LOC
KEY ------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
...
EMP
EMPNO ENAME JOB ... COMM DEPTNO FOREIGN
KEY
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
...
Not allowed
(DEPTNO 9
Insert into does not exist in
the DEPT table
7571 FORD MANAGER ... 200 9
7571 FORD MANAGER ... 200 Allowed
The FOREIGN KEY Constraint

Defined at either the table level or the


column level
SQL> CREATE TABLE emp(
2 empno NUMBER(4),
3 ename VARCHAR(10) NOT NULL,
4 job VARCHAR(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL,
10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)
11 REFERENCES dept (deptno));
Adding a Constraint

Add a FOREIGN KEY constraint to the


EMP table indicating that a manager
must already exist as a valid employee
in the EMP table.
SQL> ALTER TABLE emp
2 ADD CONSTRAINT emp_mgr_fk
3 FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.
Dropping a Constraint

– Remove the manager constraint from


the EMP table.
SQL> ALTER TABLE emp
2 DROP CONSTRAINT emp_mgr_fk;
Table altered.

You might also like