0% found this document useful (0 votes)
11 views15 pages

sql

The document provides a comprehensive overview of SQL, detailing its four main components: DDL, DML, DCL, and DQL, along with their respective commands for database management. It covers various SQL operations such as creating, altering, and deleting databases and tables, as well as inserting, updating, and deleting records. Additionally, it explains SQL constraints, data types, aggregate functions, and query syntax for data retrieval and manipulation.

Uploaded by

Hyder Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views15 pages

sql

The document provides a comprehensive overview of SQL, detailing its four main components: DDL, DML, DCL, and DQL, along with their respective commands for database management. It covers various SQL operations such as creating, altering, and deleting databases and tables, as well as inserting, updating, and deleting records. Additionally, it explains SQL constraints, data types, aggregate functions, and query syntax for data retrieval and manipulation.

Uploaded by

Hyder Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

Database: Basics (SQL)

Structure query language


-> DDL (Data definition language)
-> DML (data manipulation language)
-> DCL (data control language)
-> DQL (data query language)

1. DDL: (works on structure)


create
drop
alter
2. DML: (works on data)
insert
update
delete
3. DCL
grant (giving permission)
revoke (removing the permission)
4. DQL
SQL

to craete database:
craete database database_name;
create database sample;

to drop database:
drop database database_name;
drop database sample;

to backup database:
backup database database_name to disk ='file path';
BACKUP DATABASE sample TO DISK = 'D:\backups\sample;.bak';

to create table:
create table table_name(column1 datatype,column2 datatype,column3 datatype,....);
create table sample(id int,name varchar(10),salaray number,....);

to insert data into table:


insert into table_name(col1,col2,...)values(1,'aaa',200);
insert into sample(id,name,salary)values(1,'hyder',20000);

to drop table:
drop table table_name; //The DROP TABLE statement is used to drop an existing
table in a database.
drop table sample;
or
TRUNCATE TABLE table_name; //The TRUNCATE TABLE statement is used to delete the
data inside a table, but not the table itself.
TRUNCATE TABLE sample;

to alter table: //The ALTER TABLE statement is used to add, delete, or modify
columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
ALTER TABLE table_name ADD column_name datatype;
alter table sample add state varchar(10);

ALTER TABLE table_name DROP COLUMN column_name;


alter table sample drop state;

ALTER TABLE table_name MODIFY column_name datatype;


alter table sample modify name varchar(10);

4.renaming a column:
alter table testing rename column sno to snumber;

-->SQL constraints are used to specify rules for the data in a table.
The following constraints are commonly used in SQL:

NOT NULL - Ensures that a column cannot have a NULL value


UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
FOREIGN KEY - Prevents actions that would destroy links between tables
CHECK - Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
CREATE INDEX - Used to create and retrieve data from the database very quickly

CREATE TABLE Persons ( ID int NOT NULL,LastName varchar(255) NOT NULL,Age int);

By default, a column can hold NULL values.

*The NOT NULL constraint enforces a column to NOT accept NULL values.

*The UNIQUE constraint ensures that all values in a column are different.
ex:CREATE TABLE Persons ( ID int NOT NULL UNIQUE,LastName varchar(255) NOT NULL,Age
int);

*The PRIMARY KEY constraint uniquely identifies each record in a table.


Primary keys must contain UNIQUE values, and cannot contain NULL values.
ex:CREATE TABLE Persons ( ID int PRIMARY KEY,LastName varchar(255) NOT NULL,Age
int);

*The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the
PRIMARY KEY in another table.
CREATE TABLE Orders (OrderID int NOT NULL,PersonID int,PRIMARY KEY
(OrderID),FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));

*The CHECK constraint is used to limit the value range that can be placed in a
column.
If you define a CHECK constraint on a column it will allow only certain values for
this column
CREATE TABLE Persons (ID int NOT NULL, Age int,CHECK (Age>=18));

*The DEFAULT constraint is used to set a default value for a column.


The default value will be added to all new records, if no other value is specified.
CREATE TABLE Persons (ID int NOT NULL, city varchar(10) defualt 'mangalore');

*The CREATE INDEX statement is used to create indexes in tables.


Indexes are used to retrieve data from the database more quickly than otherwise.
*AUTO INCREMENT Field
Auto-increment allows a unique number to be generated automatically when a new
record is inserted into a table.
CREATE TABLE Persons (Personid int NOT NULL AUTO_INCREMENT,LastName varchar(255)
NOT NULL,PRIMARY KEY (Personid));

*SQL Date Data Types


MySQL comes with the following data types for storing a date or a date/time value
in the database:

DATE - format YYYY-MM-DD


DATETIME - format: YYYY-MM-DD HH:MI:SS
TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
YEAR - format YYYY or YY

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

*SQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.

CREATE VIEW Syntax


CREATE VIEW view_name AS SELECT column1, column2, ...FROM table_name WHERE
condition;

CREATE VIEW [Brazil Customers] AS SELECT CustomerName, ContactName FROM Customers


WHERE Country = 'Brazil';

*SQL Data Types


Each column in a database table is required to have a name and a data type.

In MySQL there are three main data types: string, numeric, and date and time.

->CHAR(size)
A FIXED length string (can contain letters, numbers, and special characters). The
size parameter specifies the column length in characters - can be from 0 to 255.
Default is 1
->VARCHAR(size)
A VARIABLE length string (can contain letters, numbers, and special characters).
The size parameter specifies the maximum column length in characters - can be from
0 to 65535
->BINARY(size)
->TEXT(size)
->BLOB(size)

->int
->float
->tinyint
->bool
->double
->bit

->date
->datetime

***********************************************************************
--->The SQL SELECT Statement
The SELECT statement is used to select data from a database.
SELECT Syntax:
SELECT column1, column2, ...FROM table_name;
SELECT CustomerName, City FROM Customers;

SELECT * FROM table_name; //to select all data from table


SELECT * FROM Customers;

--->The SQL SELECT DISTINCT Statement


The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you
only want to list the different (distinct) values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...FROM table_name;
SELECT DISTINCT Country FROM Customers;
SELECT COUNT(DISTINCT Country) FROM Customers;

--->The SQL WHERE Clause


The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.

WHERE Syntax
SELECT column1, column2, ...FROM table_name WHERE condition;
SELECT * FROM Customers WHERE Country='Mexico';
SELECT * FROM Customers WHERE CustomerID=1;

--->The SQL AND, OR and NOT Operators


The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one
condition:

The AND operator displays a record if all the conditions separated by AND are TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax
SELECT column1, column2, ...FROM table_name WHERE condition1 AND condition2 AND
condition3 ...;
SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin';

SELECT column1, column2, ...FROM table_name WHERE condition1 OR condition2 OR


condition3 ...;
SELECT * FROM Customers WHERE City='Berlin' OR City='München';

SELECT column1, column2, ..FROM table_name WHERE NOT condition;


SELECT * FROM Customers WHERE NOT Country='Germany'; //it displays other than the
country germany

SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR


City='München');
SELECT * FROM Customers WHERE NOT Country='Germany' AND NOT Country='USA';

The SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set in ascending or descending
order.

SELECT column1, column2, ... FROM table_name ORDER BY column1, column2, ... ASC|
DESC;
SELECT * FROM Customers ORDER BY Country;
SELECT * FROM Customers ORDER BY Country DESC;

The SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.
INSERT INTO table_name (column1, column2, column3, ...)VALUES (value1, value2,
value3, ...);
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

What is a NULL Value?


A field with a NULL value is a field with no value.
IS NULL:
to check the particular column contains null value.
select name from emp1 where salary is null;

IS NOT NULL:
to check the particular column contains not null value.
select name from emp1 where salary is not null;

The SQL UPDATE Statement


The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;

UPDATE Customers SET ContactName = 'Alfred Schmidt', City= 'Frankfurt' WHERE


CustomerID = 1;

The SQL DELETE Statement


The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;
it delete the row from table
delete from emp1 where name='aaa'

Delete All Records


It is possible to delete all rows in a table without deleting the table. This means
that the table structure, attributes, and indexes will be intact:
DELETE FROM table_name;

The SQL MIN() and MAX() Functions


The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

The COUNT() function returns the number of rows that matches a specified criterion.

COUNT() Syntax
SELECT COUNT(column_name) FROM table_name WHERE condition;

The AVG() function returns the average value of a numeric column.


AVG() Syntax
SELECT AVG(column_name) FROM table_name WHERE condition;

The SUM() function returns the total sum of a numeric column.

SUM() Syntax
SELECT SUM(column_name) FROM table_name WHERE condition;

Table is a collection of row and collums.


table=tuples
data=attributes

create table emp1(id int not null , name varchar(20), age int,primary key(id));
insert into emp1(id,name,age)values(101,'hyder',25);
insert into emp1(id,name,age,salary)values(105,'aaa',28,20000);
alter table emp1 add salary number;
select name from emp1 where id=101;
select count(age) from emp1
select * from emp1
desc emp1
select max(salary) from emp1
select min(salary) from emp1

aggregate functions:
count
sum
avg
min
max

select count(id) from emp1


select avg(salary) from emp1
select sum(salary) from emp1
select max(salary) from emp1
select min(salary)from emp1

group by:
arrange the identical data into group
arrange similar type of data into group
select count(salary), age from emp1 group by age

having:
it is using in group by for the condition.
select count(salary), age from emp1 group by age having sum(salary)>1000

order by:
it will sort the result in ascending or decending order

IS NULL:
to check the particular column contains null value.
select name from emp1 where salary is null;

IS NOT NULL:
to check the particular column contains not null value.
select name from emp1 where salary is not null;

UPDATE:
it is used to modify the content of table
update emp1 set name='shabeer' where id=104

DELETE:
it delete the row from table
delete from emp1 where name='aaa'

IN OPERATOR:
it is used to specify multiple values in where cluase
select id,name,age from emp1 where city IN('Mangalore','Bangalore','Mysoor')

BITWEEN:
it is used to select particular vale within the specified range.
select name,age from emp1 where age between 25 and 26;

ALLIASES :
giving a temporary or another name to table and column.

select name as a from emp1 //alias to column name


select e.name,e.city,e.salary from emp1 as e //alias for table

table : employee
Query 1:
get all the records from employee table
select * from employee;

in the above query * means all the columns

DDL:
create
alter
drop
DML:
insert
update
delete
DQL: SQL
DCL:
grant
revoke
SQL (Structure query language)
trying to retrieve information from database

Database:
collection of:
tables
triggers
indexes
views
Stored procedures
functions
packages
types
sequences
========================
select
count
where
or
in
not in
is not null
max
min
avg
as

table : employee (is having 100 columns)


Query 1:
get all the records from employee table
select * from employee;

in the above query * means all the columns

2. get only 4 columns


select empno,empname,sal,desg from employee;
3. count the number of records in emp table
select count(*) from emp;
4.perticular records
select * from emp where empno=7902;
5. retrieve 2 records
select * from emp where empno=7902 or empno=7499;
6.Retrieve multiple records
select * from emp where empno in (7566,7499,7521,7876,7934);
7. retrieve records using other than the condition
select * from emp where empno not in (7566,7499,7521,7876,7934);
8.comparing strings (need to use '')
select * from emp where ename='KING';
9. combining integers and strings
select * from emp where ename='ALLEN' and sal=1600;
relational operators:
10.
select * from emp where sal < 1000;
11.
select * from emp where sal >= 3000;
12. not equal (<>)
select * from emp where sal<>1100;
13.
select * from emp where job='MANAGER';
14.
select * from emp where job not in ('SALESMAN','CLERK');
15. Query to find maximum salary
select max(sal) from emp;
16. Minimum sal
select min(sal) from emp;
17.average sal
select avg(sal) from emp;
18.
select * from emp where comm is not null;
19. change the column name
select deptno as DDD from emp;
20. print all the records from emp table after sorting based on sal column
(ascending)
select * from emp order by sal;
select * from emp order by sal asc;
21. decending order
select * from emp order by sal desc;
22. sort based on 2 columns:
select * from emp order by empno,ename;
23. nesting of query : finding second highest salary
select max(sal) from emp where sal < (select max(sal) from emp);

select * from emp e1 where


&n-1 = (select count(distinct sal) from emp e2 where e1.sal <e2.sal);

nth higest sal:

select min(sal) from (select distinct sal from emp order by sal desc)
where rownum<&n;

25. count number of record for each job title


select job,count(*) from emp group by job;

key words:
select
count
where
or
in
not in
is not null
max
min
avg
as
distinct
asc
desc
order by
rownum
group by

update:
this will use to update the existing data
update single column value:
update emp set sal=10000 where empno=7902;
update multiple column values:
update emp set sal=20000,ename='FORDD' where empno=7902;

desc table;
this command will give you the details of the table
Control + left mouse button: this will also give all the details

insert:
insert into emp values (8000,'Shahbaz','MANAGER',7839,sysdate,45000,6000,30);
commit;
select * from employee;

delete: deletes the data from a table:


ex:
delete from employee where eno=8000;
this command will delete records from employee table matcing eno 8000
2. delete from employee;
this command will delete all the records

data types:
number
varchar2
varchar
date
integer

create:
create table employee (
eno number ,
ename varchar2(20),
esal number,
dept number,
ejobrole varchar2(20));

2. creating from another table:

create table student as select * from employee ;

3.creating from another table with condition:

create table student1 as select * from employee where eno=8000;

Constraints in database: conditions


1. unique
2. not null
3. primary key (unique + NOT NULL)
4. foreign key

create table student100 (


stuno number NOT NULL,
stuname varchar2(20) unique,
smarks number NOT NULL
primary key(stuno)
);

2.

create table student100 (


stuno number primary key,
stuname varchar2(20) unique,
smarks number NOT NULL
);

drop table student;

CREATE table student(id number, name varchar2(20),age number,marks number,place


varchar2(20), check(age>20), primary key(id));
insert into student values(101,'Hyder',22,'300','managlore');
insert into student values(102,'shabeer',28,'300','managlore')
insert into student values(103,'sabam',23,'300','managlore')
insert into student values(104,'Haris',25,'300','managlore')
insert into student values(105,'irshad',26,'300','managlore')
alter table student add (address varchar2(30))
alter table student modify (adress varchar(10) )
alter table student drop (address);
alter table student rename column adress to adr
select * from student;
update student set marks=350 where id=102
update student set marks=250, place='bangalore' where id=103
update student set marks=200,place='mysoor' where id=104

select distinct place from student

Create:
create table student(
sno number primary key,
sname varchar2(20) NOT NULL,
saddress varchar2(50));
alter table:
when we wanted to:
-> add a new column
-> modifying a existing column
-> delete a column
alter table student add(mobile number);
ex:
alter table testing add(smobile number unique

2. when you want to increase/decrease the size of a column


alter table testing modify(sname varchar2(40));

4.renaming a column:
alter table testing rename column sno to snumber;

1. Create table example


2. alter table with adding a column example
3. alter table with modifying a column example
4. alter table with delete a column example
5. alter table with renaming a column example

drop:
this command will drop the table (delte the table along with the data)

syntax:
drop table student;

truncate table testing;


drop table testing;
delte from table;

my table is having 100000;

delete : delete will delte the rows one by one (will take lot of time)
truncate: (actual purpose is to delete data)
-> delete the table (data and table will be deleted)
-> recreate a fresh table

6. drop table example


7. trauncate example
8. example for exaplining the differences between
-> delte
-> drop
-> truncate

DCL:
grant and revoke

grant is for giving permissions


grant insert,update,delete,alter on testing to user1,user2,

ex:
grant insert,update on testing to training;
revoke insert,update on testing from training;
grant insert,update on employee to testing
revoke insert,update on employee from testing

Grant and revoke will make sure the data security in database,
generally this task belongs to DBA.

database side important questions:


1. synatax for creating table
2. DML commands at least one example each
3. DDL commands at least one example each
4. Normalization,types,example
5. Joins, types, example

View:
is nothing but a virtual table
snapshot of a table
part of a table

syntax:
1. create view stu_view as
select * from student;
2. create view stu_view as
select sno,sname from student;
3. create view stu_view as
select sno,sname from student where sno <5;

Dropping a view:
drop view stu_view;

Triggers:
A trigger is a stored procedure which automatically
invokes/runs whenever a special event happens in
the database.
special event:
before insert/update/delete
after insert/update/delete

create trigger stutrigger


before insert
of sname
on student
for each row
set student.total=student.m1+student.m2+student.m3;
10. Creata view (for entire table)
11. create view (with some condition)
12. crate trigger example

normalization:
-> restructuring the relational database.
-> to reduce the duplicate entries (redundency)
-> improve the data integrity
-> we can maintain data hiding,security

normalization is nothing but database design


streamlining the data by reducing the redundant data.
Types of normalization:
1. 1NF
2. 2NF
3. 3NF
4. BCNF/4NF
5. 5NF
6. 6NF
What will happen if data is repeated:
1.data maintenence becomes difficult
2. data inconsistencies
3. will increase database size
4. insert/update/delete will become frequent,

Joins:
joining/combining the data from 2 or more tables

-> inner join


-> right join
-> left join
->full outer join

2 tables: table1,table2

select columns from table1


innser join table2
on table1.column = table2.column
ex:
Convert the below query to user joins:

select e.empno,e.ename,e.mob,e.age,d.deptname
from emp e,dept d
where e.deptcode=d.deptcode;

Query with joins:


select e.empno,e.ename,e.mob,e.age,d.deptname
from emp e
inner join deptname d on
e.deptcode=d.deptcode

create or replace trigger stutrigger


after update on student
for each row
begin
dbms_output.put_line('sudhakar');
end;
set serverout on;
update student set esal=60000 where eno=8000;

It is similar to index in the text books.

Syntax:

create index stu_ind


on student(ename);

2.
create index stu_ind
on student(eno,ename)

create or replace procedure myproc


as
begin
dbms_output.put_line('This is my Stored procedure');
end;

exec myproc;

Indexes:

Using indexes retrieving the data will be quickly. We can't see


indexes, but we cab observe that our retrieving is very fast.

It is similar to index in the text books.

12. crate trigger example


13. create index
14. create stored procedure

Topics covered in database:


1. DML command
2. DDL commands
3. DCL commands
4. DQL (SQL)
select
where
count
second highest sal
nested queries
5. indexes
6. table
7. Stored procedure with output statement (dbms_output.put_line('sudhakar'))
8. view
9. joins
10. Triggers
11. Normalization
12. Constraints (primary key,unique,not null
15. What is plumbing/piping in Linux or Unix?
Plumbing/ Piping refers to the technique of using one program's output as an input
to another. For instance,
Instead of delivering a folder or drive listing to the main screen, it can be
piped and delivered to a file, or sent to the printer to print a hard copy.

A pipe is a type of redirection (the transfer of standard output to another


location) used in Linux and other Unix-like operating systems to transport
the output of one command/program/process to another for additional processing.
The Unix/Linux systems allow a command's stdout to be connected to another
command's stdin.
The pipe character ‘|' can be used to do this.

SELECT now(); -- date and time


SELECT curdate(); --date
SELECT curtime(); --time in 24-hour format

select count(order_total),order_id from demo_orders where order_timestamp >


date_sub(now(), interval 8 week)group by order_id

To delete duplicate records in SQL, you can use the DELETE statement with a
subquery that identifies the duplicates. Here's an example:

Suppose you have a table named mytable with columns id, name, and email, and you
want to delete duplicate records based on the email column. You can use the
following SQL statement:

sql
Copy
DELETE FROM mytable
WHERE id NOT IN (
SELECT MIN(id)
FROM mytable
GROUP BY email
);

You might also like