Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Some SQL Statements

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

SQL statements

Create : database and table


1. Create database dbname;
2. Create table tbname(attributes datatype size, att2 datatype size)
Example: Creating the database
CREATE DATABASE dbname
Creating the tables
CREATE TABLE Employee (
empId int (7) NOT NULL,
name varchar (30) NOT NULL,
sex char (1) NOT NULL,
bDate datetime NULL,
address varchar (50) NULL,
empDate datetime NULL,
position varchar (20) NULL,
salary float NULL
• insert
INSERT INTO <table_name>| <view_name> [(column_list)] data_values
Insert into employee values(1,’xx’,’f’,………….2000)
• Update
UPDATE Emplyees SET name=‘BBB', empDate='1-1-2001'
WHERE empID= 1
• Delete
DELETE FROM [Emplyees]
WHERE [empID] = 1
• Select
• All Data
SELECT [empId], [name], [sex], [bDate], [address], [empDate], [position], [salary]
FROM [Emplyees]
{SELECT * FROM [Emplyees]}

• Single Data
SELECT [empId], [name], [sex], [bDate], [address], [empDate], [position], [salary]
FROM [Emplyees]
WHERE [empId] = 1
Adding a Column to the Table
• ALTER TABLE table name ADD column name datatype;
• E.g. alter table employee add phonenumber int
Insert values into new attribute
• Update employee set phonenumber=097868999 where empid=25
Deleting the Column of the Table
ALTER table tablename DROP COLUMN column name;
Eg. Alter table employee DROP age
Joined Tables
• Reading data from more than one table
INNER JOIN
• INNER JOIN selects records that have matching values in both tables.
Eg. Select empname, depname
From employee inner join department on
employee.depid=department.depid
• LEFT JOIN
• LEFT JOIN selects records from the left table that match records in the
right table. (inner join + any additional information about left table
records)
Eg. Select empname, depname
From employee left join department on mployee.depid=department.depid
• RIGHT JOIN
• RIGHT JOIN selects records from the right table that match records in the
left table.(inner join + any additional information about right table records)
Eg. Select empname, depname
From employee right join department on mployee.depid=department.depid
Ordering Query Results
• Syntax:
SELECT <column_list>
FROM <table_list>
WHERE <condition>
ORDER BY {<order_column> [ASC | DESC]}[,..n]
e.g select * from employee where sex='f' order by fname ASC
Aggregate Function in SQL
SUM
• SUM returns the total sum of a numeric column.
Eg. Select SUM(age) from employee
AVG
• AVG returns the average value of a numeric column.
Eg. Select AVG(age) from employee
MIN
• MIN returns the minimum value of a numeric column
Eg. Select MIN(age) from employee
MAX
• MAX returns the maximum value of a numeric column.
Eg. Select MAX(age) from employee
COUNT
• COUNT returns the number of rows that match the specified criteria
Eg. Select COUNT(*) from employee

You might also like