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

SQL-DDL and DML

hey ho

Uploaded by

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

SQL-DDL and DML

hey ho

Uploaded by

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

SQL (Structure Query

Language)
What is SQL?

 SQL stands for Structured Query Language


 SQL lets you access and manipulate databases
Why SQL?

SQL is widely popular because it offers the following


advantages:
 SQL allows you to access a database
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert new records in a database
 SQL can delete records from a database
 SQL can update records in a database
 SQL is easy to learn
.
SQL Language

 There are four categories of Sql. Query


Language, namely

1. Data Definition Language (DDL)


2. Data Manipulation Language (DML)
3. Data Control Language (DCL)
4. Transaction Control Language (TCL)
SQL commands…..

 SQL Data Definition Language (DDL)


A part of SQL permits database tables to be created ,
Modified or deleted.
No. Command & Description

CREATE
1 Creates a new Database , table, a view of a table, or other object in the
database.
ALTER
2 Modifies an existing database object, such as a table.
DROP
3 Deletes an entire database or table, a view of a table or other objects in the
database.
Truncate
4 the purpose of deleting all records, but not the table structure
SQL commands…..

 SQL Data Manipulation Language (DML)

Is the statements that are used to manage data within the


schema objects.

 SELECT - extracts data from a database table


 UPDATE - updates data in a database table
 DELETE - deletes data from a database table
 INSERT INTO - inserts new data into a database table
BASIC DATA TYPES

Numeric data types


 •Integer numbers: INT, INTEGER, SMALLINT, BIGINT
 •Floating-point (real) numbers: REAL, DOUBLE , FLOAT

Character-string data types


Fixed length: CHAR(n)
Varying length: VARCHAR(n)
 Boolean data type

Values of TRUE or FALSE or NULL


DATE data type
•Components are YEAR, MONTH, and DAY in the form YYYY-MM-DD
CREATE DATABASE

SQL CREATE DATABASE Statement


 Syntax

Create database database_name;


E.g. create database ABC ;

To select a specific database


 Syntax

Use database_name ; (for selecting the specific db.)


CREATE TABLE COMMAND

SQL CREATE TABLE Statement Example

CREATE TABLE table_name( create table person


(
column1 data_type constraint, id_no int primary key,
FirstName varchar(20),
column2 datatype,
column3 datatype, LastName varchar(20),
..... Address varchar(20),
columnN datatype, City varchar(20),
PRIMARY KEY( one or more
columns ) Year int
);
);
SQL INSERT INTO Statement

 The INSERT INTO statement is used to insert new rows into a table.
Syntax

INSERT INTO table_name VALUES (value1, value2,....)

INSERT INTO table_name (column1, column2,...) VALUES (value1,value2,....) ;


E.g.
insert into person values (' Ola',' Hansen', ' Timoteivn 10',' Sandnes' 1951 )
insert into person values ('Tove','Svendson' ,' Borgvn 23','Sandnes, 1978' ,
1980)
insert into person values ('Stale', 'Svendson',' Kaivn 18', 'Sandnes,1980 )
insert into person values ('Kari',' Pettersen',' Storgt 20', 'Stavanger', 1960 )
SQL INSERT INTO Statement…

 Insert Data in Specified Columns

INSERT INTO Persons (LastName, Address)VALUES


('Rasmussen', 'Storgt 67')
SQL SELECT Statement

 Syntax
SELECT * FROM table_name ;
e.g. select * from person;

SELECT column1, column2....columnN


FROM table_name
WHERE CONDITION;
e.g.
SELECT FirstName, LastName , Address from person
where Year=1980 ;
SQL WHERE Clause

 The WHERE clause is used to specify a selection


criterion.

The WHERE Clause


Syntax
SELECT column1, column2… FROM table_Name
WHERE column operator value
SQL WHERE Clause…

 With the WHERE clause, the following operators


can be used:

Operator Description
= Equal
<> Not equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
LIKE Search for a pattern
Example

Using the WHERE Clause


To select only the persons living in the city "Sandnes",
we add a WHERE clause to the SELECT statement:

SELECT * FROM Persons WHERE City='Sandnes'


SQL uses single quotes around text values (most database systems will also
accept double quotes). Numeric values should not be enclosed in quotes.
This is correct:

SELECT * FROM Persons WHERE FirstName='Tove‘


SELECT * FROM Persons WHERE Year>1965

This is wrong:

SELECT * FROM Persons WHERE FirstName=Tove


SELECT * FROM Persons WHERE Year>'1965‘
The LIKE Condition

 The LIKE condition is used to specify a search for a


pattern in a column.
Syntax
 SELECT column FROM table WHERE column LIKE
pattern
 A ‘%’ sign can be used to define wildcards (missing
letters in the pattern) both before and after the pattern.
Example
 The following SQL statement will return persons with first
names that start with an 'O':
SELECT * FROM Persons WHERE FirstName LIKE 'O%'
The LIKE Condition ….

 The following SQL statement will return persons with first


names that end with an 'a':

SELECT * FROM Persons WHERE FirstName LIKE '%a‘

 The following SQL statement will return persons with first


names that contain the pattern 'la':

SELECT * FROM Persons WHERE FirstName LIKE '%la%‘


select all Persons with a City NOT starting with "b", "s", or "p":
SELECT * FROM Persons
WHERE City NOT LIKE '[bsp]%';
Eliminating Duplicates

Category
SELECT
SELECT DISTINCT
DISTINCT category
category Gadgets
FROM
FROM Product
Product Photography
Household

Compare to:
Category
Gadgets
SELECT
SELECT Gadgets
category
category Photography
FROM
FROM Product
Product Household

PName Price Category Manufacturer


Dawit $19.99 Gadgets GizmoWorks
Tigist $29.99 Gadgets GizmoWorks
Mohamed $149.99 Photography Canon
19
Mulate $203.99 Household Hitachi
SQL UPDATE Statement

 The UPDATE statement is used to modify the data in a table.


Syntax
UPDATE table_name
SET column_name = new_value
WHERE column_name = some_value

We want to add a first name to the person with a last name of "Rasmussen":
UPDATE Person SET FirstName = 'Nina‘ WHERE LastName = 'Rasmussen'
SQL DELETE Statement

 The Delete Command helps to delete one, some


or all records of the table
 If a condition is specified, the records filtered by the
condition are deleted.
 Syntax
 DELETE FROM table_name WHERE column_name =
some_value
 DELETE FROM Person WHERE LastName =
'Rasmussen‘
SQL DELETE Statement…

 Delete All Rows


 If no condition is specified , then all records of the table are
completely deleted, leaving the table structure unaffected,
which can be repopulated.
DELETE FROM table_name
Or
DELETE * FROM table_name
Example:
Q28> Delete From Employee Where department = ‘History’;
Q29> Delete From Employee Where Emp_id = 103;
Q30> Delete From Employee;
SQL ORDER BY

SELECT <columns>
 The ORDER BY clause FROM <tables>
sorts the results of a
WHERE <condition>
query
 You can sort in ORDER BY <cols>
ascending (default) or [ASCENDING |
descending order
DESCENDING|
ASC | DESC ]
ORDER BY Example

SELECT * FROM Grade


ORDER BY Mark
Grade
Name Code Mark Name Code Mark
John DBS 56 Mark PR2 35
John IAI 72 Mark PR1 43
Mary DBS 60 Jane IAI 54
Mark PR1 43 John DBS 56
Mark PR2 35 Mary DBS 60
Jane IAI 54 John IAI 72
ORDER BY Example

SELECT * FROM Grade


ORDER BY Code ASC,
Mark DESC
Grade
Name Code Mark Name Code Mark
John DBS 56 Mary DBS 60
John IAI 72 John DBS 56
Mary DBS 60 John IAI 72
Mark PR1 43 Jane IAI 54
Mark PR2 35 Mark PR1 43
Jane IAI 54 Mark PR2 35
SQL Drop Table and Database

 Drop database
 You can delete an existing DB, Table with the
DROP Database statement.
 To delete a Database

Syntax
DROP DATABASE database_name ;
E.g. drop database Employee;
ALTER Command

 The Alter command is used to modify the structure of the table. The
command helps to

- To include new columns


- To modify column width
- To modify column data type
- To rename column names
- To drop columns
- To introduce constraints
 Syntax

ALTER TABLE < Table_Name > ADD


(Column1 datatype, ……, Column n datatype)
E.g.
 Alter table person add id_no int ;
ALTER Command….

 Syntax for Dropping:


ALTER TABLE < Table_Name > DROP COLUMN
<column names>
E.g.
Alter table employee drop column id_no;
ALTER TABLE Person DROP COLUMN Address;
ALTER TABLE Person alter column city varchar(50);
TRUNCATE Command

 For the purpose of deleting all records, but not the table
structure, we would prefer to use the TRUNCATE
Command.

Syntax:
TRUNCATE TABLE <table_name>

Example:
Q7> Truncate table Employee;
SQL AND & OR AND & OR

 The AND operator displays a row if ALL conditions listed


are true. The OR operator displays a row if ANY of the
conditions listed are true.
Original Table (used in the examples)
SQL AND & OR AND & OR…

Example
 Use AND to display each person with the first name
equal to "Tove", and the last name equal to "Svendson":

 SELECT * FROM Persons WHERE FirstName='Tove‘


AND LastName='Svendson‘
SQL AND & OR AND & OR…

 Example
 Use OR to display each person with the first name equal
to "Tove", or the last name equal to "Svendson":

SELECT * FROM Persons


WHERE firstname='Tove‘ OR lastname='Svendson'

Result:
SQL AND & OR AND & OR…

Example
 You can also combine AND and OR (use parentheses to form
complex expressions):

SELECT * FROM Persons


WHERE(FirstName='Tove' OR FirstName='Stephen')
AND
LastName='Svendson'
SQL Alias

With SQL, aliases can be used for column names and table
names.
Column Name Alias
The syntax is:
SELECT column AS column_alias FROM table

Table Name Alias


The syntax is:

SELECT column FROM table AS table_alias


Example: Using a Column Alias

SELECT LastName AS Family, FirstName AS Name FROM Persons


Example: Using a Table Alias

SELECT LastName, FirstName FROM Persons AS Employees


SQL JOIN ,Joins and Keys

 Sometimes we have to select data from two or more


tables to make our result complete.
 We have to perform a join.
 Tables in a database can be related to each other with
keys.
 A primary key is a column with a unique value for each
row. Each primary key value must be unique within the
table.
 The purpose is to bind data together, across tables,
without repeating all of the data in every table.
Referring to Two Tables

Example
Who has ordered a
product, and what did they
order?

Foreign key

SELECT Employees.Name, Orders.Product


FROM Employees, Orders WHERE
Employees.Employee_ID=Orders.Employee_ID
Exercise
 Who has ordered a product, and what did they
order?
Aggregate Functions
 Aggregate functions are statistical functions such as
count, min, max, sum and avg.
 They are used to compute a single value from a set of attribute
values of a column in a given SELECT statement.

Aggregate Function Description

Count Finds the number of records retrieved


Min Finds the minimum value of the column among all
records retrieved
Max Finds the maximum value of the column
among all records retrieved
Sum Finds the sum of the entire column of all
records retrieved, if it is numeric
Avg Finds the average of the column values of
all records retrieved, if it is numeric
Example

 Select count (*) from Employee where department = ‘CS’


 Select max (Salary) from Employee
 Select min (purchased_rate) from product_details
 Select sum (salary) from Employee
 Select avg (course1_mark) from marks_details
 Q21retrieves the number of staff members in the Computer
Science department
 Q2 retrieves the maximum salary amount from Employee table
Group By Clause

 Aggregate functions (like SUM) often need an added GROUP


BY functionality.

 GROUP BY... was added to SQL because aggregate functions (like


SUM) return the aggregate of all column values every time they are
called, and without the GROUP BY function it was impossible to find
the sum for each individual group of column values.

 The syntax for the GROUP BY function is:

SELECT column , SUM(column) FROM table GROUP BY column


GROUP BY Example

With this SQL SELECT Company, SUM(Amount) FROM Sales


Returns this result:
This code is invalid
because the column
returned is not part of an
aggregate. A GROUP BY
clause will solve this
problem:
GROUP BY Example….

SELECT Company , SUM(Amount) FROM Sales GROUP BY Company


How to fix Error in Sql server 2014

 This error can occur, Because in the background may be


“MYSQLSERVER”and “SQL Server Browser is not running

 So to fix this error you need to start these services.

 Steps for starting these services:

 Go to Control Panel -->System & security  Administrator Tools—>


Services select “MYSQLSERVER” or “SQL SERVER BROWSER”
and double click on it

 Click on start Service

 Now login to SQL server with Windows authentication and use


user name and password.

You might also like